Technical document

Quality Assurance Architecture to Suppress AI Agent Independent Review Round Trips and Converge to High-Quality Implementation

In AI agent development, when self-approval is eliminated and independent review is mandated, a common problem is the 'rework and re-pointing loop.' This article dissects its causes and explains a practical design that accelerates convergence through multi-layered defense: pre-emptive self-censorship, strict AST matching, fail-close confidential scanning, and machine-readable structured verification gates.
AI Development / Quality Assurance~16 minPublication Date September 22, 2026Update date November 23, 2026
How implementation agents and objective reviewers safely merge high-quality code through multi-layered defense gates.

Summary

Key points of this document

  • The Trap of 'Infinite Round Trips' Caused by Mandating Objective Reviews
  • Why Do Review Round Trips Not Stop? Three Essential Flaws Dissected
  • Multi-Layered Defense Architecture to Break the Round Trip Cycle (5 Pillars of Defense)

Overview

A system where AI agents perform implementation and another objective model conducts independent reviews is an effective safeguard for quality assurance. However, if mandated without sufficient defensive design, it can easily lead to a 'whack-a-mole' review cycle (bloated round counts) that continues for 10, 20 times. This article organizes the fundamental causes of rework and explains a practical architecture that suppresses rework and stabilizes quality through pre-emptive self-censorship, strict AST matching, confidential protection via isolated environments and full transmission scans, and structured verification gates with execution receipt matching.

The Trap of 'Infinite Round Trips' Caused by Mandating Objective Reviews

In autonomous coding using generative AI, one of the most critical risks to watch out for is 'Self-Approval.' If the agent that wrote the code approves it itself with 'This is fine,' it will inadvertently confirm misinterpretations of design assumptions, overlooked edge cases, and breaches of security boundaries.

To prevent this issue, an increasing number of sites are mandating objective reviews by an independent review model (a high-inference AI operating in an approved environment) that complies with external, vetted security standards. They also establish a 'Baseline Invariant' that prohibits merging until critical findings (Critical / High) are zero.

However, simply introducing this independent review as a rule leads to another serious problem: 'Bloated Review Round Counts (Round Trips).' For a single feature fix or rule revision, each time feedback is received from a reviewer, the code is modified and resubmitted, only to be pointed out for another flaw and modified again... This loop continues for 15, 25 rounds, wasting enormous tokens and time.

  • Danger of Self-Approval: It is difficult to spot blind spots in one's own code; independent review is essential.
  • Occurrence of Round Bloat: Simply mandating reviews can lead to a quagmire where feedback and rework rallies continue for over 20 rounds.
  • Requirements for Solution: An engineering mechanism is needed to smoothly converge to approval by suppressing unnecessary round trips, without compromising strict quality standards (zero Critical/High).

Why Do Review Round Trips Not Stop? Three Essential Flaws Dissected

Scrutinizing sites where review round trips are prolonged reveals that the cause is not so much the agent's implementation capability but rather three engineering flaws in the verification process.

The first flaw is 'Symptomatic Local Patches (Whack-a-Mole).' When a reviewer points out 'this input causes an exception,' the pattern is to add a local 'if' statement to the pointed-out line to gloss over it, without addressing the broken invariant or data structure distortion. Since the root cause is not resolved, it breaks again the moment the reviewer hits another boundary value in the next round.

The second flaw is 'Non-Deterministic Parsing and Ambiguous Instructions.' If the request to the reviewer is free-form and the pass/fail judgment is left to the subjective interpretation of humans or agents, the judgment can waver with slight changes in the reviewer's phrasing. Also, if regular expressions or general parsers are used for command or configuration validation, interpretation fluctuations due to inline comments or quotes can allow unverified defects to slip through, leading to rework.

The third flaw is 'Fail-Open Pre-Inspection.' A typical example is a design where, in a confidential information leakage check, the exit code specification of the grep command (0 on match, 1 on no match) is misunderstood, and the process passes without abnormal termination when a secret value is detected. If safety devices are fail-open, incomplete states are submitted for review, leading to inevitable rework due to obvious feedback from the reviewer.

  • Harm of Whack-a-Mole: Local conditional branch patches create new failures elsewhere, increasing round trips.
  • Trap of Non-Determinism: Free-form conversations and lenient parsers are breeding grounds for ambiguous pass/fail judgments and rework.
  • Danger of Fail-Open: If pre-inspection is bypassed, rework is guaranteed as unverified flaws will be discovered by the reviewer.

