Restricted Content

This chapter is password-protected. Please enter the password to continue.



← Back to guide overview

7  Workflow Patterns

The first two patterns are meta-patterns — they govern how every task flows. Learn these first, then the specific workflows make more sense.

7.1 Pattern 1: Plan-First Development

The plan-first pattern ensures that non-trivial tasks begin with thinking, not typing.

7.1.1 Why Planning Matters

The most common failure mode in AI-assisted development is not bad code — it is solving the wrong problem, or solving the right problem in a fragile order. Plan-first development forces an explicit design step before any file is touched. Plans are saved to quality_reports/plans/ on disk, so they survive context compaction.

Without a plan:

  • Gemini starts editing immediately, discovers a dependency on slide 3 that changes the approach, and has to undo work
  • Context compression discards the reasoning behind a design choice, and Gemini makes a contradictory decision later
  • The user and Gemini have different mental models of what “done” looks like

With a plan:

  • The approach is agreed upon before any edits happen
  • The plan is saved to disk, so it survives compression and session boundaries
  • Implementation has a checklist to follow, reducing drift

7.1.2 The Protocol

Non-trivial task arrives
  |
  +-- Step 1: Gemini enters plan mode (automatic, or say "plan this first")
  +-- Step 2: Draft plan (approach, files, verification)
  +-- Step 3: Save to quality_reports/plans/YYYY-MM-DD_description.md
  +-- Step 4: Present plan to user
  +-- Step 5: User approves (or revises)
  +-- Step 6: Save initial session log (capture context while fresh)
  +-- Step 7: Orchestrator takes over (see Pattern 2)
  +-- Step 8: Update session log + plan status to COMPLETED

7.1.3 Context Preservation

Plans are saved to disk specifically so they survive context compression. The rule: avoid /clear — prefer auto-compression. Use /clear only when context is genuinely polluted.

For details on how the system automatically preserves and restores context during compaction, see Context Survival System in the Building Blocks section.

7.1.4 Session Logging

Session logs (quality_reports/session_logs/YYYY-MM-DD_description.md) are a running record of why things happened. They have three distinct behaviors, each solving a different problem:

After plan approval — create the log with the goal, plan summary, and rationale for the chosen approach (including rejected alternatives). This captures decisions while context is richest. If you wait, auto-compression may discard the reasoning.

During implementation — append to the log as you work. Every time a design decision is made, a problem is discovered, or the approach deviates from the plan, write a 1-3 line entry immediately. This is the most important behavior: context gets compressed as the session progresses, and decisions that live only in the conversation will be lost.

At session end — add a final section with what was accomplished, open questions, and unresolved issues.

Git records what; session logs record why. A commit message says “Update Lecture 5 TikZ diagrams.” A session log says “Redesigned the TWFE decomposition diagram because the DA challenge revealed students couldn’t trace the path from weights to bias. Considered a table format but chose a flow diagram because it shows directionality.”

Incremental logging is the key. A 4-hour session that only logs at the start and end loses everything in the middle. Appending decisions as they happen means auto-compression can never erase them — they are already on disk.

Gemini writes all three log entries automatically — no need to ask.

For multi-project academics, start each week by asking Gemini to read all session logs from the past week and synthesize a status report with priorities and open questions. The session log infrastructure already captures what you need — the weekly review is just a synthesis prompt: “Read all session logs from this week. Summarize: what was accomplished, what’s blocked, what should I prioritize next?”

7.2 Pattern 2: Contractor Mode (Orchestrator)

Once a plan is approved, the orchestrator takes over. It is the natural continuation of Pattern 1: the plan says what, the orchestrator handles how — autonomously.

7.2.1 The Mental Model

Think of the orchestrator as a general contractor. You are the client. You describe what you want. The plan-first protocol is the blueprint phase. Once you approve the blueprint, the contractor takes over: hires the right specialists (agents), inspects their work (verification), sends them back to fix issues (review-fix loop), and only calls you when the job passes inspection (quality gates).

7.2.2 The Loop

User: "Translate Lecture 5 to Quarto"
  |
  |-- Plan-first (Pattern 1): draft plan, save to disk, get approval
  |
  |-- User: "Approved"
  |
  +-- Orchestrator activates:
        |
        Step 1: IMPLEMENT
        |  Execute plan steps (create QMD, translate content, etc.)
        |
        Step 2: VERIFY
        |  Run verifier: render Quarto, check HTML output
        |  If render fails -> fix -> re-render
        |
        Step 3: REVIEW (agents selected by file type)
        |  +--- proofreader ------+
        |  +--- slide-auditor ----+  (parallel)
        |  +--- pedagogy-reviewer +
        |  +--- quarto-critic ----+  (needs others first)
        |
        Step 4: FIX
        |  Apply fixes: Critical -> Major -> Minor
        |  For quarto-critic issues: invoke quarto-fixer
        |
        Step 5: RE-VERIFY
        |  Render again, confirm fixes are clean
        |
        Step 6: SCORE
        |  Apply quality-gates rubric
        |
        +-- Score >= 80?
              YES -> Present summary to user
              NO  -> Loop to Step 3 (max 5 rounds)

7.2.3 Agent Selection

The orchestrator selects agents based on which files were touched:

