Skill: scott3j/adversarial-review (version 1.0.0)

--- name: adversarial-review description: "Run a structured adversarial multi-agent review loop on any significant document. Spawns parallel Opus reviewers with different critical lenses, collects structured redlines, then guides farsight through agree/disagree positioning and v2 production. SELF-TRIGGERING: load this skill and run the complexity self-assessment whenever you are about to produce or have just produced any substantial document — score it and offer the review loop if it qualifies. Also load when the user says things like: 'use the review team', 'get the review team on this', 'spin up the reviewers', 'have the team look at this', 'red-team this', 'redline this', 'challenge this', 'critique this', 'tear this apart', 'poke holes in this', 'stress test this', 'pressure test this', 'sanity check this', 'validate this', 'get a second opinion', 'before we build/implement/ship this'." --- # Adversarial Review Structured multi-agent review loop. Catches what a single agent misses. **Session store:** `~/.openclaw/workspace/reviews/` **Process:** Init session → spawn Opus reviewers → collect redlines → position on each → produce v2 → deliver --- ## Complexity Self-Assessment **Run this check whenever you produce a substantial document.** Score 1 point per signal present. If score ≥ 3, offer the review loop without being asked. | # | Signal | Points | |---|--------|--------| | 1 | Has multiple interdependent components (failure in one affects others) | 1 | | 2 | Involves schema changes, migrations, or index design | 1 | | 3 | Irreversible or expensive to undo (data loss, structural rework) | 1 | | 4 | Affects production systems, stored data, or external services | 1 | | 5 | Introduces new abstractions, taxonomies, or data models | 1 | | 6 | Has a defined sequence of steps where order matters | 1 | | 7 | Contains security, access control, or permission logic | 1 | | 8 | Will be acted on by code or agents without further human review | 1 | | 9 | Document is longer than ~500 lines or covers 3+ distinct systems | 1 | | 10 | Scott said "let's build this" or "implement this" at any point in the conversation | 1 | **Score 0–2 → skip.** Simple doc, don't add noise. **Score 3–6 → offer.** *"This scores [N]/10 on complexity. Want me to run the review team on it before we act?"* **Score 7–10 → strongly recommend.** Don't just offer — make the case. *"This scores [N]/10 on complexity — multiple interdependent systems, production consequences, hard to reverse. I'd strongly recommend running the review team before we act on this. Today's taxonomy strategy was a 10/10 and the review caught 14 issues including multiple production-breaking bugs."* --- ## Quick Reference | Step | Action | |------|--------| | 0. Init session | `scripts/new-review.sh <slug> <path-to-doc>` | | 1. Choose reviewers | Read `references/review-types.md` for the right bundle | | 2. Spawn reviewers | `sessions_spawn` with `model=anthropic/claude-opus-4-6`, `mode=run` — all in parallel | | 3. Wait | Reviewers auto-announce. Do NOT poll. | | 4. Save raw output | Write each reviewer result to `redlines/reviewer-{role}.md` | | 5. Synthesize | `scripts/synthesize.sh <session-dir>` → writes `redlines/combined.md` | | 6. Position | AGREE / DISAGREE / MODIFY on every redline → write `positions.md` | | 7. Produce v2 | Write `output/{slug}-v2.md` incorporating accepted changes + rejected appendix | | 8. Deliver | `scripts/cp-output.sh <session-name> <destination>` | --- ## Session Directory Structure ``` ~/.openclaw/workspace/reviews/{YYYY-MM-DD}-{slug}/ ├── input/ │ └── {original-filename} ← copy of doc being reviewed ├── redlines/ │ ├── reviewer-{role}.md ← raw output per reviewer │ └── combined.md ← synthesize.sh output (sorted by severity) ├── positions.md ← farsight agree/disagree log └── output/ └── {slug}-v2.md ← final document ``` --- ## Review Types | Document Type | Reviewer A | Reviewer B | |---------------|-----------|-----------| | Architecture / strategy | Theory & data modeling | Implementation & systems | | Pipeline / workflow | Sequencing & dependencies | Failure modes & ops | | Schema / migration | SQL correctness & constraints | Performance & indexes | | Security design | Threat modeling | Implementation gaps | | Marketing / positioning | Message clarity & truth | Competitive exposure | | API / interface design | Consistency & contracts | Consumer experience | For full persona prompt templates → read `references/reviewer-personas.md` For pre-configured bundles → read `references/review-types.md` --- ## Spawning Reviewers Spawn ALL reviewers simultaneously — parallel, not sequential. Independent reviewers find different issues. ### Model Selection | Doc Score | Default Model | Rationale | |-----------|--------------|-----------| | 7–10 | `anthropic/claude-opus-4-6` | Deep reasoning required; subtle architectural flaws need Opus | | 3–6 | `anthropic/claude-sonnet-4-6` | Worth trying; structured prompts may close the gap | **A/B testing note:** If Sonnet misses a CRITICAL issue that Opus would have caught on a 3–6 doc, upgrade that doc type to Opus permanently. Track findings in `references/model-notes.md` as patterns emerge. Key parameters for every reviewer spawn: ``` model: anthropic/claude-opus-4-6 ← or sonnet for 3-6 scored docs mode: run runTimeoutSeconds: 300 label: reviewer-{role} ``` The task field contains the full reviewer prompt from `references/reviewer-personas.md` plus the document content to review. --- ## Positioning Rules For EVERY redline, take an explicit position. No skipping. | Position | When | Requirement | |----------|------|------------| | **AGREE** | Critique is correct, change should be made | State what changes | | **DISAGREE** | Original design is defensible | Must provide rationale — not just dismissal | | **MODIFY** | Issue is real, suggested resolution is wrong | Propose your alternative | All CRITICAL redlines default to AGREE unless strongly defensible. At least 1 DISAGREE expected — if zero, you may be rubber-stamping. Write positions to `positions.md` in the session directory. --- ## v2 Requirements - Revision table at the top (what changed and why) - All AGREE + MODIFY changes incorporated - Rejected redlines documented in an appendix ("considered and rejected") - Version bumped, date updated - Saved to `output/{slug}-v2.md` --- ## Quality Bar A good review session produces: - ≥2 CRITICAL issues (if zero, reviewers weren't adversarial enough — re-spawn with harder prompt) - ≥1 DISAGREE from farsight (if zero, consider whether the doc was genuinely perfect or just unchallenged) - A v2 meaningfully different from v1 --- ## Redline Format ``` **[REDLINE-{TYPE}-{NNN}]** {Section reference} **Claim:** What the document says **Challenge:** The specific objection or gap **Severity:** CRITICAL | MAJOR | MINOR **Suggested Resolution:** What should change ``` Full spec → read `references/redline-format.md`

path: _meta.json
content: ownerId: bitwage
slug: adversarial-review
version: 1.0.0

path: references/redline-format.md
content: # Redline Format Specification

---

## Standard Format

Every redline must use this exact structure:

```
**[REDLINE-{TYPE}-{NNN}]** {Section reference}
**Claim:** What the document says (quote or close paraphrase)
**Challenge:** The specific objection or identified gap
**Severity:** CRITICAL | MAJOR | MINOR
**Suggested Resolution:** What should change
```

---

## ID Scheme

`REDLINE-{TYPE}-{NNN}`

**TYPE** — reviewer role tag (one per reviewer):
| Tag | Role |
|-----|------|
| `T` | Theory & Data Modeling |
| `I` | Implementation & Systems |
| `P` | Pipeline & Sequencing |
| `X` | Performance & Indexes |
| `S` | Security & Access |
| `M` | Positioning & Message |

**NNN** — sequential number within that reviewer's output (001, 002, etc.)

Examples: `REDLINE-T-001`, `REDLINE-I-007`, `REDLINE-P-003`

---

## Severity Definitions

### CRITICAL
The document is materially wrong in a way that will cause production failures, data loss, security breaches, or fundamental architectural breakdown if implemented as written.

Examples:
- SQL that will silently fail or produce wrong results
- A claim of atomicity that is architecturally impossible
- A safety gate that is bypassed by its own default values
- An index type that doesn't support the query operators used

### MAJOR
A significant design flaw that will cause problems at scale, create operational pain, or require expensive rework. Won't necessarily cause immediate failure but will cause regret.

Examples:
- Wrong data type for a use case (JSONB for boolean flags)
- Missing failure handling for a non-trivial failure mode
- Axis definitions that are correlated but treated as independent
- A state machine with unreachable or unexitable states

### MINOR
A correctness or clarity issue that should be fixed but won't cause serious harm. Polish.

Examples:
- A naming inconsistency between sections
- A default value that's technically correct but semantically confusing
- A missing edge case in documentation
- An example that uses deprecated syntax

---

## Deduplication Rules

When synthesizing multiple reviewer outputs, two redlines are the same issue if:
- They identify the same flaw in the same section
- Even if the framing or suggested resolution differs

**Resolution:** Keep the higher-severity version. Note in parentheses: `(also raised by REDLINE-I-003)`

---

## Linking Related Redlines

If two redlines are about the same root cause but different symptoms, link them:

```
**Suggested Resolution:** Fix X. Note: this is the root cause of REDLINE-T-002.
```

---

## Positions Format

In `positions.md`, document each position in this format:

```markdown
## [REDLINE-{TYPE}-{NNN}] — {AGREE | DISAGREE | MODIFY}

**Original claim:** {one sentence}
**Redline summary:** {one sentence}
**Position:** AGREE | DISAGREE | MODIFY
**Rationale:** {Why this position. Required for DISAGREE and MODIFY.}
**Change in v2:** {What specifically changes, or "No change — rejected."}
```

---

## Rejected Redlines Appendix

At the end of the v2 document, include:

```markdown
## Appendix: Considered and Rejected

The following redlines were reviewed and rejected. Documented here to prevent
re-raising in future review cycles.

### [REDLINE-T-002] — REJECTED
**Critique:** {summary}
**Reason for rejection:** {explanation}
```


path: references/review-types.md
content: # Review Type Bundles

Pre-configured reviewer combinations by document type. Look up the document type, spawn the listed reviewers.

---

## Architecture / Strategy

**Use for:** System design docs, technical strategy, multi-component architecture decisions

| Reviewer | Persona | Tag |
|----------|---------|-----|
| A | Theory & Data Modeling | T |
| B | Implementation & Systems | I |

**Additional focus for prompts:**
- Ask Reviewer A to specifically challenge "independence" claims between components
- Ask Reviewer B to focus on what the design assumes about infrastructure that may not hold

**Expected output:** Minimum 2 CRITICAL issues on any architecture doc of real complexity. Zero CRITICALs is a red flag.

---

## Pipeline / Workflow

**Use for:** Data pipelines, enrichment flows, multi-step automation, event-driven systems

| Reviewer | Persona | Tag |
|----------|---------|-----|
| A | Pipeline & Sequencing | P |
| B | Implementation & Systems | I |

**Additional focus for prompts:**
- Ask Reviewer A to specifically trace every failure mode for every step
- Ask Reviewer B to focus on state machine completeness and partial failure recovery

---

## Schema / Migration

**Use for:** Database schema designs, migration SQL, index strategies

| Reviewer | Persona | Tag |
|----------|---------|-----|
| A | Implementation & Systems | I |
| B | Performance & Indexes | X |

**Additional focus for prompts:**
- Ask Reviewer A to test every `ADD COLUMN IF NOT EXISTS` for idempotency traps
- Ask Reviewer B to trace every query pattern against the index types created

**Common catches:** GIN vs B-tree mismatches, inline CHECK constraint bypass, wrong data types, JSONB vs column selection errors.

---

## Security Design

**Use for:** Access control systems, authentication flows, data permission models

| Reviewer | Persona | Tag |
|----------|---------|-----|
| A | Security & Access | S |
| B | Theory & Data Modeling | T |

**Additional focus for prompts:**
- Ask Reviewer A to assume an adversarial agent is trying to bypass every gate
- Ask Reviewer B to check whether the access model has contradictory defaults

---

## Marketing / Positioning

**Use for:** Positioning statements, GTM strategy, competitive narratives, product copy

| Reviewer | Persona | Tag |
|----------|---------|-----|
| A | Positioning & Message | M |
| B | Theory & Data Modeling | T |

**Additional focus for prompts:**
- Ask Reviewer A to check every claim that could be challenged by a prospect
- Ask Reviewer B to check internal consistency and whether the positioning is actually differentiated

---

## API / Interface Design

**Use for:** REST/GraphQL API specs, SDK interfaces, event schemas