Multi-Layered Defense Architecture to Break the Round Trip Cycle (5 Pillars of Defense)

To fundamentally resolve this review round-trip problem, it is necessary to shift to an architecture where, instead of 'submitting to reviewers and then fixing,' we 'anticipate reviewers' thoughts, self-create and refute, and then submit after ensuring passage with mechanical gates (shift-left).'

In this quality assurance process, we will design and operate a multi-layered defense consisting of the following five pillars.

  • Pillar 1: Pre-flight Self-Audit Protocol — Simulate failure cases (null, empty values, boundary values, invalid state transitions, concurrency, authorization) that reviewers are likely to point out, and submit only after preparing defensive test code and empirical evidence (commands, exit codes, full pass records).
  • Pillar 2: Environment Isolation with Containers, etc., and Pre-transmission Fail-Close Secret Scan — Execute reviews on containers/temporary VMs or filesystem profiles that do not have access to the host's .env or private keys (git worktree on the same host is merely checkout separation and insufficient for read protection), and scan the entire external transmission payload. If even one detection occurs or an abnormal termination happens, prevent transmission with exit 1.
  • Pillar 3: Strict AST and Limited Grammar Whitelist (Strict Allowed Grammar AST) — Mechanically validate commands as a limited grammar AST that excludes dangerous flags (-s danger-...) and external input pipes, and only permits safe execution boundaries (-s read-only) and approved models.
  • Pillar 4: Cryptographic Hash Binding (Manifest & Invariant Binding) — Calculate a manifest hash by combining the relative paths and SHA-256 of all files under review (code, verification scripts, canonical specifications), and bind it inseparably with caller-specified parameters (Caller Invariants).
  • Pillar 5: Validation Gate with Structured Output Limitation and Execution Receipt Matching — Apply full anchor validation that does not allow free-form text mixing, or API structured output. After performing real model matching and schema validation of trusted execution metadata (API receipts), the gate program automatically determines the number of issues by severity (Critical=0, High=0).

Strict enforcement of 'environment isolation' and 'fail-close secret scanning,' which are often blind spots.

What is often overlooked in independent reviews is the prevention of sensitive information (Credentials / Secrets) leakage when sending prompts to external models. Even if you specify -s read-only as a safe execution boundary, this only prevents file modification in the local environment and does not prevent the risk of the model reading local .env or untracked files and quoting/transmitting them in its response.

A critically important engineering point here is that merely creating a git worktree or a clean separate branch checkout on the same host does not constitute a 'read isolation boundary.' The reviewer process can freely traverse parent directories (..), sibling directories, and shared .git object stores, thus still being able to read .env or secret files outside the working tree. To ensure true access blocking, containers (Docker / Podman) physically and logically separated from the host's secret information, disposable virtual machines (VMs), or OS-level filesystem access profiles (allow/deny profile or sandboxes) must be mandatory requirements, and worktrees should be positioned merely as aids for organizing working directories.

Furthermore, as a pre-transmission check, strict secret scanning is performed on the entire external transmission payload (including the request text and all lines, both added and deleted, of the Git diff). UNIX's grep returns 0 on match and 1 on no match, which creates a trap of inverted exit codes for simple shell commands. A dedicated scanner that exits with 1 on detection, 0 on no detection, and 1 on scan errors establishes fail-close protection.

Also, the scan regular expression is in .env format (KEY=val) as well as JSON format ("key": "val") and YAML format (key: val) key quotes. However, simple regex heuristics have inherent limitations in missing obfuscated secret values and unknown token formats. Therefore, in practice, it is recommended to use regex scanners for immediate local blocking (Layer 1) and to concurrently use entropy analysis tools such as gitleaks and trufflehog (Layer 2) in CI environments and dedicated pre-flights as a multi-layered defense.

// Example implementation of a fail-close secret scanner using TypeScript / Node.js
// scratch/secret_scanner.js
const fs = require("fs");
const assert = require("assert");

