Skip to content

Adonis0123/adonis-skills / skills/agentic-review-handoff

agentic-review-handoff

Verified

Validate pasted review findings before fixes; run same-session automatic Git review-fix-re-review with a headless Reviewer and no redundant confirmation; start fresh-eyes Git diff Review Intake; resume review-loop sessions or packets; get a DecisionConsult from another AI; or run first-principles/DDD/high-cohesion review. Requires Git and review/consult intent; ordinary implementation or commit-only requests do not start a review loop.

scripts/review-loop/schema.mjs

View on GitHub
/**
 * Fail-closed Reviewer output parsers for auto loop.
 *
 * Round 1 (Review Findings): findings + Verdict
 * Round ≥2 (Re-review): prior reassessment + New Findings + Regression Surface + Verdict
 */

const VERDICTS = new Set([
  "PASS",
  "PASS_WITH_CONCERNS",
  "BLOCKED",
  "NO_FINDINGS",
]);

const VERDICT_TOKEN = "PASS_WITH_CONCERNS|PASS|BLOCKED|NO_FINDINGS";

/**
 * Collect all physical Verdict declarations in document order.
 * @param {string} text
 * @returns {string[]}
 */
export function collectVerdicts(text) {
  /** @type {string[]} */
  const found = [];
  const lines = String(text).split("\n");
  for (let i = 0; i < lines.length; i += 1) {
    const line = lines[i].trim();
    let m = line.match(
      new RegExp(
        `^(?:\\*\\*)?Verdict(?:\\*\\*)?\\s*[::]\\s*(${VERDICT_TOKEN})\\b`,
        "i",
      ),
    );
    if (m) {
      found.push(m[1].toUpperCase());
      continue;
    }
    // ## Verdict\n[blank lines]\nVALUE
    if (/^##\s*Verdict\s*$/i.test(line)) {
      for (let j = i + 1; j < lines.length; j += 1) {
        const next = lines[j].trim();
        if (!next) continue;
        m = next.match(new RegExp(`^(${VERDICT_TOKEN})$`, "i"));
        if (m) found.push(m[1].toUpperCase());
        break;
      }
    }
  }
  return found;
}

/**
 * Exactly one terminal Verdict (F5).
 * @param {string} text
 * @returns {string|null}
 */
export function extractVerdict(text) {
  const all = collectVerdicts(text);
  if (all.length === 0) return null;
  if (all.length !== 1) return null; // malformed: caller sees missing/invalid
  // F5: last non-empty line must be the declaration itself:
  //   - `Verdict: TOKEN`, or
  //   - bare TOKEN only when immediately preceded by `## Verdict`
  const lines = String(text)
    .split("\n")
    .map((l) => l.trim())
    .filter(Boolean);
  if (lines.length < 1) return null;
  const last = lines.at(-1) ?? "";
  const prev = lines.at(-2) ?? "";
  const labeled = last.match(
    new RegExp(
      `^(?:\\*\\*)?Verdict(?:\\*\\*)?\\s*[::]\\s*(${VERDICT_TOKEN})$`,
      "i",
    ),
  );
  const bare =
    !labeled &&
    new RegExp(`^(${VERDICT_TOKEN})$`, "i").test(last) &&
    /^##\s*Verdict$/i.test(prev)
      ? last.match(new RegExp(`^(${VERDICT_TOKEN})$`, "i"))
      : null;
  const m = labeled || bare;
  if (!m) return null;
  if (m[1].toUpperCase() !== all[0]) return null;
  return all[0];
}

/**
 * Parse a markdown pipe table into rows of objects keyed by header.
 * Fail-closed metadata: when a data row's cell count ≠ header count (typical unescaped `|`
 * in evidence/code), set `columnMismatch` so callers can refuse silent field shifts.
 * @param {string} text
 * @returns {{ headers: string[], rows: Record<string,string>[], columnMismatch: null|{rowIndex:number,expected:number,actual:number} }[]}
 */