| Reviewer | Persona | Tag |
|----------|---------|-----|
| A | Implementation & Systems | I |
| B | Theory & Data Modeling | T |

**Additional focus for prompts:**
- Ask Reviewer A to check for breaking changes and versioning gaps
- Ask Reviewer B to check naming consistency and abstraction correctness

---

## Complex / High-Stakes (3 Reviewers)

**Use for:** Major architectural decisions, anything with significant irreversible consequences

| Reviewer | Persona | Tag |
|----------|---------|-----|
| A | Theory & Data Modeling | T |
| B | Implementation & Systems | I |
| C | Pipeline & Sequencing | P |

Spawn all three simultaneously. Synthesis will take longer but the coverage is meaningfully broader.

---

## Choosing Custom Reviewers

If none of the above bundles fit exactly:

1. Read `reviewer-personas.md` and identify the two personas whose focus areas best match the document's risk areas
2. Ask: "Where would this document most likely fail?" — pick the reviewers who cover those failure modes
3. Optionally add domain-specific focus points to the prompt to sharpen the review


path: references/reviewer-personas.md
content: # Reviewer Personas

Reusable Opus prompt templates. Copy the relevant template into the `task` field of `sessions_spawn`. Replace `{DOCUMENT}` with the full document content.

---

## Table of Contents
1. [Theory & Data Modeling](#1-theory--data-modeling)
2. [Implementation & Systems](#2-implementation--systems)
3. [Pipeline & Sequencing](#3-pipeline--sequencing)
4. [Performance & Indexes](#4-performance--indexes)
5. [Security & Access](#5-security--access)
6. [Positioning & Message](#6-positioning--message)

---

## 1. Theory & Data Modeling

**Tag:** `T`  
**Lens:** Axiom validity, abstraction correctness, internal consistency, dependency claims, over/under-engineering

```
You are a senior knowledge architect and data modeling expert conducting a rigorous adversarial review. Your job is to challenge the theoretical foundations, data model choices, and architectural claims — NOT to be supportive. Find real problems.

For each issue, use this exact format:

**[REDLINE-T-{NNN}]** {Section reference}
**Claim:** What the document says
**Challenge:** Your specific objection or identified gap
**Severity:** CRITICAL | MAJOR | MINOR
**Suggested Resolution:** What should change

Focus areas:
1. Are the core abstractions correct? Do the named concepts mean what the author thinks they mean?
2. Are claimed-independent dimensions actually independent? Find correlations and dependencies.
3. Are default values defensible? Check for contradictions between defaults across related fields.
4. Is the taxonomy/classification scheme complete, or are there important cases not covered?
5. Does the architecture actually solve the stated problem, or does it create new versions of the same problem?
6. Are there circular dependencies or bootstrapping deadlocks in the design?
7. Is the system over-engineered (unnecessary complexity) or under-engineered (naive simplifications that will break at scale)?
8. Are all claims about system behavior actually true, or are some aspirational/assumed?

Be specific. Reference exact sections. Do not hedge. Do not offer praise. Your job is to find what is wrong.

---

DOCUMENT TO REVIEW:

{DOCUMENT}
```

---

## 2. Implementation & Systems

**Tag:** `I`  
**Lens:** SQL correctness, API design, operational feasibility, failure modes, deployment concerns

```
You are a senior backend engineer and systems architect conducting a rigorous adversarial review. Your job is to challenge the SQL, schema design, pipeline implementation, and operational claims — NOT to be supportive. Find real problems.

For each issue, use this exact format:

**[REDLINE-I-{NNN}]** {Section reference}
**Claim:** What the document says
**Challenge:** Your specific objection or identified gap
**Severity:** CRITICAL | MAJOR | MINOR
**Suggested Resolution:** What should change

Focus areas:
1. SQL correctness: Will the statements actually execute? Are constraints syntactically and semantically correct?
2. Index usage: Do the query patterns shown actually use the indexes created? Check operator class compatibility.
3. Atomicity claims: Is "atomic" actually achievable given the systems involved?
4. Schema design: Are the right things columns vs JSONB vs foreign keys? Wrong choices now are expensive to fix.
5. Data type correctness: Are boolean flags stored as booleans? Are arrays stored as arrays?
6. Migration safety: Are migrations additive and non-breaking? Can they be re-run safely?
7. Default value correctness: Do defaults represent the right semantic state?
8. Failure modes: What happens when each step fails? Is there a recovery path?
9. Pipeline ordering: Are there unacknowledged dependencies between steps?
10. Operational concerns: How does a developer diagnose problems in production?

Be specific. Reference exact sections and claim line-by-line where relevant. Do not hedge. Find what will break in production.

---

DOCUMENT TO REVIEW:

{DOCUMENT}
```

---

## 3. Pipeline & Sequencing

**Tag:** `P`  
**Lens:** Pass ordering, dependency chains, failure cascades, idempotency, recovery paths

```
You are a senior platform engineer specializing in data pipelines and workflow orchestration. Your job is to challenge the sequencing, dependency management, and operational resilience of the described pipeline — NOT to be supportive. Find real problems.

For each issue, use this exact format:

**[REDLINE-P-{NNN}]** {Section reference}
**Claim:** What the document says
**Challenge:** Your specific objection or identified gap
**Severity:** CRITICAL | MAJOR | MINOR
**Suggested Resolution:** What should change

Focus areas:
1. Step ordering: Does each step depend only on the outputs of prior steps? Are hidden dependencies present?
2. Idempotency: Can each step be safely re-run? What breaks if it runs twice?
3. Partial failure: What is the system state if a step fails halfway through?
4. Cascading failures: If step N fails, what downstream steps are affected?
5. State machine completeness: Are all workflow state transitions defined? Are there unreachable or stuck states?
6. Concurrency: What happens if two pipeline runs overlap on the same record?
7. Human-in-the-loop gaps: Are there automated steps that claim human involvement, or human gates that have no mechanism?
8. Trigger correctness: Are events/triggers firing at the right time and only when preconditions are met?
9. Backpressure: What happens when the pipeline falls behind? Is there a backlog management strategy?

Be specific. Reference exact sections. Do not hedge. Find what fails silently.

---

DOCUMENT TO REVIEW:

{DOCUMENT}
```

---

## 4. Performance & Indexes

**Tag:** `X`  
**Lens:** Query plan feasibility, index operator class correctness, throughput bottlenecks

```
You are a senior database performance engineer. Your job is to challenge the query patterns, index design, and performance assumptions — NOT to be supportive. Find real problems.

For each issue, use this exact format:

**[REDLINE-X-{NNN}]** {Section reference}
**Claim:** What the document says
**Challenge:** Your specific objection or identified gap
**Severity:** CRITICAL | MAJOR | MINOR
**Suggested Resolution:** What should change

Focus areas:
1. Index operator class: Do the query patterns shown (=, >, LIKE, ?, @>, ->>) match what the index type actually supports?
2. GIN vs B-tree selection: Is each index type correct for its column and query pattern?
3. Selectivity: Will the query planner actually use the indexes, or will it prefer sequential scans?
4. Join performance: For JOIN queries, which table should be the inner/outer table? Is there an implicit cartesian product risk?
5. JSONB extraction: Does ->> text extraction vs @> containment affect index usage? Are there hidden sequential scans?
6. Write amplification: How many indexes are updated per INSERT/UPDATE? Is this sustainable at scale?
7. Partial indexes: Are partial indexes used where appropriate (e.g., WHERE status = 'pending')?
8. Vector search: For ANN queries, are taxonomy filters applied pre- or post-vector-scan? Wrong ordering kills recall or performance.

Be specific. Reference exact SQL. Do not hedge.

---

DOCUMENT TO REVIEW:

{DOCUMENT}
```

---

## 5. Security & Access

**Tag:** `S`  
**Lens:** Threat surface, access control gaps, data exposure, privilege escalation paths

```
You are a security architect conducting a rigorous adversarial review. Your job is to challenge access control design, data exposure risks, and security assumptions — NOT to be supportive. Find real problems.

For each issue, use this exact format:

**[REDLINE-S-{NNN}]** {Section reference}
**Claim:** What the document says
**Challenge:** Your specific objection or identified gap
**Severity:** CRITICAL | MAJOR | MINOR
**Suggested Resolution:** What should change

Focus areas:
1. Access control enforcement: Is access control checked at the right layer? Can it be bypassed?
2. Default permissions: Are defaults too permissive? What is the blast radius if defaults are never updated?
3. Data exposure: Can confidential data leak through indirect queries or joins?
4. Agent trust: Are agents trusted to enforce their own access restrictions? Is this safe?
5. Privilege escalation: Can a lower-privileged operation write to a higher-privileged field?
6. Audit trail: Are access decisions logged? Can policy violations be detected after the fact?
7. Sync attack surface: In dual-write systems, can a malicious write to one store corrupt the other?

Be specific. Do not hedge.

---

DOCUMENT TO REVIEW:

{DOCUMENT}
```

---

## 6. Positioning & Message

**Tag:** `M`  
**Lens:** Claim accuracy, internal consistency, audience fit, competitive exposure

```
You are a senior product strategist and editor conducting a rigorous adversarial review. Your job is to challenge the clarity, accuracy, and internal consistency of the arguments made — NOT to be supportive. Find real problems.

For each issue, use this exact format:

**[REDLINE-M-{NNN}]** {Section reference}
**Claim:** What the document says
**Challenge:** Your specific objection or identified gap
**Severity:** CRITICAL | MAJOR | MINOR
**Suggested Resolution:** What should change

Focus areas:
1. Claim accuracy: Are any stated facts or benefits exaggerated, unverifiable, or simply wrong?
2. Internal consistency: Does the document contradict itself across sections?
3. Unstated assumptions: What does the argument rely on that is never stated?
4. Audience fit: Is the level of detail and vocabulary right for the stated audience?
5. Missing alternatives: Does the document fairly represent alternatives that were considered?
6. Confidence calibration: Are probabilities, risks, or outcomes stated with appropriate uncertainty?
7. Scope creep: Does the document promise more than the implementation delivers?

Be specific. Reference exact sections. Do not hedge.

---

DOCUMENT TO REVIEW:

{DOCUMENT}
```


path: scripts/cp-output.sh
content: #!/bin/bash
# adversarial-review: Copy final output document to a destination
#
# Usage: cp-output.sh <session-name> <destination-path>
#
# Finds the most recent .md file in {session}/output/
# Copies it to destination (creates directory if needed)
# Prints full destination path on completion
#
# Examples:
#   cp-output.sh 2026-03-06-bitwage-taxonomy ~/Desktop
#   cp-output.sh 2026-03-06-bitwage-taxonomy ~/Projects/bitwage-intelligence/docs/
#   cp-output.sh 2026-03-06-bitwage-taxonomy /tmp/for-team-review/

set -e

REVIEWS_DIR=~/.openclaw/workspace/reviews

if [ -z "$1" ] || [ -z "$2" ]; then
  echo "Usage: cp-output.sh <session-name> <destination-path>"
  echo ""
  echo "Available sessions:"
  ls "$REVIEWS_DIR" 2>/dev/null | while read -r s; do
    count=$(ls "$REVIEWS_DIR/$s/output/" 2>/dev/null | wc -l | tr -d ' ')
    echo "  $s ($count output file(s))"
  done
  exit 1
fi

SESSION_NAME="$1"
DESTINATION="$2"
SESSION_DIR="${REVIEWS_DIR}/${SESSION_NAME}"
OUTPUT_DIR="${SESSION_DIR}/output"

if [ ! -d "$SESSION_DIR" ]; then
  echo "Error: Session not found: $SESSION_DIR"
  echo ""
  echo "Available sessions:"
  ls "$REVIEWS_DIR" 2>/dev/null
  exit 1
fi

if [ ! -d "$OUTPUT_DIR" ]; then
  echo "Error: Output directory not found: $OUTPUT_DIR"
  echo "Has v2 been written yet? Write output/{slug}-v2.md first."
  exit 1
fi

# Find the most recent .md file in output/
LATEST=$(ls -t "$OUTPUT_DIR"/*.md 2>/dev/null | head -1)

if [ -z "$LATEST" ]; then
  echo "Error: No .md files found in $OUTPUT_DIR"
  echo "Has v2 been written yet?"
  exit 1
fi

FILENAME=$(basename "$LATEST")

# Expand destination path
DEST=$(eval echo "$DESTINATION")

# Create destination if it doesn't exist
mkdir -p "$DEST"

cp "$LATEST" "$DEST/$FILENAME"

echo ""
echo "✓ Copied: $FILENAME"
echo "  From: $LATEST"
echo "  To:   $DEST/$FILENAME"
echo ""


path: scripts/new-review.sh
content: #!/bin/bash
# adversarial-review: Initialize a new review session directory
#
# Usage: new-review.sh <project-slug> <path-to-input-doc>
#
# Creates:
#   ~/.openclaw/workspace/reviews/{YYYY-MM-DD}-{slug}/
#     input/{filename}     ← copy of the document being reviewed
#     redlines/            ← populated by reviewers
#     output/              ← populated after v2 is written
#     positions.md         ← template for agree/disagree/modify log

set -e

REVIEWS_DIR=~/.openclaw/workspace/reviews

if [ -z "$1" ] || [ -z "$2" ]; then
  echo "Usage: new-review.sh <project-slug> <path-to-input-doc>"
  echo "Example: new-review.sh bitwage-taxonomy ~/Desktop/strategy.md"
  exit 1
fi

SLUG="$1"
INPUT_DOC="$2"

if [ ! -f "$INPUT_DOC" ]; then
  echo "Error: File not found: $INPUT_DOC"
  exit 1
fi

DATE=$(date +%Y-%m-%d)
SESSION_NAME="${DATE}-${SLUG}"
SESSION_DIR="${REVIEWS_DIR}/${SESSION_NAME}"

if [ -d "$SESSION_DIR" ]; then
  echo "Warning: Session directory already exists: $SESSION_DIR"
  echo "Continue? (y/n)"
  read -r confirm
  if [ "$confirm" != "y" ]; then exit 1; fi
fi

mkdir -p "$SESSION_DIR/input"
mkdir -p "$SESSION_DIR/redlines"
mkdir -p "$SESSION_DIR/output"

# Copy input document
FILENAME=$(basename "$INPUT_DOC")
cp "$INPUT_DOC" "$SESSION_DIR/input/$FILENAME"

# Create positions.md template
cat > "$SESSION_DIR/positions.md" << EOF
# Positions — ${SESSION_NAME}

**Document:** ${FILENAME}
**Date:** ${DATE}
**Status:** In Progress

---

## Redline Positions

For each redline from combined.md, record your position here.

Format:
\`\`\`
## [REDLINE-{TYPE}-{NNN}] — {AGREE | DISAGREE | MODIFY}

**Redline summary:** {one sentence}
**Position:** AGREE | DISAGREE | MODIFY
**Rationale:** {required for DISAGREE and MODIFY}
**Change in v2:** {what changes, or "No change — rejected"}
\`\`\`

---

<!-- Positions go below this line -->


EOF

echo ""
echo "✓ Review session initialized: $SESSION_DIR"
echo ""
echo "  input/    → $FILENAME (ready)"
echo "  redlines/ → empty (populate after reviewer runs)"
echo "  output/   → empty (populate after v2 is written)"
echo "  positions.md → template ready"
echo ""
echo "Session name: $SESSION_NAME"
echo "Next: spawn reviewers from references/reviewer-personas.md"
echo "      write reviewer outputs to: $SESSION_DIR/redlines/reviewer-{role}.md"


path: scripts/synthesize.sh
content: #!/bin/bash
# adversarial-review: Synthesize reviewer outputs into a sorted combined redline
#
# Usage: synthesize.sh <session-name>
#
# Reads all .md files in {session}/redlines/ (except combined.md)
# Extracts REDLINE-* blocks, sorts by severity (CRITICAL → MAJOR → MINOR)
# Writes {session}/redlines/combined.md

set -e

REVIEWS_DIR="${HOME}/.openclaw/workspace/reviews"

if [ -z "$1" ]; then
  echo "Usage: synthesize.sh <session-name>"
  echo "Example: synthesize.sh 2026-03-06-bitwage-taxonomy"
  echo ""
  echo "Available sessions:"
  ls "$REVIEWS_DIR" 2>/dev/null || echo "  (none)"
  exit 1
fi

SESSION_NAME="$1"
REDLINES_DIR="${REVIEWS_DIR}/${SESSION_NAME}/redlines"
OUTPUT="${REDLINES_DIR}/combined.md"

if [ ! -d "$REDLINES_DIR" ]; then
  echo "Error: Redlines directory not found: $REDLINES_DIR"
  exit 1
fi

SOURCE_COUNT=$(find "$REDLINES_DIR" -name "*.md" ! -name "combined.md" | wc -l | tr -d ' ')

if [ "$SOURCE_COUNT" -eq 0 ]; then
  echo "Error: No reviewer output files found in $REDLINES_DIR"
  echo "Write reviewer outputs as reviewer-{role}.md before synthesizing."
  exit 1
fi

echo "Synthesizing ${SOURCE_COUNT} reviewer file(s)..."

# Write node script to a temp file to avoid heredoc env var issues
TMPSCRIPT=$(mktemp /tmp/synthesize-XXXXXX.js)

cat > "$TMPSCRIPT" << 'JSEOF'
const fs = require('fs');
const path = require('path');

const sessionName = process.argv[2];
const reviewsDir  = process.argv[3];
const redlinesDir = path.join(reviewsDir, sessionName, 'redlines');
const outputFile  = path.join(redlinesDir, 'combined.md');

const files = fs.readdirSync(redlinesDir)
  .filter(f => f.endsWith('.md') && f !== 'combined.md')
  .map(f => path.join(redlinesDir, f));

const severityOrder = { CRITICAL: 0, MAJOR: 1, MINOR: 2 };
const redlines = [];

for (const file of files) {
  const content = fs.readFileSync(file, 'utf8');
  const reviewer = path.basename(file, '.md').replace('reviewer-', '');

  // Split on REDLINE block boundaries
  const blocks = content.split(/(?=\*\*\[REDLINE-)/).filter(b =>
    b.includes('**Severity:**') && b.includes('**[REDLINE-')
  );

  for (const block of blocks) {
    const idMatch  = block.match(/\*\*\[REDLINE-([A-Z])-(\d+)\]\*\*/);
    const sevMatch = block.match(/\*\*Severity:\*\*\s*(CRITICAL|MAJOR|MINOR)/);
    if (!idMatch || !sevMatch) continue;

    redlines.push({
      id:       `REDLINE-${idMatch[1]}-${idMatch[2]}`,
      type:     idMatch[1],
      num:      parseInt(idMatch[2]),
      severity: sevMatch[1],
      order:    severityOrder[sevMatch[1]] ?? 99,
      reviewer,
      text:     block.trim()
    });
  }
}

// Sort: severity first, then reviewer, then number
redlines.sort((a, b) =>
  a.order - b.order ||
  a.reviewer.localeCompare(b.reviewer) ||
  a.num - b.num
);

const counts = { CRITICAL: 0, MAJOR: 0, MINOR: 0 };
redlines.forEach(r => counts[r.severity]++);

const date = new Date().toISOString().split('T')[0];
let out = `# Combined Redlines — ${sessionName}\n\n`;
out += `**Synthesized:** ${date}  \n`;
out += `**Source files:** ${files.length}  \n`;
out += `**Total redlines:** ${redlines.length}`;
out += ` (🔴 CRITICAL: ${counts.CRITICAL} | 🟡 MAJOR: ${counts.MAJOR} | 🟢 MINOR: ${counts.MINOR})\n\n---\n\n`;

let currentSeverity = null;
for (const r of redlines) {
  if (r.severity !== currentSeverity) {
    currentSeverity = r.severity;
    const emoji = currentSeverity === 'CRITICAL' ? '🔴' : currentSeverity === 'MAJOR' ? '🟡' : '🟢';
    out += `## ${emoji} ${currentSeverity}\n\n`;
  }
  out += `${r.text}\n\n---\n\n`;
}

fs.writeFileSync(outputFile, out);

console.log(`\n✓ Combined redlines written: ${outputFile}`);
console.log(`\n  🔴 CRITICAL: ${counts.CRITICAL}`);
console.log(`  🟡 MAJOR:    ${counts.MAJOR}`);
console.log(`  🟢 MINOR:    ${counts.MINOR}`);
console.log(`  TOTAL:    ${redlines.length}`);

if (counts.CRITICAL === 0) {
  console.log('\n⚠ Zero CRITICAL issues — consider whether reviewers were adversarial enough.');
}
JSEOF

node "$TMPSCRIPT" "$SESSION_NAME" "$REVIEWS_DIR"
rm -f "$TMPSCRIPT"


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)