// Detection patterns for JSON ("key": "val"), YAML (key: val), and env (KEY=val)
const SECRET_PATTERNS = [
  /ghp_[0-9a-zA-Z]{36}/,                                                   // GitHub Classic PAT
  /github_pat_[0-9a-zA-Z_]{82}/,                                           // GitHub Fine-grained PAT
  /AKIA[0-9A-Z]{16}/,                                                      // AWS Access Key ID
  /["']?aws_secret_access_key["']?\s*[:=]\s*['"]?[0-9a-zA-Z/+]{40}['"]?/i, // AWS Secret Access Key
  /-----BEGIN [A-Z ]*PRIVATE KEY-----/,                                    // Private Keys (RSA/EC/OpenSSH)
  /Bearer\s+[a-zA-Z0-9_.-]{20,}/,                                         // Bearer Tokens
];

// Key-value secret information pattern (with placeholder exclusion)
const KV_SECRET_PATTERN = /["']?(?:password|secret|secret_key|api_key|access_token|private_key)["']?\s*[:=]\s*['"]?([^\s'";#]{8,})['"]?/gi;

// Allowlist for safe environment variable references and placeholders
const SAFE_PLACEHOLDER_PATTERN = /^(\$\{[A-Z0-9_]+\}|<REDACTED>|placeholder|changeme|example[a-z0-9_]*|dummy[a-z0-9_]*)$/i;

function scanText(text, sourceName) {
  // 1. Scan for fixed-format tokens
  for (const pattern of SECRET_PATTERNS) {
    if (pattern.test(text)) {
      console.error(`CRITICAL_SECRET_DETECTED in ${sourceName}: matches ${pattern}`);
      process.exit(1);
    }
  }

  // 2. Scan for key-value format (safely excluding placeholders and environment variable references)
  let match;
  while ((match = KV_SECRET_PATTERN.exec(text)) !== null) {
    const value = match[1];
    if (!SAFE_PLACEHOLDER_PATTERN.test(value)) {
      console.error(`CRITICAL_SECRET_DETECTED in ${sourceName}: candidate key with value "${value}"`);
      process.exit(1);
    }
  }
}

function main() {
  const args = process.argv.slice(2);
  if (args.length < 2) {
    console.error("Usage: node secret_scanner.js <prompt_file> <diff_file>");
    process.exit(1);
  }

  try {
    // 1. Scan the entire prompt text
    const promptText = fs.readFileSync(args[0], "utf8");
    scanText(promptText, "prompt payload");

    // 2. Scan the entire diff text (all lines, including added and deleted lines) to be sent externally
    const diffText = fs.readFileSync(args[1], "utf8");
    scanText(diffText, "git diff payload");

    console.log("PASS: Pre-flight Secret Scan succeeded without findings.");
    process.exit(0);
  } catch (err) {
    console.error("SCANNER_ERROR:", err.message);
    process.exit(1); // Fail-close and block even on file read failure or unexpected exceptions
  }
}

main();

Validation Gate with Structured Output Only and Cryptographic Receipt Verification

The biggest key to quickly converging review rounds is to elevate the pass/fail judgment of reviews from natural language interactions to 'machine-verifiable structured gates'.

An important note here is that the model names and counts within the json:review_result output by the model itself are merely 'self-reported'. If an unauthorized model is accidentally activated, or if the summary count is misrepresented as high: 0 despite serious issues in the main text, blindly trusting self-reported numbers will break invariants.

Furthermore, we must prevent deceptive patterns where the model describes serious issues outside the JSON block (in free-form text before and after) and makes the JSON block appear as 'no issues (high: 0, findings: [])'. Therefore, we either directly use API-level structured output (response_format: { type: "json_schema" }) or, in CLI output validation, strictly verify that the entire response consists of a single structured block only (a perfect match anchor that allows no free-form text or comments before or after).

Also, when verifying the execution receipt (executionReceipt), simply matching the model name or plaintext hash is insufficient. With unkeyed plaintext receipts, malicious agents or unauthorized processes can forge fixed issuer strings and response hashes. Therefore, a digital signature using asymmetric public-key cryptography (e.g., Ed25519) is applied with the private key of an independently managed review runner. The gate then verifies the authenticity of the issuer using the runner's public key, and then cross-references the recorded target identifier (target_identifier) and the cryptographic hash of the entire response text (response_digest) in a three-way match. Furthermore, individual structured findings (findings) fully validates each element according to the schema, recalculates the number of issues by severity at the gate, and reconciles them.

// Specification for the Structured Review Result Schema (json:review_result)
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "ReviewResult",
  "type": "object",
  "additionalProperties": false,
  "required": [
    "target_identifier",
    "reviewer_model",
    "completion_state",
    "severity_counts",
    "findings"
  ],
  "properties": {
    "target_identifier": {
      "type": "string",
      "description": "Commit ID, diff SHA-256, or target manifest SHA-256 of the item under review"
    },
    "reviewer_model": {
      "type": "string",
      "enum": ["approved-reviewer-primary", "approved-reviewer-secondary"]
    },
    "completion_state": {
      "type": "string",
      "enum": ["DONE", "BLOCKED"]
    },
    "severity_counts": {
      "type": "object",
      "additionalProperties": false,
      "required": ["critical", "high", "medium", "low", "advisory"],
      "properties": {
        "critical": { "type": "integer", "minimum": 0 },
        "high": { "type": "integer", "minimum": 0 },
        "medium": { "type": "integer", "minimum": 0 },
        "low": { "type": "integer", "minimum": 0 },
        "advisory": { "type": "integer", "minimum": 0 }
      }
    },
    "findings": {
      "type": "array",
      "items": {
        "type": "object",
        "additionalProperties": false,
        "required": ["id", "severity", "title"],
        "properties": {
          "id": { "type": "string" },
          "severity": {
            "type": "string",
            "enum": ["critical", "high", "medium", "low", "advisory"]
          },
          "title": { "type": "string" }
        }
      }
    }
  }
}
// Validation Gate with signature authentication, tripartite receipt verification, and full findings validation
// Excerpt from validate_review_gate.js
const crypto = require("crypto");
const assert = require("assert");

function validateReviewGate(reviewText, executionReceipt, expectedTargetIdentifier, approvedModelList, runnerPublicKey) {
  // 1. Authenticity verification of signature using independently managed runner key (mathematically prevents receipt self-forgery)
  const signedPayload = `${executionReceipt.issuer}:${executionReceipt.actual_model}:${executionReceipt.target_identifier}:${executionReceipt.response_digest}`;
  const isValidSignature = crypto.verify(
    null,
    Buffer.from(signedPayload),
    runnerPublicKey,
    Buffer.from(executionReceipt.signature, "hex")
  );
  assert(isValidSignature, "INVALID_RECEIPT_SIGNATURE");

  assert.strictEqual(executionReceipt.issuer, "secure-review-runner", "UNTRUSTED_RECEIPT_ISSUER");
  assert(approvedModelList.includes(executionReceipt.actual_model), "UNAPPROVED_EXECUTION_MODEL");
  assert.strictEqual(executionReceipt.target_identifier, expectedTargetIdentifier, "RECEIPT_TARGET_MISMATCH");

  const actualResponseDigest = crypto.createHash("sha256").update(reviewText).digest("hex");
  assert.strictEqual(executionReceipt.response_digest, actualResponseDigest, "RECEIPT_RESPONSE_DIGEST_MISMATCH");

  // 2. Full anchor validation that the entire response consists of only a single structured block (prevents mixing of free-form text before/after)
  const trimmed = reviewText.trim();
  const fullMatch = trimmed.match(/^```json:review_result\s*\n([\s\S]*?)\n```$/);
  assert(fullMatch, "GATE_FAILED: Response must exclusively contain a single json:review_result block without external text");

  // 3. JSON parsing and full top-level validation (reject unknown properties)
  const data = JSON.parse(fullMatch[1]);
  const allowedKeys = ["completion_state", "findings", "reviewer_model", "severity_counts", "target_identifier"].sort();
  assert.deepStrictEqual(Object.keys(data).sort(), allowedKeys, "Unknown top-level keys");

  assert(typeof data.target_identifier === "string", "target_identifier must be string");
  assert.strictEqual(data.target_identifier, expectedTargetIdentifier, "Target SHA mismatch");
  assert.strictEqual(data.reviewer_model, executionReceipt.actual_model, "Model mismatch with receipt");
  assert.strictEqual(data.completion_state, "DONE", "Completion state must be DONE");

  const sev = data.severity_counts;
  assert(sev && typeof sev === "object" && !Array.isArray(sev), "severity_counts must be object");
  const allowedSevKeys = ["advisory", "critical", "high", "low", "medium"].sort();
  assert.deepStrictEqual(Object.keys(sev).sort(), allowedSevKeys, "Unknown severity keys");

  for (const k of allowedSevKeys) {
    assert(typeof sev[k] === "number" && Number.isInteger(sev[k]) && sev[k] >= 0, `${k} must be non-negative integer`);
  }

  // 4. Full schema validation of structured findings (required: id, severity, title / additionalProperties: false)
  assert(Array.isArray(data.findings), "findings must be an array");
  const allowedFindingKeys = ["id", "severity", "title"].sort();
  const computedCounts = { advisory: 0, critical: 0, high: 0, low: 0, medium: 0 };

  for (const finding of data.findings) {
    assert(finding && typeof finding === "object" && !Array.isArray(finding), "finding must be an object");
    assert.deepStrictEqual(Object.keys(finding).sort(), allowedFindingKeys, "Unknown or missing keys in finding");
    assert(typeof finding.id === "string" && finding.id.length > 0, "finding.id must be non-empty string");
    assert(typeof finding.title === "string" && finding.title.length > 0, "finding.title must be non-empty string");
    assert(allowedSevKeys.includes(finding.severity), `Invalid finding severity: ${finding.severity}`);
    computedCounts[finding.severity]++;
  }

  // 5. Verify exact match between re-calculated counts from findings and self-declared counts
  for (const k of allowedSevKeys) {
    assert.strictEqual(
      sev[k],
      computedCounts[k],
      `COUNT_MISMATCH for ${k}: declared=${sev[k]}, computed from findings=${computedCounts[k]}`
    );
  }

  // 6. Machine determination of Baseline Invariant (Critical / High must be zero)
  if (computedCounts.critical > 0 || computedCounts.high > 0) {
    throw new Error(`GATE_BLOCKED: Critical=${computedCounts.critical}, High=${computedCounts.high} (must be 0)`);
  }
  return { status: "PASSED", computedCounts };
}