export function parseMarkdownTables(text) {
  const lines = String(text).split("\n");
  /** @type {{ headers: string[], rows: Record<string,string>[], columnMismatch: null|{rowIndex:number,expected:number,actual:number} }[]} */
  const tables = [];
  for (let i = 0; i < lines.length; i += 1) {
    if (!/^\s*\|/.test(lines[i])) continue;
    const headerCells = splitRow(lines[i]);
    if (!headerCells.length) continue;
    const next = lines[i + 1] ?? "";
    if (!/^\s*\|?\s*:?-{3,}/.test(next)) continue;
    const headers = headerCells.map(normalizeHeader);
    /** @type {Record<string,string>[]} */
    const rows = [];
    /** @type {null|{rowIndex:number,expected:number,actual:number}} */
    let columnMismatch = null;
    i += 2;
    while (i < lines.length && /^\s*\|/.test(lines[i])) {
      const cells = splitRow(lines[i]);
      if (cells.every((c) => /^[-:]+$/.test(c))) {
        i += 1;
        continue;
      }
      if (cells.length !== headers.length && !columnMismatch) {
        columnMismatch = {
          rowIndex: rows.length,
          expected: headers.length,
          actual: cells.length,
        };
      }
      /** @type {Record<string,string>} */
      const row = {};
      headers.forEach((h, idx) => {
        row[h] = (cells[idx] ?? "").trim();
      });
      rows.push(row);
      i += 1;
    }
    i -= 1;
    tables.push({ headers, rows, columnMismatch });
  }
  return tables;
}

function splitRow(line) {
  const raw = line.trim().replace(/^\|/, "").replace(/\|$/, "");
  return raw.split("|").map((c) => c.trim());
}

function normalizeHeader(h) {
  return String(h).trim().toLowerCase().replace(/\s+/g, " ");
}

/**
 * First-round / New Findings table column contract (auto-loop-contract.md).
 * Each entry lists accepted header aliases (already compared after normalizeHeader).
 */
const FINDINGS_TABLE_COLUMNS = [
  { label: "ID", aliases: ["id", "finding id", "finding_id"] },
  { label: "Severity", aliases: ["严重度", "severity", "sev"] },
  { label: "Summary", aliases: ["标题", "title", "summary"] },
  { label: "Evidence", aliases: ["证据", "evidence"] },
  {
    label: "Target files",
    aliases: ["target files", "target file", "files", "target"],
  },
  { label: "Required fix", aliases: ["required fix", "fix", "required"] },
  {
    label: "Acceptance check",
    aliases: ["acceptance check", "acceptance", "check"],
  },
];

/**
 * @param {string[]} headers already normalizeHeader'd
 * @returns {string[]} missing column labels
 */
export function missingFindingsTableColumns(headers) {
  const set = new Set((headers || []).map((h) => normalizeHeader(h)));
  /** @type {string[]} */
  const missing = [];
  for (const col of FINDINGS_TABLE_COLUMNS) {
    if (!col.aliases.some((a) => set.has(normalizeHeader(a)))) {
      missing.push(col.label);
    }
  }
  return missing;
}

/**
 * @param {Record<string,string>} row
 */
export function findingFromRow(row) {
  const id = row.id || row["finding id"] || row["finding_id"] || "";
  const severity = row["严重度"] || row.severity || row["sev"] || "";
  const title = row["标题"] || row.title || row.summary || "";
  const evidence = row["证据"] || row.evidence || "";
  const target =
    row["target files"] ||
    row["target file"] ||
    row.files ||
    row["target"] ||
    "";
  const required = row["required fix"] || row.fix || row["required"] || "";
  const acceptance =
    row["acceptance check"] || row.acceptance || row["check"] || "";
  return {
    id: String(id).trim(),
    severity: String(severity).trim(),
    title: String(title).trim(),
    evidence: String(evidence).trim(),
    targetFiles: String(target).trim(),
    requiredFix: String(required).trim(),
    acceptanceCheck: String(acceptance).trim(),
    blocking:
      /阻塞|blocking|blocker/i.test(severity) &&
      !/非阻塞|non-?blocking/i.test(severity),
  };
}