Files Modified Agents Selected
.tex only proofreader + slide-auditor + pedagogy-reviewer
.qmd only proofreader + slide-auditor + pedagogy-reviewer
.qmd with matching .tex Above + quarto-critic (parity check)
.R scripts r-reviewer
TikZ diagrams present tikz-reviewer
Domain content domain-reviewer (if configured)
Multiple formats verifier for cross-format parity

Agents that are independent of each other run in parallel. The quarto-critic runs after other agents because it may need their context.

7.2.4 “Just Do It” Mode

Sometimes you do not want to approve the final result — you just want it done:

“Translate Lecture 5 to Quarto. Just do it.”

In this mode, the orchestrator still runs the full verify-review-fix loop (quality is non-negotiable), but skips the final approval pause and auto-commits if the score is 80 or above. It still presents the summary so you can see what was done.

7.2.5 Relationship to Existing Skills

The orchestrator does NOT replace skills. It coordinates them:

  • qa-quarto remains available as a standalone adversarial QA loop
  • slide-excellence remains available for comprehensive multi-agent review
  • create-lecture remains available as a guided creation workflow

The difference: when you invoke a skill directly, it runs its specific workflow. When the orchestrator is active, it decides which agents to invoke based on context. The orchestrator is the default; skills are for targeted use.

Natural-language task → Gemini picks a skill: “Translate Lecture 5 to Quarto” → Gemini invokes translate-to-quarto, and that skill runs the orchestrator pattern (translate → verify → review → fix → score) internally.

Explicit skill call: qa-quarto Lecture5 — you specifically want the adversarial critic-fixer loop, nothing else.

Both are valid. The natural-language path is the “I trust you, pick the skill” path. Explicit skill calls are the “I know exactly which loop I want” path. Either way, the orchestrator pattern runs inside the invoked skill — there is no auto-trigger outside a skill.

7.3 Pattern 3: Creating a New Lecture

The create-lecture skill guides you through a structured lecture creation workflow — from gathering source material to deploying polished slides:

create-lecture
  |
  +-- Phase 1: Gather materials (papers, outlines)
  +-- Phase 2: Design slide structure
  +-- Phase 3: Draft Beamer slides
  +-- Phase 4: Generate R figures
  +-- Phase 5: Polish and verify
  |     +-- slide-excellence (domain + visual + pedagogy)
  |     +-- proofread (grammar/typos)
  |     +-- visual-audit (layout)
  +-- Phase 6: Deploy
        +-- translate-to-quarto (optional)
        +-- deploy
TipTikZ diagrams: start from the gallery, not from scratch

Writing TikZ from a blank page reliably produces label-over-arrow collisions because the compiler doesn’t warn about them. The template ships three reinforcing layers:

  • templates/tikz-snippets/ — 8 production-ready standalone diagrams (DAG basic, DAG mediation, two-period DiD, event study, timeline, regression scatter, 3-step flowchart, supply-demand). Each embeds the prevention rules (explicit node dimensions, coordinate map, directional edge labels) by construction.
  • Rules tikz-prevention.md + tikz-measurement.md — Upstream authoring rules (P1–P6) and the six-pass collision protocol with formulas (Bézier depth, character widths, 0.4 cm boundary clearance). Adapted from Scott Cunningham’s MixtapeTools.
  • new-diagram skill — Scaffolds from the gallery, runs the P3/P4 grep pre-check before compiling, invokes tikz-reviewer with measurement citations, loops until APPROVED.

For existing diagrams in a Beamer deck, extract-tikz runs the same pre-check plus the SVG pipeline.

7.4 Pattern 4: Translating Beamer to Quarto

Translation preserves all content while adapting format, converting TikZ to SVG and ggplot to interactive Plotly charts:

translate-to-quarto Lecture5_Topic.tex
  |
  +-- Phase 1-3: Environment mapping + content translation
  +-- Phase 4-5: Figure conversion (TikZ -> SVG)
  +-- Phase 6-7: Interactive charts (ggplot -> plotly)
  +-- Phase 8-9: Render + verify
  +-- Phase 10-11: qa-quarto adversarial QA
        +-- Critic: finds issues
        +-- Fixer: applies fixes
        +-- Critic: re-audits
        +-- ... (until APPROVED or 5 rounds)

7.5 Pattern 5: Replication-First Coding

When working with papers that have replication packages:

Phase 1: Inventory original code
  +-- Record "gold standard" numbers (Table X, Column Y = Z.ZZ)

Phase 2: Translate (e.g., Stata -> R)
  +-- Match original specification EXACTLY (same covariates, same clustering)

Phase 3: Verify match
  +-- Compare every target: paper value vs. our value
  +-- Tolerance: < 0.01 for estimates, < 0.05 for SEs
  +-- If mismatch: STOP. Investigate before proceeding.

Phase 4: Only then extend
  +-- New estimators, new specifications, course-specific figures
ImportantNever Skip Replication

In one course, we discovered that a widely-used R package silently produced incorrect estimates due to a subtle specification issue. This bug was caught 3 times in different scripts. Without the replication-first protocol, these wrong numbers would have been taught to PhD students.