Multi-repository compatibility and exception stopping (BLOCKED) operation

To operate as a global guideline across all company projects, it is essential to design operations that absorb environmental differences in individual repositories while maintaining security boundaries.

For example, if the default branch specification in integrated diff reviews is fixed to "--base main", reviews will become impossible for repositories where the default branch is "master" or "develop", or those based on release tags. Therefore, we adopt a design that dynamically resolves the default branch from Git's symbolic references ("git symbolic-ref refs/remotes/origin/HEAD") and passes it as an argument after verifying its validity using Git's own reference validation (equivalent to "git check-ref-format --branch").

Furthermore, fallback provisions are extremely important for cases where independent reviews cannot be received due to external network outages or API rate limits. If exceptions like 'merging with self-approval because the review isn't working' are allowed in any emergency, the quality assurance baseline will instantly become a mere formality. When delegation is not possible, self-approval is prohibited, the work is temporarily stopped (BLOCKED), escalated to a human, and a fail-safe operation is thoroughly enforced to await external environment recovery or to decide on switching to an approved model from a different system.

  • Dynamic resolution of default branch: Eliminates fixed 'main' and resolves and passes a valid default branch name verified by git check-ref-format, etc.
  • Absolute prohibition of self-approval: Even when the review system fails, bypassing with self-approval is prohibited, and operations are stopped with BLOCKED.
  • Prohibition of easy same-system fallback: Eliminates superficial switching to aliases or same-platform models, strictly adhering to truly independent approval paths or temporary suspension (BLOCKED).

Summary: From 'Spirit' to 'Machine-Executable Gates'

In modern development environments where automation by AI agents is advancing, merely describing rules and codes of conduct as 'natural language in prompts (spirit)' cannot fully prevent agent interpretation fluctuations or symptomatic rework.

The key to reliably establishing Quality Assurance Baseline Invariants lies in elevating conventions into machine-executable programs (deterministic AST validation, fail-close secret scanners in isolated environments, structured validation gates with execution receipt reconciliation), and enclosing the agent's own actions with engineering guardrails.

By preemptively crushing counterexamples with pre-self-censorship and strictly determining pass/fail with structured validation gates, this multi-layered defense architecture allows humans to truly trust the autonomous implementation of AI agents and achieve efficient release cycles with reduced rework.

  • Limitations of 'Spirit': Instructions like 'review carefully' alone cannot prevent back-and-forth rework.
  • Engineering Guardrails: Mechanically arranging AST validation, secret scanning, and structured validation gates in series prevents rework proactively.
  • Balancing Trust and Speed: The existence of strict validation gates is the foundation for expanding the scope of delegation to agents and stabilizing development quality.

Technical documents

We will continue to increase technical documentation.

We will continue to organize our thoughts on AI, cloud, business app development, requirements definition, and operational design into documents.

Go to technical documentation list