/**
 * Validate first-round Review Findings output.
 * @param {string} text
 * @returns {{ ok: true, verdict: string, findings: ReturnType<typeof findingFromRow>[] } | { ok: false, error: string }}
 */
export function parseReviewFindings(text) {
  const verdict = extractVerdict(text);
  if (!verdict || !VERDICTS.has(verdict)) {
    return {
      ok: false,
      error:
        "missing or invalid Verdict (expected PASS|PASS_WITH_CONCERNS|BLOCKED|NO_FINDINGS)",
    };
  }

  const tables = parseMarkdownTables(text);
  const findingsTable = tables.find((t) =>
    t.headers.some((h) => h === "id" || h === "finding id"),
  );
  // Always require a findings table (PASS may use a single (none) row)
  if (!findingsTable) {
    return { ok: false, error: "missing findings table with ID column" };
  }
  // Fail-closed: same full column set as re-review New Findings (reject ID-only stubs)
  const missingCols = missingFindingsTableColumns(findingsTable.headers);
  if (missingCols.length) {
    return {
      ok: false,
      error: `findings table missing columns required by first-round schema: ${missingCols.join(", ")}`,
    };
  }
  if (findingsTable.columnMismatch) {
    const m = findingsTable.columnMismatch;
    return {
      ok: false,
      error: `findings table column count mismatch at data row ${m.rowIndex}: expected ${m.expected} cells, got ${m.actual} (unescaped | in a cell?)`,
    };
  }

  /** @type {ReturnType<typeof findingFromRow>[]} */
  let findings = findingsTable.rows.map(findingFromRow).filter((f) => f.id);

  // Filter placeholder (none) rows for field validation
  const realFindings = findings.filter(
    (f) => f.id && f.id !== "(none)" && !/^[-—]+$/.test(f.id),
  );

  if (verdict === "BLOCKED" || verdict === "PASS_WITH_CONCERNS") {
    if (!realFindings.length) {
      return {
        ok: false,
        error: `${verdict} requires at least one finding row with ID`,
      };
    }
  }

  for (const f of realFindings) {
    if (!f.title || !f.severity) {
      return { ok: false, error: `finding ${f.id} missing title or severity` };
    }
    if (
      !/^\[(阻塞|非阻塞)\]$/.test(f.severity) &&
      !/^(blocking|non-?blocking)$/i.test(f.severity)
    ) {
      return {
        ok: false,
        error: `finding ${f.id} severity must be [阻塞] or [非阻塞] (got "${f.severity}")`,
      };
    }
    if (!f.evidence || !f.requiredFix || !f.acceptanceCheck) {
      return {
        ok: false,
        error: `finding ${f.id} missing evidence/required fix/acceptance check`,
      };
    }
    // Fail-closed: every finding (blocking and non-blocking) must name Target files
    if (!f.targetFiles) {
      return { ok: false, error: `finding ${f.id} missing Target files` };
    }
  }

  const blocking = realFindings.filter((f) => f.blocking);
  findings = realFindings;
  if (verdict === "PASS" || verdict === "NO_FINDINGS") {
    if (blocking.length) {
      return { ok: false, error: `${verdict} cannot include [阻塞] findings` };
    }
  }

  if (verdict === "PASS_WITH_CONCERNS") {
    if (blocking.length) {
      return {
        ok: false,
        error:
          "PASS_WITH_CONCERNS only allowed when all remaining findings are non-blocking",
      };
    }
  }

  if (verdict === "BLOCKED") {
    if (!blocking.length) {
      return {
        ok: false,
        error: "BLOCKED requires at least one [阻塞] finding",
      };
    }
  }

  return { ok: true, verdict, findings };
}

/**
 * Validate re-review output (round ≥ 2).
 * @param {string} text
 * @param {string[]} priorFindingIds
 * @param {{ priorBlockingIds?: string[] }} [opts]
 */