Source-language coverage: The pattern is language-agnostic. The template ships data-analysis for R-first projects and stata-replication (v1.9.0) for Stata-first projects (mirrors data-analysis exactly; same numbered-pipeline shape, different language; executes via the stata-mcp MCP server). Python-first projects follow the same convention with the path scripts/python/_outputs/. For Stata users, stata-code-conventions.md (v1.9.0) codifies the header (version 18, clear all, set seed/set sortseed), numbered pipeline (00–99), esttab for \input{} tables, clustering discipline (reghdfe), balance via iebaltab, and AEA Data Editor compliance.

NoteClaims provenance via passport.yaml (v1.9.0)

Replication-first verifies the current state. A separate question: how do we keep manuscript and code in sync over the lifetime of a paper, especially during R&R?

The answer is a per-paper quality_reports/passports/<paper-slug>.yaml that records, for each numeric claim in the manuscript, the script + line + output that produced it. Schema includes tolerance, last_verified_on, status (PASS / FAIL / STALE / UNVERIFIED). audit-reproducibility reads and rewrites the passport in place; commit reads it to block commits when a load-bearing claim is FAIL or STALE.

Starter file: templates/passport-template.yaml. Copy once per paper. Pattern attributed to Imbad0202/academic-research-skills “Material Passport” concept (scope-reduced for this template: numeric claims only).

7.6 Pattern 6: Multi-Agent Review

The slide-excellence skill runs up to 6 specialized agents in parallel:

slide-excellence Lecture5_Topic.tex
  |
  +-- Agent 1: Visual Audit (slide-auditor)
  +-- Agent 2: Pedagogical Review (pedagogy-reviewer)
  +-- Agent 3: Proofreading (proofreader)
  +-- Agent 4: TikZ Review (tikz-reviewer, if applicable)
  +-- Agent 5: Content Parity (if Quarto version exists)
  +-- Agent 6: Substance Review (domain-reviewer)
  |
  +-- Synthesize: Combined quality score + prioritized fix list

7.7 Pattern 7: Self-Improvement Loop

There are two levels of self-improvement: quick corrections via [LEARN] tags and full skill extraction via learn.

7.7.1 Quick Corrections: [LEARN] Tags

Every correction gets tagged for future reference in MEMORY.md:

## Corrections Log
- [LEARN:notation] T_t = 1{t=2} is deterministic -> use T_i in {1,2}
- [LEARN:citation] Post-LASSO is Belloni (2013), NOT Belloni (2014)
- [LEARN:r-code] Package X: ALWAYS include intercept in design matrix
- [LEARN:workflow] Every Beamer edit must auto-sync to Quarto

These tags are searchable and persist across sessions. When Gemini encounters a similar situation, it checks memory first.

7.7.2 Automated Skill Capture: learn

For discoveries that deserve more than a one-line tag, use learn to create a full skill:

learn fixest-missing-covariate-handling

The learn skill guides you through a 4-phase workflow:

Phase 1: EVALUATE
  "Was this non-obvious? Would future-me benefit?"
  → If YES to any, continue
         ↓
Phase 2: CHECK EXISTING
  Search .agents/skills/ for related skills
  → Nothing related? Create new. Overlap? Update existing.
         ↓
Phase 3: CREATE SKILL
  Write to .agents/skills/[name]/SKILL.md
  • Problem statement
  • Trigger conditions (exact errors, symptoms)
  • Step-by-step solution
  • Verification steps
         ↓
Phase 4: QUALITY GATE
  • Description has specific triggers?
  • Solution verified to work?
  • Specific enough to be actionable?
  • General enough to be reusable?

7.7.2.1 When to Use learn

The context monitor suggests learn at 40%, 55%, and 65% context usage. Consider extracting a skill when you encounter:

Trigger Example
Non-obvious debugging 10+ minute investigation not in docs
Misleading errors Error message was wrong, found real cause
Workarounds Found limitation with creative solution
Undocumented APIs Tool integration not in official docs
Trial-and-error Multiple attempts before success
Repeatable workflows Multi-step task you’d do again

7.7.2.2 Skill vs. [LEARN] Tag

Situation Use
One-liner fix [LEARN:category] tag in MEMORY.md
Multi-step workflow learn to create full skill
Error + root cause + solution learn if reusable, [LEARN] if not
Package quirk learn if affects multiple projects

Skills saved to .agents/skills/ survive compaction and session boundaries — if you discover something valuable late in a session, extract it with learn before compaction erases the details.

7.8 Pattern 8: Devil’s Advocate

At any design decision, invoke the Devil’s Advocate:

“Create a Devil’s Advocate. Have it challenge this slide design with 5-7 specific pedagogical questions. Work through each challenge and tell me what survives.”

This catches:

  • Unstated assumptions
  • Alternative orderings that might work better
  • Notation that could confuse students
  • Missing intuition before formalism
  • Cognitive load issues

A stronger variant: when Gemini reviews its own work in the same conversation, it suffers confirmation bias — it has internalized its own reasoning and will systematically find the work acceptable. The fix: spawn a new agent via the Task tool with NO access to the original conversation. Give it only the artifact and a critique prompt. The fresh agent has no sunk cost in the work and will be ruthless.

“Spawn a new agent. Have it read only my paper draft — not our conversation. Ask it to find the 5 weakest points and suggest how a hostile referee would attack each one.”

Like handing your draft to a colleague who wasn’t in the room when you wrote it.

7.9 Research Workflows

Patterns 1–8 apply broadly, with course materials as the primary example. The next four patterns are designed for research projects — papers, simulations, and empirical analysis — where the rhythm is different: ideas are uncertain, experiments may fail, and code is often written to answer a question rather than to ship. Patterns 13–14 then extend the foundation to reproducibility standards and presentation rhetoric.

7.9.1 Pattern 9: Parallel Agents for Research Tasks

Antigravity can spawn multiple agents simultaneously using the Task tool. This is not limited to review — you can use it for any research or analysis task where independent subtasks can run at the same time.

7.9.1.1 When to Use Parallel Agents

Scenario Sequential (slow) Parallel (fast)
Reviewing a lecture Run proofreader, then auditor, then pedagogy Run all 3 simultaneously
Analyzing 3 papers for a new lecture Read paper 1, then 2, then 3 Spawn 3 agents, each reading one paper
Generating figures Create plot 1, then plot 2, then plot 3 Spawn agents for independent plots
Comparing estimators Run simulation 1, then 2, then 3 Spawn agents for each simulation
Debating research design Consider DiD, then SC, then RDD 3 agents, each advocating one approach

7.9.1.2 How It Works

You do not need to manage this manually. Skills that implement the orchestrator pattern (create-lecture, review-paper --peer, slide-excellence, etc.) can recognize independent subtasks within their scope and spawn parallel subagents via context: fork — both during implementation (Step 1) and review (Step 3). For example, when slide-excellence runs on a deck, it spawns the visual / pedagogy / proofread agents in parallel; when review-paper --peer runs, it spawns the two referees in parallel. The parallelism is built into the skill’s logic, not into a repo-wide daemon.

You can also request parallelism explicitly:

“Read these three papers in parallel. For each, extract the key identification assumption, the main estimator, and whether they have a replication package. Summarize in a table.”

Either way, Gemini spawns up to 3 Task agents, each processing one paper simultaneously, then synthesizes the results.

7.9.1.3 Long-running tasks: Background Tasks and Schedulers

For genuinely long jobs — a 30-minute R fit, an audit-reproducibility batch over many tables, a Quarto render of a 200-slide deck — Antigravity allows launching processes as background tasks and scheduling notifications or check-ins. You can run long jobs in the background and let Antigravity notify you or proceed with other work in the meantime. No polling loop, no sleep cycles. Useful inside data-analysis for the regression step and inside audit-reproducibility when re-running the whole script suite.

7.9.1.4 Watching parallel agents

When several review agents run in parallel (such as the review-paper --peer editor and referee subagents, or slide-excellence’s visual, pedagogy, and proofread fan-out), you can list and monitor them using the subagent management tools. This allows you to track multiple background sessions on a single screen without opening one terminal per agent.

7.9.1.5 Agent Debates

A powerful variant: give each parallel agent a distinct methodological perspective and have them argue. Instead of asking “which estimator should I use?”, spawn 3 agents — one advocates for DiD, one for synthetic control, one for RDD — each arguing why their approach fits your research question best and critiquing the others. Synthesize the debate into a decision matrix. This produces genuinely diverse perspectives that a single conversation cannot, because each agent commits fully to its position.

7.9.1.6 Practical Limits

  • 3 agents is the sweet spot. More than that increases overhead without proportional speedup.
  • Agents are independent — they cannot see each other’s work. If task B depends on task A’s output, they must run sequentially.
  • Each agent consumes its own context window. For very large files, sequential processing may be more reliable.
TipCost-Conscious Parallelism

Parallel agents multiply token usage. For cost-sensitive tasks, run the expensive work (Opus agents) sequentially and the cheap work (Sonnet agents) in parallel. The orchestrator already does this: it runs Sonnet-level reviewers in parallel, then the Opus-level critic sequentially.

7.9.2 Pattern 10: Research Exploration Workflow

The exploration workflow provides a structured sandbox for experimental work.

7.9.2.1 The Problem

Without structure, experimental code scatters across the repository: analysis scripts in scripts/, test files in root, comparison documents in quality_reports/. After a week of exploration, the repo is cluttered with files that may or may not be useful, and nobody remembers which version was the good one.

7.9.2.2 The Solution: Exploration Folder

All experimental work goes into explorations/ first:

explorations/
├── [active-project]/
│   ├── README.md           # Goal, hypotheses, status
│   ├── R/                  # Code iterations (_v1, _v2)
│   ├── scripts/            # Test scripts
│   └── output/             # Results
└── ARCHIVE/
    ├── completed_[name]/   # Graduated to production
    └── abandoned_[name]/   # Documented why stopped

7.9.2.3 Fast-Track vs. Plan-First

The decision tree is simple:

Question Answer Workflow
“Will this ship?” YES Plan-First (80/100 quality)
“Am I testing an idea?” YES Fast-Track (60/100 quality)
“Does this improve the project?” NO Don’t build it

Fast-Track explorations skip formal planning. Instead, a 2-minute research value check gates the work: “Does this improve the paper/slides/analysis?” If the answer is “maybe”, explore. If “no”, skip. If “yes”, use Plan-First rigor.

7.9.2.4 The Lifecycle

Research value check (2 min)
  ↓
Create explorations/[project]/ (5 min)
  ↓
Code without overhead (60/100 quality)
  ↓
Decision point (1-2 hours):
  ├── Graduate → Move to R/, scripts/, tests/ (upgrade to 80/100)
  ├── Keep exploring → Stay in explorations/
  └── Abandon → Archive with brief explanation

The kill switch is explicit: at any point, you can stop, archive with a one-paragraph explanation, and move on. No guilt, no sunk cost. See .agents/rules/exploration-folder-protocol.md and .agents/rules/exploration-fast-track.md for the full protocols.

7.9.2.5 Simplified Orchestrator for Research

The full orchestrator (Pattern 2) is designed for course materials with multi-agent review loops. For research projects, the simple variant strips this down to: implement → verify → score → done. No multi-round reviews, no parallel agent spawning. This lives in its own path-scoped rule (.agents/rules/orchestrator-research.md) that loads only when working on R scripts or explorations.

7.9.2.6 Merge-Only Quality Reporting

In research projects, commits are frequent and incremental. Generating a quality report for each commit creates noise. Instead, quality reports are generated only at merge time — a permanent snapshot of what was merged and why. Session logs capture the ongoing reasoning. See .agents/rules/session-logging.md.

7.9.3 Pattern 11: Research Skills

Ten skills support the research workflow (including our mathematical and theoretical proof workflow):

Skill What It Does When to Use
lit-review [topic] Search, synthesize, and identify gaps in the literature Starting a new project or section
research-ideation [topic] Generate research questions, hypotheses, and empirical strategies Brainstorming phase
interview-me [topic] Interactive interview to formalize a vague idea into a concrete specification When you have an intuition but not a plan
review-paper [file] Full manuscript review with referee objections Before submission or after a draft
data-analysis [data] End-to-end R analysis: explore, regress, produce publication-ready output Empirical analysis phase
co-math-init Initialize a new AI co-mathematician research project Starting a new theoretical proof paper
co-math-status Render the current status of theoretical workstreams Tracking project progress
math-proof Write clear, detailed mathematical proofs Writing proofs for a paper
gemini-math Run Gemini 3.5 Pro as an adversarial co-processor (verify, write, explore modes) Verifying or exploring complex proof steps
proof-readability Audit math proofs for logical flow and readability Polishing mathematical proofs

These skills produce structured reports saved to quality_reports/. The data-analysis skill also generates R scripts (saved to scripts/R/) and runs the r-reviewer agent automatically.

Notereview-paper --peer [journal] — simulated peer review pipeline

For submission-ready manuscripts, review-paper --peer <journal> runs an editor + two dispositioned referees + editorial decision, calibrated to the target journal. Editor calibration reads .agents/references/journal-profiles.md; the template ships profiles for AER, QJE, JPE, ECMA, JoE (econ) and APSR, AJPS, JOP (poli-sci). Other fields: add a profile, ~40 lines each.

The methods-referee is paper-type-aware — the same skill picks different sanity checks based on what kind of paper this is:

Paper type Methods-referee tilts toward Sanity checks include
reduced-form identification credibility, parallel-trends defence, robustness range DiD pre-trends, IV first-stage, overlap, balance
structural model identification, counterfactual credibility, fit moment-matching, sensitivity to functional form, out-of-sample
theory+empirics model-data correspondence does the empirical estimand identify the theoretical object?
descriptive measurement validity, generalisability sampling frame, missingness, comparator choice
formal-theory (v1.8.0) model originality, comparative-static sharpness equilibrium existence, assumption tractability, robustness to relaxation
survey-experiment (v1.8.0) design, sampling, attrition + manipulation checks balance, manipulation-check pass rate, attrition asymmetry, sampling-frame validity

R&R continuation is built in: --r2 / --r3 for response-to-referees rounds; --stress for a hostile-editor stress test. See .agents/references/discipline-cards.md for econ + poli-sci defaults (paper-type frequency, dominant journals, preregistration norms, code conventions). Forkers extend for psych / sociology / public-health.

7.9.3.1 The Research Lifecycle as a Dependency Graph

A research project is not a waterfall — it is a dependency graph. Some phases run in parallel; others are strictly sequential:

research-ideation ─────┐
                        ├──→ lit-review ──→ data-analysis ──→ review-paper
interview-me ──────────┘         ↑               ↑
                                  │               │
                          (can run in parallel)   │
                                                  │
                          (enter mid-pipeline: ───┘
                           start with data and
                           work backwards)

Enter mid-pipeline. You do not have to start from ideation. If you already have data, start with data-analysis and work backwards to the research question. If you already have a draft, start with review-paper. The skills are modular — use what you need, skip what you don’t.

For a production-grade paper pipeline, a dedicated fork takes these same skills and wraps them in full research infrastructure: 6 worker-critic agent pairs plus specialized agents (data-engineer, referees, verifier), simulated blind peer review, weighted aggregate scoring, journal targeting, and R&R response routing. If your primary output is research papers, see The Ecosystem for details.

7.9.4 Pattern 12: Branch Isolation with Git Worktrees (Advanced)

NoteAdvanced Pattern

This pattern is optional and primarily useful for major translations, risky refactors, or multi-day projects. Most day-to-day work doesn’t need it.

Git worktrees create a separate working directory linked to the same repository. Each directory has its own branch but shares commit history. Subagents can use worktrees via the isolation: worktree field (see Advanced Agent Configuration).

your-project/                     ← main branch (stays clean)
.worktrees/lecture-06-quarto/     ← isolated branch (Gemini works here)

7.9.4.1 Why Use Worktrees?

Benefit Example
Safe experimentation Translate Lecture 6 to Quarto — if it fails, main is untouched
Clean history 50 intermediate commits squash into one clean commit
Easy discard Wrong approach? Delete worktree, no trace in main
Multi-session work Resume worktree next day, no context loss
Parallel work Work on slides (main) while Gemini translates (worktree)

7.9.4.2 The Workflow

1. CREATE WORKTREE
   git worktree add .worktrees/lecture-06-quarto -b quarto/lecture-06
   cd .worktrees/lecture-06-quarto
         ↓
2. IMPLEMENT
   All changes happen in the worktree
   Commit frequently (intermediate commits are OK)
         ↓
3. VERIFY
   Run tests, render, review against worktree only
         ↓
4. SYNC TO MAIN (when ready)
   git checkout main
   git merge --squash quarto/lecture-06
   git commit -m "feat: add Lecture 6 Quarto version"
         ↓
5. CLEANUP
   git worktree remove .worktrees/lecture-06-quarto
   git branch -d quarto/lecture-06

7.9.4.3 Commands Reference

# Create a worktree with new branch
git worktree add .worktrees/[name] -b [branch-name]

# List active worktrees
git worktree list

# Remove a worktree (after merging or abandoning)
git worktree remove .worktrees/[name]

# Delete the branch (after removal)
git branch -d [branch-name]

# Squash-merge into main
git checkout main
git merge --squash [branch-name]
git commit -m "feat: description of changes"
Noteworktree.baseRef (Apr 2026 Week 19)

Antigravity’s EnterWorktree tool branches fresh worktrees from a configurable base ref via the worktree.baseRef setting in .agents/settings.json:

  • fresh (default) — branch from the remote default branch (typically origin/main). Safest for clean experimentation.
  • head — branch from local HEAD. Use when you have uncommitted local work the worktree should inherit.

The default surprises users with uncommitted in-flight edits: a fresh worktree won’t see those changes. If your workflow assumes “branch off whatever I’m looking at now,” set "worktree.baseRef": "head".

7.9.4.4 When to Use

Situation Use Worktree?
Quick fix to one file No — just edit main
New lecture creation Maybe — if multi-session
Beamer → Quarto translation Yes — many intermediate states
Major refactor Yes — safe rollback
Experimenting with new approach Yes — easy discard

For example, translating Lecture 5 from Beamer to Quarto involves extracting TikZ diagrams, converting ggplot to plotly, and rewriting environments — dozens of intermediate files over multiple sessions. A worktree keeps main clean while you iterate.

7.9.4.5 Complexity Cost

  • Adds ~3 commands to learn
  • Adds mental model: “Where am I working?”
  • Requires discipline to sync/discard, not leave orphan worktrees

For most novice users, working directly on main with frequent commits is simpler and sufficient. Use worktrees when the benefits of isolation outweigh the added complexity.

7.10 Advanced Patterns: Reproducibility and Presentation Design

The patterns above use slides as the primary example, but the infrastructure is domain-agnostic. The next two patterns address dimensions no existing pattern covers: reproducibility standards and presentation rhetoric.

7.10.1 Pattern 13: Reproducibility & Replication Compliance

Pattern 5 covers matching someone else’s results before extending them. This pattern is the complement: packaging your own work so that others — and journal data editors — can verify it.

7.10.1.1 The AEA Data Editor Standard

The Template README for Social Science Replication Packages is the compliance standard for the AEA, Review of Economic Studies, Economic Journal, and other major journals. It requires eight structured sections:

Section What It Covers
Overview What the code does, data sources, software, runtime
Data Availability Statements Provenance, access rights, redistribution permissions for every data source
Dataset List Every data file: source, format, whether provided
Computational Requirements Software versions, packages, random seeds, memory, runtime
Description of Programs Directory structure, execution order, dependencies
Instructions to Replicators Numbered steps — ideally one command
Table/Figure Mapping Every exhibit mapped to the specific program and line that generates it
References Proper bibliographic citations for all data sources

The Table/Figure Mapping row is exactly what passport.yaml (v1.9.0) machine-encodes: each numeric claim → script + line + output file + tolerance + verified-on timestamp. The AEA requires the spreadsheet-style version; the passport is the programmatic version. They’re complementary — generate the AEA spreadsheet from the passport when you submit.

7.10.1.2 Pre-Submission Checklist

Documentation:

Code:

Data:

Verification:

7.10.2 Pattern 14: The Rhetoric of Decks

The slide-auditor checks technical quality (overflow, spacing). The pedagogy-reviewer checks teaching quality (notation density, prerequisites). Neither addresses rhetorical quality — whether the slides persuade, whether the argument flows, whether beauty serves function.

The Rhetoric of Decks framework fills this gap.

7.10.2.1 The Three Laws

Law 1: Beauty is function. Beautiful slides are not decorated slides. Beauty is clarity made visible. Every element earns its presence. Nothing distracts from the point. “Decoration without function is noise.”

Law 2: Cognitive load is the enemy. One idea per slide. ONE. This is not a guideline — this is the law. The audience has limited working memory. Every unnecessary word, data point, or “just in case” inclusion steals bandwidth from the actual message.

Law 3: The slide serves the spoken word. “If your slides can be understood without you speaking, you have written a document and called it a presentation.” The slide is a visual anchor for speech — a focal point for attention, a memory hook for retention.

7.10.2.2 The MB/MC Equivalence

The most original contribution of this framework — applying marginal analysis to slide design:

Optimal rhetoric equalizes the marginal benefit to marginal cost ratio across all slides: MB₁/MC₁ = MB₂/MC₂ = … = MBₙ/MCₙ

What this means in practice:

  • Overloaded slides (MB/MC too low): text running into footer, competing ideas, audience gives up
  • Underloaded slides (MB/MC too high): wasted opportunity, attention captured but unused
  • The goal is smoothness — consistent cognitive load throughout — not maximum density
  • Exception: deliberate “jump scares” — intentional spikes for rhetorical effect (a striking statistic, a provocative claim)

7.10.2.3 Actionable Principles

Principle Why Anti-Pattern
Titles are assertions “Treatment increased distance by 61 miles” carries the argument “Results” tells the audience nothing
Bullets are defeat A list says “I couldn’t find the structure” Find the sequence, contrast, hierarchy, or causal chain
White space signals confidence Crowded slides signal fear — fear of silence, fear of forgetting Filling every pixel with text
Direct labels, not legends Legends force the eye to travel; labels stay with the data Color-coded legends requiring a key
One message per chart If you can’t explain it in one sentence, it’s too complex Multi-panel figures with competing stories
Min 24pt body, max 2 fonts Sans-serif for projection; test from the back row 12pt text, decorative fonts

7.10.2.4 How Existing Agents Support This

The slide-excellence skill already invokes the pedagogy-reviewer and slide-auditor, which enforce many of these principles automatically. To enforce all of them — including title-as-assertion and MB/MC smoothness — customize the domain-reviewer agent (.agents/agents/domain-reviewer.md) with rhetoric-of-decks lenses. The orchestrator will then apply them during every review cycle without manual invocation.

For the complete philosophical treatment — from Aristotle’s three modes of persuasion through neuroaesthetics and the Netflix analogy — see The Rhetoric of Decks. The repository includes a full essay, example Beamer decks with professional color palettes, a theme_rhetoric() ggplot2 theme, and a tested deck generation prompt for Antigravity.

7.10.3 Pattern 15: Sequential Adversarial Audits

Principle: Run N independent audit passes, each focused on ONE dimension. Each auditor sees only the artifact — not previous audits — to prevent groupthink and anchoring bias.

This pattern differs from the parallel multi-agent review in Pattern 6. There, agents run simultaneously and findings are merged. Here, audits run sequentially, each producing an independent report. The independence is the point: a citation auditor shouldn’t be influenced by what the prose auditor flagged.

7.10.3.1 The Seven-Audit Protocol (for Papers)

Inspired by GeminiCodeTools “The Editor”, this protocol runs seven sequential passes before submission:

  1. Abstract audit — Does the abstract accurately reflect findings? Is it a compelling “storefront”?
  2. Introduction structure — Does the intro follow a recognized template (classic, puzzle-first, contribution-first)?
  3. Section-by-section audit — Data description, identification, results, robustness — each checked independently
  4. Argumentation audit — Logical gaps, alternative explanations, missing qualifications
  5. Prose quality — Passive voice, hedging, jargon density, paragraph flow
  6. Citation fidelity — Every claim has a citation? Every citation is real and correctly referenced?
  7. “So What” test — Five questions: What’s the question? Why does it matter? What did you find? How do you know? What does it mean?

7.10.3.2 How to Implement

Use review-paper for a comprehensive single-pass review. When you need deeper, independent audits (e.g., before journal submission), run each audit as a separate skill invocation with context: fork to ensure isolation:

You: "Run the seven-audit protocol on my paper"
Gemini: [Runs 7 sequential forked reviews, each blind to the others]
       → Produces 7 independent reports
       → Synthesizes into prioritized revision checklist

Adapting for other artifacts: The same principle works for replication packages (7 passes: code, data, documentation, licensing, runtime, outputs, README) or grant proposals (significance, approach, innovation, environment, budget).

For the R&R stage (after referee comments arrive): Use respond-to-referees [report] [revised-manuscript]. It parses each concern, classifies coverage (addressed / partially / deferred / disagreement), points to specific revisions, and drafts the response document using templates/response-to-referees.md.

7.10.4 Pattern 16: Preregistration and Submission Discipline

Principle: Lock in your hypotheses, design, and analysis plan before you see the realised data. Preregistration is the strongest defence against p-hacking, HARKing, and forking-paths, and it’s increasingly mandatory for credibility in social-science venues. Pair it with checkpoint for a verifiable trail of what you committed to and when.

7.10.4.1 When preregistration matters

  • Before launching an experiment (lab, field, or survey) — the canonical case.
  • Before analysing observational data on a target population for a specific RQ. “I have the data but haven’t looked at the outcome variable yet” is the right moment.
  • During R&R when a referee asks for a written preanalysis plan covering robustness specifications.
  • Funding — NSF, NIH, OSF, AEA grants increasingly require a PAP at submission.

7.10.4.2 Choosing a registry

The template ships three styles via preregister --style:

Registry Style flag Field Length Editable later?
OSF (osf.io/registries) osf Broad social science (default for psych, poli-sci, sociology) Long-form, ~10–20 pages Yes, with versioning
AsPredicted (aspredicted.org) aspredicted Behavioural / experimental short-form 9 questions, ~2 pages Locked once submitted
AEA RCT Registry (socialscienceregistry.org) aea-rct Economics field experiments (mandatory for AEA journals since 2018) Structured fields, ~3–5 pages Limited fields editable

For public health / clinical trials, use ClinicalTrials.gov or ISRCTN directly — this template’s preregister doesn’t cover those formats. They’re on the v2.0-backlog.

7.10.4.3 The workflow

interview-me                       preregister --style osf
   ↓                                   ↓
research-spec.md  ─────────────→  preregistration-draft.md
   ↓                                   ↓
(quality_reports/specs/)         (quality_reports/preregistrations/)
                                       ↓
                                  user reviews,
                                  uploads to OSF,
                                  receives registration ID
                                       ↓
                                  checkpoint preregistration-submitted
                                       ↓
                                  data collection begins

preregister reads your interview-me spec frontmatter (the paper_type: field flows in from there if you set it) and produces a registry-formatted draft with MUST / SHOULD / MAY annotations on every section. Pre-flight checks: directional hypothesis declared, named estimator, ex-ante exclusion rules, sample-size stopping rule.

7.10.4.4 Mandatory fields per registry style

The --style flag determines the mandatory section list. The template enforces these via the pre-flight check:

Field OSF AsPredicted AEA RCT
Directional hypothesis (with sign) MUST MUST MUST
Sampling frame + recruitment MUST SHOULD MUST
Sample-size / stopping rule MUST MUST MUST
Named primary estimator MUST MUST MUST
Pre-specified covariate set SHOULD MAY MUST
Multiple-comparison adjustment plan SHOULD SHOULD MUST
Ex-ante exclusion rules MUST MUST MUST
Robustness specifications (named in advance) SHOULD MAY SHOULD
Data-sharing plan SHOULD MAY MUST
Intervention description (RCTs) — — MUST

preregister refuses to draft a “retrospective preregistration” — if your description contains realised results or post-hoc reasoning, the skill halts and explains why. That refusal is the point.

7.10.4.5 Pairing with checkpoint

checkpoint is the structured companion to the narrative session-log workflow. For preregistration specifically:

  • Before submitting to the registry: checkpoint preregistration-pre-submit snapshots the draft state, the spec it derives from, and the next-action (“upload to OSF and record registration ID”).
  • After submission: checkpoint preregistration-submitted [registration-id] records the registry ID and the date in the structured snapshot. The plan and session log link to it.
  • On data arrival: checkpoint data-arrived marks the boundary between “things I could legitimately commit to” and “things I learned from looking.” Anything that follows is exploratory unless explicitly anchored in the preregistered plan.

checkpoint files live at quality_reportscheckpoints/YYYY-MM-DD_<slug>.md (gitignored — they’re session-state, not version-controlled artifacts). Optional --no-memory flag suppresses the auto-proposal of [LEARN] entries to MEMORY.md.

7.10.4.6 Post-flight verification

Any cited literature in the preregistration runs through verify-claims (Chain-of-Verification, forked-verifier context, fresh) before the draft is considered ready. Hallucinated citations are the most common preregistration failure mode and the hardest to fix after submission — gate-refusing them at draft time pays back many-fold.

7.10.4.7 What this pattern protects against

  • HARKing (Hypothesising After Results are Known) — the preregistered hypothesis pins the directional claim before observation.
  • p-hacking — the named estimator + named multiple-comparison plan removes the discretion that produces inflated false-positive rates.
  • Forking paths — every data-dependent choice is either declared MUST or disclosed as exploratory.
  • Selective reporting — the data-sharing plan + named robustness specifications make selective reporting visible to referees.

For econometrics, see Christensen & Miguel (2018) on transparency in development economics. For political science, see Monogan (2015) on the political-science case. For psychology, see the OSF Preregistration Guide.

7.10.5 Pattern 17: Large Datasets, Unstructured Filings & Out-of-Core Processing

Principle: When building empirical datasets from raw financial text (SEC EDGAR filings, regulatory disclosures) or multi-gigabyte databases, keep heavy data processing out-of-core and structured. Do not feed raw data directly into the model’s context window.

7.10.5.1 Unstructured to Structured Pipelines (e.g. SEC EDGAR)

  • Interactive Plan-First Design: Use /interview-me or interactive plan mode to define table schemas and parsing logic before writing scraper scripts.
  • Scraping & Parsing Rules: Write deterministic Python/R scripts to download raw HTML/XML filings, parse structured fields (items, tables, notes), and output clean Parquet or SQLite files.
  • Validation Gates: Inspect intermediate parsing reports before running full batch extractions.

7.10.5.2 Large Dataset Processing (DuckDB & Polars)

  • Out-of-Core Execution: Use DuckDB or Polars for large academic datasets that exceed RAM capacity.
  • Query Aggregation: Let the agent write SQL/Polars queries to summarize, index, and join massive tables on disk. Feed only summarized tables or regression-ready samples into statistical models (R fixest, Stata, or Python statsmodels).
  • Context Isolation: Keeps the agent’s context window lightweight and prevents out-of-memory crashes during large data transformations.