export function parseReReview(text, priorFindingIds = [], opts = {}) {
  const verdict = extractVerdict(text);
  if (!verdict || !VERDICTS.has(verdict)) {
    return { ok: false, error: "missing or invalid Verdict on re-review" };
  }

  // Prior findings reassessment: need status per prior ID when priors exist
  const lower = String(text).toLowerCase();
  if (
    !/prior findings reassessment|prior finding|复评|reassessment/i.test(
      text,
    ) &&
    priorFindingIds.length
  ) {
    return {
      ok: false,
      error: "re-review missing Prior Findings Reassessment section",
    };
  }
  if (!/new findings/i.test(lower) && !/新增/i.test(text)) {
    // allow empty new findings if section header present
    if (!/##\s*new findings/i.test(text)) {
      return { ok: false, error: "re-review missing New Findings section" };
    }
  }
  if (!/regression surface/i.test(lower) && !/回归/i.test(text)) {
    return { ok: false, error: "re-review missing Regression Surface section" };
  }

  // Exact section only — do not scan unrelated tables for reassessment rows
  let priorSectionBody = "";
  const engPrior = String(text).split(/##\s*Prior Findings Reassessment/i);
  if (engPrior.length >= 2) {
    priorSectionBody = engPrior[1].split(/##\s+/)[0] ?? "";
  } else {
    const zhPrior = String(text).split(/##\s*复评/i);
    if (zhPrior.length >= 2) {
      priorSectionBody = zhPrior[1].split(/##\s+/)[0] ?? "";
    } else if (priorFindingIds.length) {
      return {
        ok: false,
        error: "re-review missing Prior Findings Reassessment section body",
      };
    }
  }
  /** @type {{ id: string, status: string, evidence: string }[]} */
  const reassessments = [];
  for (const t of parseMarkdownTables(priorSectionBody)) {
    const idKey = t.headers.find((h) => h === "id" || h === "finding id");
    const statusKey = t.headers.find((h) => /status|状态|result/.test(h));
    if (!idKey || !statusKey) continue;
    for (const row of t.rows) {
      const id = String(row[idKey] ?? "").trim();
      const status = String(row[statusKey] ?? "").trim();
      if (!id || id === "(none)" || /^[-—]+$/.test(id)) continue;
      if (/^(resolved|partially|unresolved)$/i.test(status)) {
        const evidence =
          row.evidence || row["复核证据"] || row["evidence"] || "";
        if (!String(evidence).trim() || evidence === "—") {
          return {
            ok: false,
            error: `reassessment for ${id} missing 复核证据`,
          };
        }
        reassessments.push({
          id,
          status: status.toLowerCase(),
          evidence: String(evidence).trim(),
        });
      } else if (/^(partial|fixed|open)$/i.test(status)) {
        return {
          ok: false,
          error: `invalid reassessment status "${status}" for ${id} (use resolved|partially|unresolved)`,
        };
      }
    }
  }

  // Exact-once: no duplicate reassessment IDs
  const reassessIds = reassessments.map((r) => r.id);
  const reassessSet = new Set(reassessIds);
  if (reassessSet.size !== reassessIds.length) {
    const dups = reassessIds.filter((id, i) => reassessIds.indexOf(id) !== i);
    return {
      ok: false,
      error: `duplicate reassessment id(s): ${[...new Set(dups)].join(", ")}`,
    };
  }
  // Exact set equality with priorFindingIds when priors exist
  if (priorFindingIds.length) {
    const priorSet = new Set(priorFindingIds);
    for (const id of priorFindingIds) {
      if (!reassessSet.has(id)) {
        return {
          ok: false,
          error: `re-review missing reassessment for prior finding ${id}`,
        };
      }
    }
    for (const id of reassessSet) {
      if (!priorSet.has(id)) {
        return {
          ok: false,
          error: `reassessment id ${id} is not in prior finding set`,
        };
      }
    }
  }

  // New Findings: same schema as round 1 — full column set + table (use (none) row if empty)
  /** @type {ReturnType<typeof findingFromRow>[]} */
  let newFindings = [];
  const newSectionMatch = String(text).split(/##\s*New Findings/i);
  if (newSectionMatch.length < 2) {
    return { ok: false, error: "re-review missing New Findings section" };
  }
  const newSectionBody = newSectionMatch[1].split(/##\s+/)[0] ?? "";
  const newTables = parseMarkdownTables(newSectionBody);
  const newFindingsTable = newTables.find((t) =>
    t.headers.some((h) => h === "id" || h === "finding id"),
  );
  if (!newFindingsTable) {
    return {
      ok: false,
      error:
        "New Findings must include findings table with ID column (use a single (none) row if empty)",
    };
  }
  // Fail-closed: table must carry the same column set as first-round findings schema
  // (reject `| ID |` only stubs that would parse as ok with empty rows).
  const missingCols = missingFindingsTableColumns(newFindingsTable.headers);
  if (missingCols.length) {
    return {
      ok: false,
      error: `New Findings table missing columns required by first-round schema: ${missingCols.join(", ")}`,
    };
  }
  if (newFindingsTable.columnMismatch) {
    const m = newFindingsTable.columnMismatch;
    return {
      ok: false,
      error: `New Findings table column count mismatch at data row ${m.rowIndex}: expected ${m.expected} cells, got ${m.actual} (unescaped | in a cell?)`,
    };
  }
  newFindings = newFindingsTable.rows
    .map(findingFromRow)
    .filter((f) => f.id && f.id !== "(none)" && !/^[-—]+$/.test(f.id));
  // New Findings IDs unique among themselves
  const newIds = newFindings.map((f) => f.id);
  if (new Set(newIds).size !== newIds.length) {
    return { ok: false, error: "New Findings contains duplicate finding ids" };
  }
  // New Findings must not intersect prior / reassessment IDs
  for (const id of newIds) {
    if (priorFindingIds.includes(id) || reassessSet.has(id)) {
      return {
        ok: false,
        error: `New Findings id ${id} collides with prior/reassessment ids`,
      };
    }
  }
  for (const f of newFindings) {
    if (!f.title || !f.severity) {
      return {
        ok: false,
        error: `new finding ${f.id} missing title or severity`,
      };
    }
    if (
      !/^\[(阻塞|非阻塞)\]$/.test(f.severity) &&
      !/^(blocking|non-?blocking)$/i.test(f.severity)
    ) {
      return {
        ok: false,
        error: `new finding ${f.id} severity must be [阻塞] or [非阻塞]`,
      };
    }
    // Round ≥2: only load-bearing blockers allowed as new findings
    if (!f.blocking) {
      return {
        ok: false,
        error: `new finding ${f.id} must be [阻塞] on re-review (non-blocking not allowed)`,
      };
    }
    if (!f.evidence || !f.requiredFix || !f.acceptanceCheck || !f.targetFiles) {
      return {
        ok: false,
        error: `new blocking finding ${f.id} missing evidence/target files/required fix/acceptance check`,
      };
    }
  }

  // Extract Regression Surface body (preserve reviewer text; never invent "none")
  let regressionSurface = "";
  const regSplit = String(text).split(/##\s*Regression Surface/i);
  if (regSplit[1]) {
    regressionSurface = regSplit[1].split(/##\s+/)[0].trim();
    // Strip trailing verdict block if nested
    regressionSurface = regressionSurface
      .replace(/##\s*Verdict[\s\S]*$/i, "")
      .replace(/^Verdict\s*[::].*$/im, "")
      .trim();
  }
  if (!regressionSurface) {
    return {
      ok: false,
      error: "re-review Regression Surface section is empty",
    };
  }
  try {
    assertNoInjectedH1(regressionSurface, "Regression Surface");
  } catch (err) {
    return {
      ok: false,
      error: err instanceof Error ? err.message : String(err),
    };
  }

  const unresolved = reassessments.filter(
    (r) => r.status === "unresolved" || r.status === "partially",
  );
  const newBlocking = newFindings.filter((f) => f.blocking);
  // F1: only prior *blocking* IDs gate PASS (explicit list; empty means none blocking)
  const priorBlocking = new Set(
    Array.isArray(opts.priorBlockingIds)
      ? opts.priorBlockingIds
      : priorFindingIds,
  );
  const unresolvedBlocking = unresolved.filter((r) => priorBlocking.has(r.id));
  if (verdict === "PASS" || verdict === "NO_FINDINGS") {
    if (unresolvedBlocking.length || newBlocking.length) {
      return {
        ok: false,
        error: `${verdict} rejected: unresolved/partially prior blockers or new blockers present`,
      };
    }
  }
  if (verdict === "PASS_WITH_CONCERNS") {
    if (newBlocking.length) {
      return {
        ok: false,
        error: "PASS_WITH_CONCERNS cannot include new [阻塞] findings",
      };
    }
    if (unresolvedBlocking.length) {
      return {
        ok: false,
        error:
          "PASS_WITH_CONCERNS rejected: unresolved/partially prior blockers remain (must BLOCKED)",
      };
    }
  }
  if (
    verdict === "BLOCKED" &&
    !unresolvedBlocking.length &&
    !newBlocking.length
  ) {
    return {
      ok: false,
      error:
        "BLOCKED re-review requires unresolved prior blocker or new blocker",
    };
  }

  return {
    ok: true,
    verdict,
    reassessments,
    newFindings,
    regressionSurface,
  };
}

/**
 * Reject top-level H1 injection in free-form reviewer prose (F2).
 * @param {string} text
 */
export function assertNoInjectedH1(text, label = "section") {
  const lines = String(text).split("\n");
  for (const line of lines) {
    if (/^# [^#\n]/.test(line.trim())) {
      throw new Error(
        `${label} must not contain top-level H1 lines (got: ${line.trim().slice(0, 60)})`,
      );
    }
  }
  return text;
}

/**
 * Convert parsed first-round findings into packet markdown stages.
 * @param {{ verdict: string, findings: ReturnType<typeof findingFromRow>[], reviewer: string, baseSha: string, evidencePath: string, requireFixHandoff?: boolean }} parsed
 */
export function formatReviewFindingsStage(parsed) {
  const {
    verdict,
    findings,
    reviewer,
    baseSha,
    evidencePath,
    requireFixHandoff = false,
  } = parsed;
  const rows =
    findings.length === 0
      ? "| (none) | — | No findings | — | — | — | — |"
      : findings
          .map(
            (f) =>
              `| ${f.id} | ${f.severity} | ${f.title} | ${f.evidence} | ${f.targetFiles} | ${f.requiredFix} | ${f.acceptanceCheck} |`,
          )
          .join("\n");

  let md = `# Review Findings

## Scope reviewed

- Auto loop frozen evidence: \`${evidencePath}\`
- Base SHA: \`${baseSha}\`
- Reviewer: ${reviewer}

## Verification

- Evidence file read by Reviewer (headless)
- Schema fail-closed parse of findings + Verdict

## Findings

| ID | 严重度 | 标题 | 证据 | Target files | Required fix | Acceptance check |
|---|---|---|---|---|---|---|
${rows}

## Verdict

${verdict}
`;

  // completion=pass treats non-blocking concerns as work, so it also needs a handoff.
  if (verdict === "BLOCKED" || requireFixHandoff) {
    const handoffRows = findings
      .map(
        (f) =>
          `| ${f.id} | ${f.severity} | ${f.title} | ${f.targetFiles} | ${f.requiredFix} | ${f.acceptanceCheck} |`,
      )
      .join("\n");
    md += `
# Fix Handoff

## Scope

- Findings from auto loop round review
- Evidence: \`${evidencePath}\`

## Validated findings to fix

| ID | 严重度 | 标题 | Target files | Required fix | Acceptance check |
|---|---|---|---|---|---|
${handoffRows}

## Constraints

- Fix only listed findings; do not broaden scope

## Verification required

- Per-finding Acceptance check in table above

## Required fix agent output

- Append \`# Fix Completion\` via \`review-loop fix-completion\`
`;
  }
  return md.trim() + "\n";
}

/**
 * @param {{
 *   verdict: string,
 *   reassessments: {id:string,status:string,evidence:string}[],
 *   newFindings: ReturnType<typeof findingFromRow>[],
 *   reviewer: string,
 *   round: number,
 *   evidencePath: string,
 * }} parsed
 */
export function formatReReviewStage(parsed) {
  const title =
    parsed.round > 2 ? `# Re-review (round ${parsed.round})` : "# Re-review";
  const reRows =
    parsed.reassessments.length === 0
      ? "| (none) | — | — |"
      : parsed.reassessments
          .map((r) => `| ${r.id} | ${r.status} | ${r.evidence || "—"} |`)
          .join("\n");
  const newRows =
    parsed.newFindings.length === 0
      ? "| (none) | — | — | — | — | — | — |"
      : parsed.newFindings
          .map(
            (f) =>
              `| ${f.id} | ${f.severity} | ${f.title} | ${f.evidence} | ${f.targetFiles} | ${f.requiredFix} | ${f.acceptanceCheck} |`,
          )
          .join("\n");

  return `${title}

> reviewer: ${parsed.reviewer}
> evidence: ${parsed.evidencePath}

## Scope

- Scoped re-review of prior findings against frozen evidence \`${parsed.evidencePath}\`
- Reviewer: ${parsed.reviewer}

## Prior Findings Reassessment

| ID | 状态 | 复核证据 |
|---|---|---|
${reRows}

## New Findings

| ID | 严重度 | 标题 | 证据 | Target files | Required fix | Acceptance check |
|---|---|---|---|---|---|---|
${newRows}

## Regression Surface

${assertNoInjectedH1(parsed.regressionSurface || "No load-bearing regressions identified beyond listed findings.", "Regression Surface")}

## Verdict

${parsed.verdict}
`;
}

/**
 * Lifecycle for auto loop given verdict + stage.
 * @param {'review_findings'|'re_review'} stage
 * @param {string} verdict
 */
export function lifecycleForVerdict(stage, verdict) {
  const v = String(verdict).toUpperCase();
  if (v === "PASS" || v === "NO_FINDINGS") return "archived";
  if (v === "PASS_WITH_CONCERNS") return "awaiting_user_decision";
  if (v === "BLOCKED") return "blocked";
  return "in_progress";
}

/**
 * Format user Decision Closure stage (PWC accept-concerns).
 * Does not rewrite the original Verdict — acceptance ≠ resolved.
 * @param {{
 *   reason: string,
 *   originalVerdict: string,
 *   concerns: { id: string, title?: string, severity?: string }[],
 *   closedAt?: string,
 * }} opts
 */
export function formatDecisionClosureStage(opts) {
  const closedAt = opts.closedAt || new Date().toISOString();
  const concerns = Array.isArray(opts.concerns) ? opts.concerns : [];
  const rows =
    concerns.length === 0
      ? "| (none) | — | — | accepted as backlog |"
      : concerns
          .map(
            (c) =>
              `| ${c.id || "—"} | ${c.severity || "—"} | ${c.title || "—"} | accepted as backlog |`,
          )
          .join("\n");
  return `# Decision Closure

## Reason

\`${opts.reason}\`

## Original Verdict

\`${opts.originalVerdict}\`

## Accepted Concerns

| ID | 严重度 | 标题 | Disposition |
|---|---|---|---|
${rows}

## Closure

- closed_at: ${closedAt}
- actor: user via review-loop close
- note: accepting concerns does not rewrite the original Verdict to PASS
`;
}

export { VERDICTS };
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall