← Plugin catalog
Productivity

Elephant-Goldfish Model

Google v0.1.0

Draft and review documents

Create a free account to save this plugin.

From the developer

Declared capabilities

  • Develop ideas
  • Review documents
  • Check implementation drift

Not specified in the available declarations: limitations, pricing & account requirements.

Sources & dates

Developer declarations; not independently tested. Listing last checked Nov 5, 2026. Package observed Nov 5, 2026.

View package source →

Description

From the marketplace listing

Use AI to develop ideas, draft plans, and review documents. Independent reviewers check the work without the earlier conversation. Software tools also document codebases and check changes against specifications.

Language: English · Automatically detected from descriptions.

Changes

No changes recorded yet. Follow this plugin to keep track of future changes.

First seen Nov 5, 2026. Last seen Nov 5, 2026.

Files & skills

File archives

Plugin package54 files · 75.7 KBBrowse files →
Skill instructions
egm-bootstrap23.2 KB

View saved version →

---
name: egm-bootstrap
license: Apache-2.0
disable-model-invocation: true
description: Create or update documentation for an existing codebase.
---

# EGM Peanuts and Hay Bootstrap (`egm-bootstrap`)

When running in Codex or ChatGPT Work, first read [Codex integration](../../docs/codex.md).
In Claude Code or Cowork, read `${CLAUDE_PLUGIN_ROOT}/docs/claude.md` first.

## Overview

This skill automates the creation, correction, formatting, and correctness
verification of Elephant-and-Goldfish Model (EGM) compliant `README.md` files
across a directory tree. It establishes clear architectural contracts
(interfaces, invariants, and side effects) for both human developers and AI
assistants.

*   **Peanuts**: Leaf-level Component Package READMEs containing specific file
    contracts.
*   **Hay**: Parent-level Repository Blueprints that roll up child interface
    contracts into high-altitude indexes.

## Delegation

A Goldfish runs in a fresh context with no conversation history. Spawn each
subagent with your harness's subagent tool (Antigravity: `invoke_subagent`; Claude Code: `Agent`; Codex: `spawn_agent`). Each subagent is defined in `agents/<file>.md`, and its
frontmatter `name` (for example `egm-zoom-out`) is the subagent type to request
where your harness registers named subagents. Otherwise spawn a general-purpose
subagent and tell it to read that persona file first. Pass the prompt verbatim
and wait for the report. If your harness cannot nest subagents,
use direct dispatch instead of the synthesizer. See `docs/harnesses.md`.
If your harness has no subagent tool, run the scout steps inline.

## Inputs

*   **`path`**: The target root directory path to bootstrap (Required).
*   **`is_worker`**: Internal parameter. `true` if executing as a worker
    Sub-Orchestrator (Optional, default: `false`).
*   **`sub_tree_root`**: Internal parameter. The root path of the assigned
    subtree partition (Optional).
*   **`target_filename`**: Target contract filename to generate or update
    (Optional, default: `"README.md"`). Supports alternate blueprint filenames
    such as `"EGM.md"` when pre-existing human-maintained READMEs must not be
    modified.

## Execution Constraints (CRITICAL)

1.  **No Code Generation**: You are strictly limited to documentation. Do not
    write or refactor any functional source code.
2.  **VCS Isolation**: Do not perform any version control commits (`git commit`,
    `git add`). All filesystem changes must be written locally using standard
    file-writing tools. Tracking
    and submitting is deferred to the human user.
3.  **Temporary File Isolation**: Each worker keeps its status, checkpoint,
    and log files in its own directory outside the workspace (host scratch or
    `mktemp -d`), never a fixed, shared path. If neither exists, skip them.
4.  **Tool Usage (CRITICAL)**: Use your shell, file-reading, file-writing, and file-editing tools for directory discovery and contract/README
    generation. Adhere to clean Markdown formatting directly during generation
    (standard headers, tables, and fenced code blocks). If a project markdown
    formatter (e.g. `npx prettier --write`) is explicitly configured in the
    repository, it may optionally be invoked.
5.  **Subagent Delegation**: Spawn sub-orchestrator workers in parallel.
6.  **Mandatory Safety Gate (CRITICAL)**: If you discover more than 15
    subdirectories, you MUST immediately request user approval (using a structured question tool, if your harness has one, or plain chat) before proceeding with full-tree execution
    or unbounded subagent spawning.

---

## Workflow

### Step 0: Ecosystem & Verification Discovery

1.  Inspect the repository root for package/build manifests:
    *   Node.js / TypeScript: `package.json` -> `npm test` (or `pnpm test` / `yarn test`)
    *   Rust: `Cargo.toml` -> `cargo test`
    *   Go: `go.mod` -> `go test ./...`
    *   Python: `pyproject.toml` / `pytest.ini` / `setup.py` -> `pytest`
    *   C/C++ / Make: `Makefile` -> `make test`
    *   Bazel: `BUILD` / `BUILD.bazel` -> `bazel test //...`
    *   None found: `<test-command>`
2.  Record as `VerificationCommand` to populate generated README contracts.

---

### Step 1: Startup Branching Control

1.  Check the `is_worker` input parameter.
2.  If `is_worker` is `true`, jump directly to **Step 4: Sub-Orchestrator Worker
    Flow** to process the assigned `sub_tree_root`.
3.  If `is_worker` is `false` or unset, proceed as the Root Orchestrator to
    **Step 2: Incremental Scoping & Safety Gate**.

---

### Step 2: Incremental Scoping & Safety Gate (Root Orchestrator)

1.  **Incremental BFS Discovery**: Map the target `path` tree level-by-level
    (BFS) using a directory queue, listing one directory level at a time. (CRITICAL: never run a recursive search such as `find` or `ls -R`.)

    *   Preserve intermediate folder nodes.
    *   Ignore symbolic links to prevent infinite recursion.
    *   Ignore hidden/system directories (`.git`, `.antigravity`, `node_modules`,
        `venv`, `dist`, `build`, `third_party`).
    *   Read `.gitignore` and `.egmignore` (if present) and ignore matching glob patterns.
    *   Preserve package and build manifests (`package.json`, `Cargo.toml`,
        `go.mod`, `pyproject.toml`, `Makefile`, `BUILD`) in the discovery map
        to extract verification targets later.

2.  **Safety Gate & Unbounded Spawning Approval (CRITICAL)**: During the BFS
    loop, if the total running count of discovered directories exceeds **15**,
    immediately pause discovery and request user approval (using a structured question tool, if your harness has one, or plain chat) to warn the user and request approval
    for full-tree execution:

    *   `question`: "The target directory tree contains more than 15
        subdirectories. This is a large execution scope. Do you want to proceed
        with full-tree bootstrapping?"
    *   `options`: `["Yes, proceed with full tree bootstrapping",
        "No, abort execution"]`
    *   (CRITICAL: After requesting approval, you MUST wait for the user's
        response before continuing or spawning any workers).
    *   If the user selects abort, terminate execution immediately.

3.  **Bottom-up Post-Pruning Pass**: Once mapping is complete (and approved),
    walk the mapped tree bottom-up (leaves to root). Filter out non-code and
    test-only directories:

    *   *Source Code Files*: Files matching recognized source code, schema, and
        contract extensions:
        - Systems & Compiled: `.c`, `.cc`, `.cpp`, `.cxx`, `.h`, `.hh`, `.hpp`,
          `.rs`, `.go`, `.zig`, `.lean`
        - Managed & Enterprise: `.java`, `.kt`, `.scala`, `.cs`, `.fs`
        - Scripting & Dynamic: `.py`, `.rb`, `.php`, `.lua`, `.sh`, `.bash`
        - Web & Mobile: `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.swift`,
          `.m`, `.dart`
        - Data & Schemas / IDLs: `.sql`, `.proto`, `.graphql`, `.gql`,
          `.thrift`, `.prisma`
        - Infrastructure / Declarative Code: `.tf`, `.hcl`, `.cue`
        (Excludes build manifests, lockfiles, test fixtures, documentation, and
        generic data dumps like `.csv`, `.tsv`, `.parquet`).
    *   *Test Directory Exclusion*: Exclude directories containing exclusively
        test code (e.g. named `tests`, `testing`, `testdata`, or containing only
        files matching `*_test.*`, `*Test.*`, `test_*.*`, or `*.spec.*`).
    *   *Non-Code Filtering*: Exclude any directory that contains no source code
        files AND contains no subdirectories with code. Retain empty
        intermediate folders only if they have child directories that contain
        code.

4.  Calculate the total count of pruned directories and maximum depth. Proceed
    to **Step 3: Execution Strategy Selection**.

---

### Step 3: Execution Strategy Selection (Root Orchestrator)

1.  **Direct Execution Strategy (Directory Count <= 5)**:

    *   If the total count of pruned directories is 5 or fewer, execute the bottom-up
        documentation directly in the current thread.
    *   Jump to **Step 4: Sub-Orchestrator Worker Flow** (treating the Root
        Orchestrator as the worker for the entire `path`), and then proceed to
        **Step 5: Root Compilation & Termination**.

2.  **Unbounded Parallel Subagent Swarm Strategy (Directory Count > 5)**:

    *   (CRITICAL: If Directory Count > 15, you MUST verify that you have
        received explicit user approval before proceeding. If not yet approved,
        request approval immediately and wait for the user's response before
        spawning workers).
    *   Partition the discovery map into independent subtree branches using the
        **Adaptive Depth Partitioning Algorithm**:
        1.  Set `depth = 1`.
        2.  Extract directory nodes from the discovery map located at the
            current `depth`.
        3.  If the count of nodes at `depth` is between 3 and 5: select these
            nodes as subtree partition roots.
        4.  If the count of nodes at `depth` < 3: increment `depth` (up to a max
            of 3) and repeat step 2.
        5.  If the count of nodes at `depth` > 5: group the largest branches (by
            total nested folder count) into 3-4 separate partitions, combine the
            remaining small branches into a single fallback partition subtree,
            and select these as partition roots.
        6.  Fallback: If `depth` reaches 3 and count is still < 3, select the
            immediate children of the root (or fall back to sequential
            execution).
    *   **Spawn Unbounded Sub-Orchestrators**: For each partition subtree root,
        use your harness's subagent tool to spawn a parallel worker:
        *   Subagent: `egm-bootstrap-orchestrator` (`agents/bootstrap_orchestrator.md`) (or a general-purpose subagent)
        *   `Prompt`: "Run egm-bootstrap with path=`[path]`,
            is_worker=true, sub_tree_root=`[partition_root]`,
            target_filename=`[target_filename]`."
    *   **Unbounded Execution**: Spawn all Sub-Orchestrators in parallel without
        artificial concurrency limits (as authorized by the user during the
        safety gate).
    *   Go idle and wait for all worker subagents to return their JSON subtree
        index payloads. Jump to **Step 5: Root Compilation & Termination**.

---

### Step 4: Sub-Orchestrator Worker Flow

1.  **Scout Registration**: Use a read-only `goldfish-explorer` scout. Where your harness supports defining subagents at runtime, register it with:

    *   `name`: `goldfish-explorer`
    *   `description`: `Read-only codebase explorer scout.`
    *   `system_prompt`: >- You are a read-only codebase explorer. Your task is
        to analyze the source files in the target directory and return a
        concise, factual summary. Do not write or modify any files. Return a
        JSON object containing the directory's public symbols (interface),
        invariants, and side effects matching schema: {"interface": [],
        "invariants": [], "side_effects": []}. Never infer RPC methods,
        routes, status enums, or invariants from file or directory names
        alone; cite the exact `[file:symbol_or_flag]` for every entry, and
        output `["None"]` if no explicit invariants or side effects exist in
        code.
    *   `enable_write_tools`: `false`
    *   `enable_subagent_tools`: `false`

2.  **Post-Order Traversal**: Walk the assigned `sub_tree_root` (or `path`) in
    post-order (deepest leaves first). For each directory `D`:

    *   **Correction & Modification Policy**: Check if `target_filename` (default:
        `README.md`) already exists in `D`.

        *   If `target_filename` exists, **do not overwrite it completely**. Instead,
            read its existing content.
        *   *Scout Scan Requirement*: Whether `target_filename` exists or not,
            **always scan** the source code using the `goldfish-explorer` scout
            for `D` to compile the true code symbol boundary.
        *   *Legacy Extraction & Correction*: If `target_filename` exists, call the
            reasoning LLM with prompt: > "Analyze the following unstructured
            documentation content. Extract all public symbol names, classes,
            interfaces, invariants, and side effects. Format your response
            strictly as a JSON object matching the following schema: {
            \"interface\": string[], \"invariants\": string[], \"side_effects\":
            string[] }." Merge these extracted symbols with the scout's code
            symbols. Use your file-editing tool (or your file-writing tool) to correct
            and update the existing contract file to be EGM compliant while preserving
            developer notes and descriptions.

    *   **Scout Spawning & Constraints**: Spawn `goldfish-explorer` for `D`.

        *   *Scout Constraints*: No per-directory or per-file byte cap; every
            non-test file in `D` is read in full. Bound each scout call to
            about **1,500 lines** of source instead: list top-level definitions
            (class/func/def/route/flag lines) with your search tool, cut the
            directory's files into chunks at those boundaries (never mid-body;
            small files share a chunk), spawn one `goldfish-explorer` per
            chunk in parallel, and merge their JSON. Give each chunk the
            file's imports and top-level definition list so it can judge
            visibility. Check build-manifest deps and `import` / `#include`
            statements before attributing an RPC service, schema, or message
            type to a local file. Read non-test files in this order:
            1.  Contracts, schemas, and build manifests (`.h`, `.hh`, `.hpp`,
                `.proto`, `.graphql`, `.gql`, `.thrift`, `.prisma`, `.sql` DDL,
                interface classes); extract exact DDL table names and exported
                build targets.
            2.  Module entry points (`main.*`, `index.*`, `lib.*`, `mod.*`,
                `__init__.py`, or files matching directory name), then
                production source/query files alphabetically.
            3.  Templates and configs: up to 200 lines each (800 in config-only
                directories); exclude `.css`/`.scss`.
            4.  Test files (`*_test.*`, `*Test.*`, `test_*.*`, `*.spec.*`):
                ignore entirely, including in hybrid directories.
        *   *Child Fault Tolerance*: If the scout fails or times out, log a
            warning, use placeholder values `["(Details pending/documentation
            failed)"]`, and continue execution.

    *   **Parent Context Propagation**: When processing a parent directory `P`,
        retrieve the compiled interface summaries of its immediate child
        subdirectories.

        *   *Propagation Heuristics*:
            1.  If the child was documented during this run, retrieve its public
                interface directly from the in-memory execution cache.
            2.  If the child was corrected/modified (Correction Policy), use the
                merged legacy extraction symbols.
        *   Pass these child symbol blocks as prompt context when invoking `P`'s
            explorer scout.

    *   **Verification Command Target Lookup**: Populate the Verification section
        using the discovered `VerificationCommand`.
        *   If the project uses Bazel/BUILD files: check if a `BUILD` file exists
            in `D` or the nearest ancestor, referencing `bazel test` / `bazel build`
            with valid target patterns (`//[package_path]/...` or
            `//[package_path]:all`, never `//[package_path]...` or
            `//[package_path]:...`). Use `bazel run` for interactive runner
            targets.
        *   If the project uses other manifests (`package.json`, `Cargo.toml`,
            `go.mod`, `pyproject.toml`, `Makefile`), populate with the corresponding
            test runner command.
        *   If no verification command is identified, omit or use a placeholder.

    *   **Directory Classification & Template Generation**: Generate or correct
        `target_filename` using your file-writing tool or your file-editing tool based on
        `D`'s classification.

        *   **Component Package (Peanut)**: `D` contains direct source code
            files. Use the **Component Package README Template**. (If it also
            has child subdirectories, include relative links to their contracts
            in the Interface section).
        *   **Repository Blueprint (Hay)**: `D` contains no direct source code
            files, but contains subdirectories with code contracts. Use the
            **Intermediate Blueprint README Template**.
        *   **Link Formatting Policy (CRITICAL)**: Package contract files must use a
            hybrid link formatting approach to balance portability and clarity:
            1.  **Relative Links to Existing Files Only**: Use relative paths
                (e.g., `./child/${target_filename}` or `../sibling/${target_filename}`) for child
                contracts and sibling file references within the same codebase
                subsystem. (CRITICAL: Only generate `[Child](./child/${target_filename})`
                links for child directories that exist in the pruned
                `subtree_index` and contain an actual `${target_filename}`. If a child
                directory contains a `SKILL.md` or other non-contract asset, link
                directly to `./child/SKILL.md` or format it as an unlinked
                bullet point. Never output speculative links to non-existent
                contract files).
            2.  **Absolute Links**: Use standard URLs or repository paths
                for referencing files outside the package subsystem (e.g.,
                cross-package dependencies).

    *   **Markdown Formatting**: Immediately after writing or correcting
        `target_filename` in `D`, ensure clean markdown formatting (valid headers,
        tables, and code fences). If a project markdown formatter (e.g. `npx prettier --write`)
        is configured in the repository, you may execute it on `target_filename`.

3.  **Worker Reporting**: Once the assigned subtree is fully traversed, compile
    the `subtree_index` array containing the `path`, `summary`, `interface`,
    `invariants`, and `side_effects` for every processed directory.

4.  If `is_worker` is `true`, read the [Worker Return Interface Schema](references/worker-return.schema.json)
    relative to this skill directory, then return a matching JSON payload to
    the Root Orchestrator and terminate. If
    `is_worker` is `false` (sequential mode), proceed directly to **Step 5: Root
    Compilation & Termination**.

---

### Step 5: Root Compilation & Termination (Root Orchestrator)

1.  **Receive Worker Payloads**: Collect the JSON `subtree_index` payloads
    returned by all parallel Sub-Orchestrators.

    *   **Root Fault Tolerance**: If a parallel worker fails or times out, log a
        warning, insert a placeholder warning link (`[Subtree Root]
        (Documentation failed / Subagent execution timeout)`) in the root
        Blueprint's subdirectory index, and complete the remaining compilation.
        (Worker failures leaving partial files are handled as an incremental
        progress feature; the Correction Policy allows resuming on subsequent
        runs).

2.  **Intermediate Directory Documentation**: Identify any intermediate
    directories sitting between the root `path` and the partitioned subtree
    roots.

    *   Process these intermediate directories sequentially bottom-up.
    *   Generate Intermediate Blueprint contract files using the compiled summaries
        returned by the workers.
    *   Ensure clean formatting and valid relative links for each Intermediate
        Blueprint contract file.

3.  **Root Directory Documentation**: The target root `path` of the execution is
    *always* classified as the **Repository Root (Blueprint / Hay)**.

    *   Check if `target_filename` already exists in `path`. If present, apply the
        **Correction & Modification Policy** to read and retain the existing
        title, metadata, and architectural overview at the top of the root
        contract file.
    *   Check if `path` itself contains any direct source files. If present,
        spawn a `goldfish-explorer` scout for `path` to extract local symbols
        and invariants, appending them under the optional `## Local Interface &
        Invariants` section.
    *   Compile the final root `target_filename` using the **Repository Root Blueprint
        Template**, rolling up all top-level subdirectory boundaries. Ensure any
        root architecture or sequence diagrams strictly match the synchronous /
        asynchronous boundaries, operation names, and storage backends in the
        child `subtree_index` payloads without inventing unverified nodes.
    *   Write the root `target_filename` using your file-writing tool.

4.  **Final Correctness Verification (CRITICAL)**: You MUST perform a final
    verification pass across ALL created and modified contract files in the
    `subtree_index` (including all child package contracts like `pkg1/${target_filename}`
    and `pkg2/${target_filename}`) as a correctness check before concluding work. You
    MUST explicitly read every single created or modified contract file
    to verify its content. Do not skip any child contract files. Verify:

    *   **EGM Compliance & Code Grounding**: Ensure `Interface`, `Invariants`,
        and `Side Effects` sections exist, cite real code symbols/flags/tables
        from the scout extraction, and contain zero speculative or unverified
        claims.
    *   **Markdown Syntax**: Ensure clean headers, valid tables, and proper code block fences.
    *   **Valid & Resolvable Links (CRITICAL)**: Ensure all subdirectory and
        sibling links use valid relative paths (`./subdir/${target_filename}` or
        `./subdir/SKILL.md`), and explicitly verify that every referenced target
        file actually exists on the filesystem. Remove or correct any broken
        relative references.
    *   **Valid Targets**: Verify verification targets match project test
        configuration and use valid target syntax (for Bazel, `/...` or
        `:all`, never `:...`).

5.  **Optional Drift Review (CRITICAL)**: After verification, ask the user (using
    a structured question tool, if your harness has one, or plain chat) to offer running a drift report
    on the generated documentation updates:

    *   `question`: "Do you want to run the EGM Drift Report on the generated
        contract updates to check for consistency with the codebase?"
    *   `options`: `["(Recommended) Yes, run drift report on modified contracts",
        "No, skip drift review"]`
    *   If the user selects "Yes", run the `egm-drift-report` skill targeting
        the modified contracts to verify both missing code coverage and
        doc-to-code hallucinations (verifying every documented method, route,
        enum, database table, and invariant against local source files and
        recording discrepancies in the drift report for human triage). (Note:
        While `egm-drift-report` is often used for design documents, it can be
        applied to EGM-compliant contracts as a variant).

6.  Terminate execution successfully.

---

## Templates

Before writing any contract file, read the
[README templates](references/templates.md) relative to this skill directory.
It defines the **Component Package (Peanuts)**, **Repository Root (Blueprint /
Hay)**, and **Intermediate Blueprint** README templates referenced above.

Referenced files: 4 — file references are metadata, not package contents.

egm-brainstorm14.2 KB

View saved version →

---
name: egm-brainstorm
license: Apache-2.0
disable-model-invocation: true
description: Test an idea and write a concept brief.
---

# EGM Brainstorm: Interactive Multi-Lens Ideation & Refinement

When running in Codex or ChatGPT Work, first read [Codex integration](../../docs/codex.md).
In Claude Code or Cowork, read `${CLAUDE_PLUGIN_ROOT}/docs/claude.md` first.

## Overview

This skill acts as the upstream conversational brainstorming engine for the
Elephant-Goldfish Model (EGM). It turns "half-baked" or raw concepts into
hypotheses by combining **interactive clarifying questions** with an automated
**Goldfish review**. The outcome is an iteratively refined RFC summary
(`concepts_brief.md`) that leads directly into `/egm-draft` or review with
peers.

## Delegation

A Goldfish runs in a fresh context with no conversation history. Spawn each
subagent with your harness's subagent tool (Antigravity: `invoke_subagent`; Claude Code: `Agent`; Codex: `spawn_agent`). Each subagent is defined in `agents/<file>.md`, and its
frontmatter `name` (for example `egm-zoom-out`) is the subagent type to request
where your harness registers named subagents. Otherwise spawn a general-purpose
subagent and tell it to read that persona file first. Pass the prompt verbatim
and wait for the report. If your harness cannot nest subagents,
use direct dispatch instead of the synthesizer. See `docs/harnesses.md`.
If your harness has no subagent tool, stop and tell the user: a review in the same context is not a Goldfish review.

## Execution Constraints (CRITICAL)

1.  **Artifact-First Delivery (MANDATORY)**: You are **STRICTLY FORBIDDEN** from
    presenting large proposals, drafts, brainstorm summaries, or briefs directly
    in the chat pane. You **MUST** write/update them directly to a file (e.g.,
    `./concepts_brief.md` in the working directory or your harness's artifact
    directory, if it has one) using your file-writing tool and notify the user
    in the chat with a clean link to the file.
2.  **Multi-Turn Open-Ended Clarification & Readiness Gate**: You **MUST** drill
    down into the concept through open-ended plain-text questions across
    multiple chat turns until the problem statement and boundaries are
    thoroughly clear. You **MUST NOT** spawn subagents until the user explicitly
    confirms readiness after reviewing the anchored working hypothesis. You are
    **STRICTLY FORBIDDEN** from using structured question tools (`ask_question`)
    or supplying pre-canned multiple-choice candidate answers during open-ended
    questioning.
3.  **Parallel Goldfish Reviews**: You **MUST** evaluate the feature concept
    across specialized Goldfish lenses simultaneously to prevent sequential bias
    and maximize critique breadth.
4.  **Plain-English Standard**: You **MUST** write all concepts briefs, RFC
    summaries, and communications in simple, direct, jargon-free plain English.
    Explain technical mechanisms directly. Do not summarize away substance or
    rely on buzzwords. Do not use ungrounded promotional adjectives (e.g.,
    *seamless*, *robust*, *blazingly fast*) or decorative adverbs (e.g.,
    *seamlessly*, *effortlessly*, *literally*, *drastically*, *obviously*).
5.  **Default to Stress-Testing**: Never agree by default. Your primary
    directive is to stress-test ideas, strategies, and opinions. Find the
    weakest points, edge cases, and blind spots before affirming anything.
6.  **No Glazing**: Eliminate sycophancy. Do not call ideas "great,"
    "brilliant," or "smart." Compliments without substance are noise.
7.  **Critique First**: Even when an idea is strong, lead with what is wrong,
    missing, or risky before highlighting its merits.
8.  **Reject Echo-Chamber Framing**: Never parrot framing back to the user. If a
    conclusion is asserted, do not validate it reflexively.
9.  **Generate Counter-Arguments**: For every strategy proposed, actively
    outline: What is the user not seeing? What is the strongest
    counter-argument? Is the opposing view justified?
10. **Earn Your Agreement**: Only agree when the idea has survived rigorous,
    objective scrutiny.
11. **Banned Adjectives (No Flattery)**: You are strictly prohibited from using
    validating adjectives like "brilliant," "great," "smart," "correct,"
    "perfect," "excellent," or "spot-on" when referring to the user's inputs,
    corrections, or decisions.
12. **Banned Apologies**: You MUST NOT output polite apologies (e.g., "I
    apologize," "I am sorry," "Forgive me") when challenged or corrected.
    Instead, outline the corrected technical logic or trade-offs directly.
13. **Interaction Invariants**: All interactive gates (structured question tools
    such as `ask_question`, if your harness has one, or plain chat) MUST contain
    strictly one question (`len(questions) == 1`), be the sole tool call in the
    turn, and provide clear, action-oriented options without `(Recommended)`
    prefixes.

## The Goldfish Brainstorming Lenses

| Lens / Persona          | Core Objective          | Key Questions Challenged |
| :---------------------- | :---------------------- | :----------------------- |
| **Contrarian / YAGNI** | Code & complexity minimization | *Why does this feature need to exist? Can an existing library, open-source dependency, API, or service solve 90% of this problem without writing new code?* |
| **Cost, Quota & Token Economics** | Infrastructure & budget scaling | *What is the peak QPS, memory footprint, database query load, or LLM token budget? Will this hit quota ceilings at scale?* |
| **UX & Developer Ergonomics** | Usability & cognitive overhead | *Is the API/CLI intuitive? Does it match ecosystem conventions? Are error messages actionable, or does it add developer friction?* |
| **Migration & Backward Compatibility** | Rollout safety & version skew | *How do existing clients/data migrate? Does this break serialized schemas, protos, or persistent storage? How is rollback handled mid-migration?* |
| **Observability & SRE Debuggability** | Telemetry & operational visibility | *Are key operations traceable via distributed tracing? Are telemetry metrics actionable? How will oncall engineers triage a production incident at 3 AM?* |
| **Long-Term Tech Debt & Maintenance** | Future maintainability | *Does this introduce tightly coupled dependencies or brittle state machines that will be painful to maintain in 2 years?* |

## Execution Workflow

### Step 1: Deep Clarification & Problem Statement Drilling

1.  **Check for Concept Foundation & Author Identity**: Verify if the user provided an initial
    feature idea or concept prompt. If missing, prompt the user to describe what
    they want to brainstorm. Resolve the brief's `Author` from `git config user.name`,
    then `GIT_AUTHOR_NAME`; if neither is set, ask in chat.
2.  **Iterative Problem Drilling (Multi-Turn Chat)**: Do **NOT** rush into
    launching subagents after a single response. Continue asking targeted,
    open-ended clarifying questions across multiple chat turns as needed until
    the problem statement, constraints, and target behavior are thoroughly
    defined. Do NOT use structured question tools (`ask_question`) and do NOT
    provide candidate multiple-choice options during problem exploration. Ask
    open-ended questions directly in chat:

    *   *What specific problem, bottleneck, or pain point does this solve?*
    *   *Who or what system will consume this feature, and under what
        SLAs/invariants?*
    *   *What are the hard non-negotiable constraints (e.g., zero false
        positives, offline operation, specific platform/dialect)?*
    *   *What are the edge cases or out-of-scope boundaries?*
    *   *How is this issue dealt with today? Why doesn't that work?*
    *   *How is success going to be measured?*

3.  **Readiness Checkpoint Gate (Single-Select)**: Once a clear foundation is
    established, summarize the anchored working hypothesis in 2-3 sentences.
    Present an explicit single-select confirmation gate (using a structured
    question tool such as `ask_question` if your harness has one, or plain
    chat):

    ```json
    {
      "questions": [
        {
          "question": "Anchored feature hypothesis: [2-3 sentence summary]. How would you like to proceed?",
          "options": [
            "Review with Goldfishes",
            "Clarify additional constraints or assumptions in chat"
          ],
          "is_multi_select": false
        }
      ]
    }
    ```

    *   **Option 0: `Review with Goldfishes`**: The user confirms readiness.
        Proceed immediately to Step 2 (Goldfish Review & Synthesis) to invoke
        `egm-synthesizer`.
    *   **Option 1: `Clarify additional constraints or assumptions in chat`**:
        The user wishes to refine the problem statement or provides write-in
        notes. Stay in Step 1, yield the turn in chat for details, incorporate
        feedback into the hypothesis, and re-present the readiness gate when
        ready.

4.  **Proceed to Step 2 ONLY** after Option 0 is confirmed. Do NOT spawn
    subagents before this gate confirms readiness.

### Step 2: Goldfish Review & Synthesis

1.  **Delegate to Synthesizer Subagent**: Spawn the intermediate
    **`egm-synthesizer`** agent (or parallel Goldfish subagents across the 6
    specialized lenses if your harness cannot nest subagents):
    *   Subagent: `egm-synthesizer` (`agents/synthesizer.md`)
    *   `Prompt`: >- Conduct multi-lens brainstorm for feature concept:
        `[AnchoredFeatureHypothesis]`. Mode: `BRAINSTORM`. Reviewers:
        `[egm-design, egm-codebase-details, egm-zoom-out, egm-comprehension,
        egm-implementation-readiness, egm-structural]`.
2.  **Synthesizer Execution**: The `egm-synthesizer` subagent launches the
    parallel Goldfish reviewers across the specialized lenses (`egm-design`,
    `egm-codebase-details`, `egm-zoom-out`, `egm-comprehension`,
    `egm-implementation-readiness`, `egm-structural`) with `Mode: BRAINSTORM`.
3.  **Deduplication**: Collect the raw findings from the Goldfish reviewers,
    deduplicate overlapping points, and format them into a cohesive analysis.
4.  **Write/Update Artifact**: Format and write the synthesized brief to
    `concepts_brief.md` in the working directory (or your harness's artifact
    directory, if it has one) using your file-writing tool.

The `concepts_brief.md` artifact follows this structure:

```markdown
# [Feature Name]

* **Author:** [Author Name or GitHub Handle]
* **Date:** [YYYY-MM-DD]

## Overview

[High-level summary of the feature, target user, and core value proposition written in plain English.]

## Analysis

[Cohesive analysis found by review lenses written in plain English.]

## Goals vs. Non-Goals

* **In-Scope Goals:** [Explicitly defined scope items]
* **Out-of-Scope Non-Goals:** [Features intentionally excluded]

## Alternatives Weighed

[Each option rejected during ideation, with the technical reason (e.g. "Rejected by author: <reason>"). Do not attribute a rejection to a maintainer without linking their issue, discussion, or PR. `/egm-draft` copies
these into Alternatives Considered and has no other source for them.]

## Key Decisions & Staging for Next Steps

[Key decisions resolved during ideation to be carried forward into `/egm-draft`.]
```

### Step 3: Interactive Iteration & Refinement Loop

1.  **Notify & Highlight (No Chat Dumps)**: Notify the user in chat that
    `concepts_brief.md` has been updated (give its path). Highlight 2-3 key
    objections or open risks raised by the Goldfish reviewers.
2.  **Iterate**: Ask the user how they wish to address the Goldfish objections
    (e.g., pivoting the approach, narrowing scope, or adding constraints).
3.  **Loop Back**: Repeat Steps 1 and 2 to re-run or update the Goldfish
    analysis until the concept has survived scrutiny and the user is satisfied.

### Step 4: Finalize & Handoff

1.  **Artifact Alignment**: Ask the user to review the final `concepts_brief.md`
    artifact and confirm their alignment.
2.  **Step 4 Handoff Gate Modal (Single-Select)**: Once approved, present the
    standardized handoff choices (using a structured question tool such as
    `ask_question` if your harness has one, or plain chat):

    ```json
    {
      "questions": [
        {
          "question": "Brainstorming complete. concepts_brief.md is finalized. Select next step:",
          "options": [
            "Publish concepts_brief.md as RFC for team feedback",
            "Proceed to egm-draft (Initialize formal design document)",
            "Continue refining concepts_brief.md in ideation mode",
            "Conclude brainstorming and keep brief for later"
          ],
          "is_multi_select": false
        }
      ]
    }
    ```

    *   **Option 0: `Publish concepts_brief.md as RFC for team feedback`**:
        *   Write `concepts_brief.md` to `docs/designs/<feature_name>.md` using
            your file-writing tool.
        *   Register the RFC in `docs/designs/SITEMAP.md` if it exists.
        *   Notify the user in chat that the RFC has been published and can be
            shared with the team for feedback before formal drafting. Remind the
            user that once feedback is gathered, a detailed design can be
            initiated by starting the `egm-draft` skill on
            `docs/designs/<feature_name>.md` with the host's command form (for
            example `/egm:egm-draft docs/designs/<feature_name>.md` in Claude
            Code and agy CLI, or the skill picker in Codex).
    *   **Option 1: `Proceed to egm-draft (Initialize formal design
        document)`**:
        *   Confirm that `concepts_brief.md` is saved in the working directory
            or artifact directory.
        *   Instruct the user to start the `egm-draft` skill with the host's
            command form (for example `/egm:egm-draft` in Claude Code and agy
            CLI, or the skill picker in Codex), noting that it automatically
            ingests `concepts_brief.md` as its Priority 1 intake source.
    *   **Option 2: `Continue refining concepts_brief.md in ideation mode`**:
        *   Return to Step 3 iteration loop to drill into further edge cases or
            update the brief based on user chat input.
    *   **Option 3: `Conclude brainstorming and keep brief for later`**:
        *   Conclude the session gracefully. Remind the user that
            `concepts_brief.md` remains saved for future reference.

Referenced files: 2 — file references are metadata, not package contents.

egm-draft16.9 KB

View saved version →

---
name: egm-draft
license: Apache-2.0
disable-model-invocation: true
description: Turn a brief or existing notes into a design document.
---

# Design Drafting (Document Construction)

When running in Codex or ChatGPT Work, first read [Codex integration](../../docs/codex.md).
In Claude Code or Cowork, read `${CLAUDE_PLUGIN_ROOT}/docs/claude.md` first.

This skill guides the user through drafting a technical design document based on
the aligned problem and requirements from the brainstorm phase.

## Execution Constraints (CRITICAL)

1.  You **MUST** read and apply the
    execution instructions in `resources/execution_instructions.md`.
2.  **Artifact-First Delivery (MANDATORY)**: You are **STRICTLY FORBIDDEN** from
    presenting large proposals, drafts, summaries, or plans directly in the chat
    pane. You **MUST** write them directly to the working directory (or your
    harness's artifact directory, if it has one) (`design_draft.md` or
    `./design_draft.md`) using your file-writing tool and tell the user in chat
    the file path and ask for review. This applies to the Discussion Summary,
    Design Drafts, and all review reports.
3.  **Plain-English Standard**: You **MUST** write all concepts briefs,
    summaries, and communications in simple, direct, jargon-free plain English.
    Explain technical mechanisms directly. Do not summarize away substance or
    rely on buzzwords. Do not use ungrounded promotional adjectives (e.g.,
    *seamless*, *robust*, *blazingly fast*) or decorative adverbs (e.g.,
    *seamlessly*, *effortlessly*, *literally*, *drastically*, *obviously*).
4.  **Default to Stress-Testing**: Never agree by default. Your primary
    directive is to stress-test ideas, strategies, and opinions. Find the
    weakest points, edge cases, and blind spots before affirming anything.
5.  **No Glazing**: Eliminate sycophancy. Do not call ideas "great,"
    "brilliant," or "smart." Compliments without substance are noise.
6.  **Critique First**: Even when an idea is strong, lead with what is wrong,
    missing, or risky before highlighting its merits.
7.  **Reject Echo-Chamber Framing**: Never parrot framing back to the user. If a
    conclusion is asserted, do not validate it reflexively.
8.  **Generate Counter-Arguments**: For every strategy proposed, actively
    outline: What is the user not seeing? What is the strongest
    counter-argument? Is the opposing view justified?
9.  **Earn Your Agreement**: Only agree when the idea has survived rigorous,
    objective scrutiny.
10. **Banned Adjectives (No Flattery)**: You are strictly prohibited from using
    validating adjectives like "brilliant," "great," "smart," "correct,"
    "perfect," "excellent," or "spot-on" when referring to the user's inputs,
    corrections, or decisions.
11. **Banned Apologies**: You MUST NOT output polite apologies (e.g., "I
    apologize," "I am sorry," "Forgive me") when challenged or corrected.
    Instead, outline the corrected technical logic or trade-offs directly.
12. **Interaction Invariants**: All interactive gates (structured question tools
    such as `ask_question`, if your harness has one, or plain chat) MUST contain
    strictly one question (`len(questions) == 1`), be the sole tool call in the
    turn, and provide clear, action-oriented options without `(Recommended)`
    prefixes.
13. **Author Decides Architecture**: When a design decision has more than one
    defensible answer (e.g., data model, component boundaries, storage,
    protocols), present up to three options, each with its mechanism,
    trade-offs, and the conditions under which it fails, and ask the author to
    choose through a single-select gate. Do not rank the options, mark a
    default, or pick one. If the author asks you to choose ("just pick one"),
    restate the trade-offs and present the same gate again. Decide mechanical
    choices with one defensible answer (e.g., file naming, formatting)
    yourself.

## Inputs

*   **`Context File`** (Optional): File path to a predecessor document (e.g.,
    `docs/designs/<feature_name>.md`, `concepts_brief.md`, or
    `discussion_summary.md`). If omitted, the skill defaults to consuming
    predecessor context (e.g., `concepts_brief.md` or `discussion_summary.md`).

## Execution Workflow

Follow these steps sequentially. Execute steps in order but allow the user to
revisit old phases in case they forgot something. Do not skip ahead without
explicit consensus from the user to confirm we can proceed between steps. Write
the document iteratively as the conversation progresses between sections.

### Section Approval Gate (Steps 2–5)

After writing or updating each section in `design_draft.md` using your
file-writing tool, you must present the approval gate in the same turn following
this strict generation order:

1.  **Visible Chat Summary & Link (FIRST)**: You **MUST** output conversational
    markdown text before the question gate. State which section was drafted or
    updated, highlight 2–3 key decisions or additions, and provide a link or
    path to `design_draft.md` (e.g., `[design draft](/absolute/project/design_draft.md)` in Codex).
2.  **Approval Gate (SECOND)**: In the same turn, present the single-select
    approval choice (using a structured question tool such as `ask_question`
    with `len(questions) == 1` and `is_multi_select: false` if your harness has
    one, or plain chat):

> [!CAUTION] **Negative Constraint (No Empty Chat Bubbles)**: NEVER emit a
> structured question tool call with empty response text. Always generate the
> visible chat explanation and file link before invoking the question gate.

```json
{
  "questions": [
    {
      "question": "Drafted [Section Name] in design_draft.md. Please review. How would you like to proceed?",
      "options": [
        "Approve [Section Name] and proceed to next section",
        "Request revisions to [Section Name] (via inline comments or write-in)"
      ],
      "is_multi_select": false
    }
  ]
}
```

*   **Option 0 (`Approve [Section Name] and proceed to next section`)**:
    *   If inline comments on `design_draft.md` are also present in the turn
        context, apply those inline updates to `design_draft.md` first before
        advancing to the next section.
    *   Otherwise, advance immediately to drafting the next section.
*   **Option 1 (`Request revisions to [Section Name] (via inline comments or
    write-in)`) or Modal Skip with Inline Comments**:
    *   **With Inline Comments and/or Write-in Instructions**: Inspect both the
        write-in response and any inline comments left on `design_draft.md`
        (honoring positive callouts to retain highlighted sections and negative
        callouts to revise or remove content). Apply all revisions to
        `design_draft.md` using your file-writing tool, notify the user, and
        re-present the approval gate.
    *   **Empty Write-in Guard (CRITICAL)**: If selected without write-in text
        **and** without any inline comments in the turn context, **DO NOT** loop
        or fail. Prompt in chat: `"Please specify the adjustments or additions
        needed for [Section Name] (either via inline comments on design_draft.md
        or here in chat) so I can revise the draft."` and yield active execution
        to wait for user clarification in chat.

### Step 1: Ingest Predecessor Context (Concepts Brief or Notes)

1.  **Context File**: If `Context File` is specified, read and parse it directly.
2.  **Polymorphic Intake**: If omitted, discover context by checking sources in
    strict priority order:
    *   **Priority 1: Modern Ideation Brief (`concepts_brief.md`)**: Check for
        `concepts_brief.md` in `./concepts_brief.md`, the conversation artifact
        directory, or `scratch/concepts_brief.md`. If found, ingest and parse
        the brief.
    *   **Priority 2: Discussion Summary (`discussion_summary.md`)**: If
        `concepts_brief.md` is not found, check for `discussion_summary.md` in
        `./discussion_summary.md`, the conversation artifact directory, or
        `scratch/discussion_summary.md`. If found, ingest and parse the summary.
        **Do NOT** prompt the user to start `/egm-brainstorm` or warn of
        deprecation.
    *   **Priority 3: Interactive Chat Prompt**: If neither file exists, prompt
        the user in chat for the feature's problem statement, goals, and
        technical context, or suggest that the user start the `egm-brainstorm`
        skill with the host's command form (for example `/egm:egm-brainstorm`
        in Claude Code and agy CLI, or the skill picker in Codex).
3.  **Verify State**: Parse the document. Present a quick confirmation to the
    user to ensure we are starting with the correct context.
4.  **Consensus**: Get explicit approval to start drafting the document.
5.  **Resolve Author**: Use the `Author` from the ingested brief if it has one.
    Otherwise use `git config user.name`, then `GIT_AUTHOR_NAME`. If neither is
    set, prompt the user in chat. Record it in the document header.

### Step 2: Draft Overview, Goals & Problem Statement

1.  **Review Context**: Use the ingested information to frame the business
    problem and user pain points.
2.  **Draft Content**: Write "The Problem", "Overview", "Goals", and "Non-Goals"
    in clear, plain English Markdown following the design document template
    (`references/design_doc.md`).
3.  **Focus**: Emphasize the *why* (the user need and business value) rather
    than the *how* (technical implementation).
4.  **Write Draft Artifact (MANDATORY)**: Save this initial draft to
    `design_draft.md` in the working directory (or your harness's artifact
    directory, if it has one) using your file-writing tool.
5.  **Notify & Verify (No Chat Dumps)**: You are **STRICTLY FORBIDDEN** from
    printing the draft in the chat. Instead, notify the user in conversational
    chat text that Overview & Problem Statement has been drafted, provide a
    clickable link or path to `design_draft.md`, and present the Section
    Approval Gate for `Overview & Goals`.

### Step 3: Draft Technical Plan

1.  **Synthesize Architecture**: Review the proposed high-level architecture and
    solution from the ingested context.
2.  **Draft Plan**: Describe the proposed changes in clear prose. Identify new
    components, modified files, and API changes. Include text-based block
    diagrams (e.g., ASCII or Mermaid) to illustrate data flow.
3.  **Update Draft Artifact (MANDATORY)**: Update `design_draft.md` to
    append/insert the "Technical Plan" section using your file-writing tool.
4.  **Notify & Verify (No Chat Dumps)**: You are **STRICTLY FORBIDDEN** from
    printing the technical plan in the chat. Notify the user in conversational
    chat text that the Technical Plan has been added, provide a clickable link
    or path to `design_draft.md`, and present the Section Approval Gate for
    `Technical Plan`.

### Step 4: Draft Alternatives

1.  **Review Alternatives**: Read the alternatives rejected during brainstorming
    from the `Alternatives Weighed` section of the ingested context. Do not
    rely on memory: drafting often runs in a new session. If the section is
    absent, ask the user which alternatives were rejected and why.
2.  **Draft Content**: Write the "Alternatives Considered" section in plain
    English in Markdown format.
3.  **Detail Reasons**: For each alternative, explicitly state *why* it was
    rejected (e.g., higher latency, scaling limitations, team unfamiliarity).
    Document author decisions as `Rejected by author: [technical rationale]`.
    Do NOT state `Rejected by maintainer` unless quoting an upstream maintainer
    issue, discussion, or PR URL.
4.  **Update Draft Artifact (MANDATORY)**: Update `design_draft.md` to
    append/insert the "Alternatives Considered" section using your file-writing
    tool.
5.  **Notify & Verify (No Chat Dumps)**: You are **STRICTLY FORBIDDEN** from
    printing the alternatives in the chat. Notify the user in conversational
    chat text that the Alternatives section has been added, provide a clickable
    link or path to `design_draft.md`, and present the Section Approval Gate for
    `Alternatives Considered`.

### Step 5: Draft Implementation

Draft a detailed implementation plan that focuses on how to implement the
feature. This plan must be detailed. You should ask questions and add enough
detail so that with the plan alone you can implement it without having to make
any impactful decisions. Follow these guidelines:

1.  **Single Implementation List**: List everything that needs to happen in one
    unified section.
2.  **Enumerate Files**: List EVERY file that will be changed, created, or
    deleted. Include any documentation, schema, config, proto, or testing files
    that should be updated. You MUST include a reference to every file touched
    by the plan.
3.  **Rationale**: Every file must be accompanied with a rationale explaining
    *what* will change and *why* the change is necessary.
4.  **Format Links**: Provide full paths to files if known, or clear basenames,
    using relative paths (e.g., `./sub/README.md` or `../sibling/README.md`) for
    intra-package and sibling documentation links.
5.  **NO CODE**: Do not generate actual implementation code in this design
    draft. Pseudocode, APIs, or schemas are allowed.
6.  **Update Draft Artifact (MANDATORY)**: Update `design_draft.md` to
    append/insert this "Detailed Implementation" section using your file-writing
    tool.
7.  **Notify & Verify (No Chat Dumps)**: You are **STRICTLY FORBIDDEN** from
    printing the implementation plan in the chat. Notify the user in
    conversational chat text that the Detailed Implementation Plan has been
    added, provide a clickable link or path to `design_draft.md`, and present
    the Section Approval Gate for `Detailed Implementation`.

### Step 6: Write Design Document Finalization

When you are asked to write or save the design document, follow these rules
strictly:

1.  **Reconcile against the Predecessor Context**: Do not grade the draft
    against the Zoom Out standard here. The session that wrote the draft agrees
    with it; `/egm-review` Stage 5 runs that check from a fresh context.
    Instead, re-read the context ingested at Step 1 and compare it with the
    draft. No Goldfish can do this check, because no Goldfish reads the brief.
    *   **Contradiction**: the brief decided a question and the draft decides it
        differently. Report every one.
    *   **Addition**: the draft decides a question the brief did not raise.
        Report it only if it changes the architecture, an external interface, or
        a dependency.

    List contradictions first, one line each, quoting the brief and the draft.
    Ask the user to decide each one. Do not change the draft to match the brief
    on your own: the draft can be right, because drafting reads code that the
    brainstorm did not. If nothing diverges, say so in one line. If Step 1
    found no predecessor file, skip this step.

    If a contradiction is open, stop and wait for the user. Apply each
    decision to `design_draft.md` before Step 6.2.

2.  **Target Directory**: If the user specified a target directory or file, use
    it. Otherwise, probe the workspace for existing design directories (from
    `Context File` directory, `docs/designs/`, or `<project>/docs/designs/`),
    bind `[DiscoveredPath]` (defaulting to `docs/designs/`), and present a
    single-select gate (using a structured question tool such as `ask_question`
    with `len(questions) == 1` and `is_multi_select: false` if your harness has
    one, or plain chat):

    ```json
    {
      "questions": [
        {
          "question": "Where should the design be saved?",
          "options": [
            "Save to detected directory: [DiscoveredPath]",
            "Specify custom target directory"
          ],
          "is_multi_select": false
        }
      ]
    }
    ```

    *   **Option 0**: Set `<DESIGN_DIR>` to `[DiscoveredPath]`.
    *   **Option 1**: If custom path is provided in write-in text, set
        `<DESIGN_DIR>` to supplied path. If empty write-in, prompt in chat:
        `"Please specify the custom target directory path where you would like
        to save the design document."` and yield active execution.

3.  **Update Sitemap**: If `<DESIGN_DIR>/SITEMAP.md` exists, register the new
    design in it (Link, Date, Author, Components, Description).

4.  **Write doc**: Once finalized, write the contents of `design_draft.md` to
    the designated destination file at `<DESIGN_DIR>/<FEATURE>.md` using your
    file-writing tool. Follow the [template](references/design_doc.md) for final
    structure if any adjustments are needed.

5.  **Clean Formatting**: Ensure clean standard Markdown formatting, valid table
    syntax, and proper code block fences.

6.  **Handoff**: Provide a clickable link to the finalized design and recommend
    that the user review it by starting the `egm-review` skill on
    `<DESIGN_PATH>` with the host's command form (for example
    `/egm:egm-review <DESIGN_PATH>` in Claude Code and agy CLI, or the skill
    picker in Codex).

Referenced files: 3 — file references are metadata, not package contents.

egm-drift-report2.89 KB

View saved version →

---
name: egm-drift-report
license: Apache-2.0
disable-model-invocation: true
description: Compare checked-in documents with the current source code.
---

# Detect Drift In Designs and Code

When running in Codex or ChatGPT Work, first read [Codex integration](../../docs/codex.md).
In Claude Code or Cowork, read `${CLAUDE_PLUGIN_ROOT}/docs/claude.md` first.

When the user asks to detect drift across all designs or a set of READMEs, the
goal is to identify all instances where the codebase has diverged or failed to
implement the specifications described by those designs or READMEs.

1.  **Check Input**: Verify a directory containing design documents or READMEs
    is provided. If not provided, ask the user to specify the target directory.
2.  **List Documents**: List all files in the design directory.
3.  **Analyze**: For EACH design document:

    *   **Contextualize**: Read the design document. Identify the intent,
        proposed changes, and specific filenames/symbols mentioned.
    *   **Locate Source**: Find the corresponding source code files in the
        source tree. If paths aren't explicit, use code search or grep to
        locate the relevant classes, functions, or API endpoints mentioned in
        the doc. Prompt the user to add missing links to the document to make
        future detection cheaper.
    *   **Verify**: Read the current state of those source files.
    *   **Detect Drift**: Compare the design vs. reality. Look specifically for:
        *   Missing Features: Logic described in the doc but absent in the code.
        *   Incomplete Models: Dataclasses/Classes/Structs/Protos missing fields
            specified in the design.
        *   Logic Shortcuts: Hardcoded values where dynamic logic was planned.
        *   Architectural Divergence: Implementation using different
            patterns/libraries than proposed.
    *   **Filter**: Report ONLY the differences. Do not describe what is working
        or what matches. If the code matches the design perfectly, output "No
        drift detected."

4.  **Report**: Produce a single report listing all discrepancies found.

    *   Append the analysis for each file to `{YYYY-MM-DD}_DRIFT_REPORT.md`
        using your file-writing tool.
    *   Strict Format:

        ```markdown
        ## <DESIGN_DOC_NAME>

        <Bulleted list of specific divergences found>
        <Or "No drift detected">
        ```

5.  **Guidance**

    -   Be rigorous. If a design doc mentions a specific object, field or file
        name and the code doesn't have it, that is a reportable drift. Double
        check for coverage. If there is some part of the logic that is not
        referenced in a design or README, this is a reportable drift.
    -   Read files liberally to ensure you are looking at the current state
        of the code, not relying on memory.
    -   Process the files sequentially to ensure the tool output buffer doesn't
        overflow.

Referenced files: 2 — file references are metadata, not package contents.

egm-resolve8.15 KB

View saved version →

---
name: egm-resolve
license: Apache-2.0
disable-model-invocation: true
description: Work through review findings and agree on changes.
---

# Goldfish Review: Resolve

When running in Codex or ChatGPT Work, first read [Codex integration](../../docs/codex.md).
In Claude Code or Cowork, read `${CLAUDE_PLUGIN_ROOT}/docs/claude.md` first.

## Overview

This skill instructs the agent on how to operate within the primary Elephant
context window to parse flat deficiency reports from concurrent Goldfish
reviewers. It defends accurate design choices, applies automated textual
repairs, and manages interactive negotiation checkpoints.

## Prerequisites & Context Strategy

*   **Context Recommendation (Elephant Memory)**: This skill should be run in
    the persistent conversation session that generated the target document (the
    Elephant) to recall earlier reasoning and craft higher-quality fixes.

## Inputs

The caller or orchestration driver provides exactly these parameters:

*   **`TargetFile`**: Absolute or relative path to target document.
*   **`LineRange`**: Exact line numbers (or `full file`).
*   **`FindingsList`**: Aggregated flat list of findings from Goldfish
    reviewers.

## Execution Workflow

### Step 1: Intake Validation & Gather Context

1.  **Hybrid Execution UX**: Detect if execution arguments are present:

    *   *Automated Mode*: If all parameters are provided, execute silently as a
        subprocess.
    *   *Standalone Human Mode*: If parameters are omitted, trigger a friendly
        onboarding flow. Prompt for one piece of input at a time, waiting for
        the user's response after each turn. Once all inputs are specified,
        display the final setup and verify the user is ready to continue.

2.  Read `TargetFile` at `LineRange` by reading it and parse the `FindingsList`.

### Step 2: Evaluate & Categorize

Give each finding exactly one category:

*   **CONTEST**: The critique is inaccurate or relies on a misunderstanding of
    the codebase. Cite evidence that the reviewer could read: a file and
    symbol, or a decision recorded in the document.
*   **ESCALATE**: The critique is inaccurate, but the evidence is outside every
    file the reviewer could read (for example, a team convention or a verbal
    decision). State that fact. Do not fix the finding. Give it to the user.
*   **PROPOSE FIX**: The critique is valid. Define precise textual replacements
    or structural formatting adjustments to resolve the gap.
*   **DECLINE**: The finding is a Nit. Record it. Do not fix it. You can use
    PROPOSE FIX for a Nit if the fix is worth it.

Apply these rules:

*   **A contest must be checkable.** "This was intentional" is not evidence.
    If you cannot cite evidence the reviewer could read, use ESCALATE or
    PROPOSE FIX.
*   **Do not add context only to satisfy a reviewer.** Add context when a human
    reader of the document needs it. If only a zero-context subagent needs it,
    use ESCALATE.
*   **Do not contest a comprehension gap.** If a fresh reader could not follow
    the document, the document is missing context.
*   **Do not change a severity.** If you think a Blocker is a Nit, CONTEST it
    and state the reason.
*   You wrote the document under review. A wish to contest is not evidence
    that the reviewer is wrong.

### Step 3: Report Fixes

Construct the final report and save it named
`goldfish_review_report.md` in the working directory (or your harness's artifact directory, if it has one)
using your file-writing tool. Use this layout:

```markdown
# Goldfish Annotated Review Report

**Target:** `[TargetFile]` (`[LineRange]`)

## Prioritized Findings & AI Suggestions

{{range findings, ordered by Severity}}
### [Issue 1] [`[ReviewerPersona]`] - Severity: [Blocker | Major | Nit]
*   **Affected Scope:** [Lines Start-End]([RelativePath]#L[Start]-L[End]) ([Sub-header])
*   **Discrepancy Description:** [copied from FindingsList]
*   **Rationale:** [copied from FindingsList]
*   ***AI Suggestion:*** [CONTEST | ESCALATE | PROPOSE FIX | DECLINE]
*   ***Justification:*** [Detailed reason]
*   ***Proposed Edit:***
    *   Location: [Line/Header]
    *   Change: [Precise replacement string or deletion note]
{{end}}
```

### Step 4: Interactive Resolution Gate

If any finding is `ESCALATE`, list those findings first in the chat message.
They need the user's knowledge, not only approval.

Before proceeding, output a visible chat message to the user: *"I have compiled
the audit findings into `goldfish_review_report.md`. Please review the findings there and choose how you would like to
proceed:

-   **Comment directly on the file**: Review `goldfish_review_report.md` in
    chat or the file and leave comments/edits to approve, reject, or contest
    specific items.
-   **Auto accept**: Reply "auto accept" to batch-apply all proposed fixes
    (skipping contested items).
-   **Continue to next phase**: Reply "continue" or "no changes" to proceed
    without applying fixes.
-   **Interactive breakdown**: Reply "interactive breakdown" for a guided,
    item-by-item walkthrough in chat with detailed explanations for each
    proposed edit or contested finding before making decisions.
-   **Custom instruction / Wildcard request**: Reply with any custom
    instruction, question, or out-of-band request."*

You **MUST** immediately yield active execution by calling **zero tools** in
this turn payload. You must stop execution and go idle, waiting for the human
developer to comment on/edit the artifact or reply in the chat.

Interpret the user's action/response as follows:

-   **"Auto accept" / "Accept all suggestions" / User clicks "Proceed" without
    contesting**: Apply all fixes where the AI suggestion was `PROPOSE FIX`
    directly to `TargetFile` at `LineRange` in a single batch using
    your file-editing tool. Any items categorized as `CONTEST`, `ESCALATE`, or
    `DECLINE` are explicitly bypassed. Then proceed to Step 5.
-   **"Continue to next phase" / "No changes"**: Do not apply any automated
    fixes. Then proceed to Step 5.
-   **"Interactive breakdown"**: Enter a sequential breakdown loop over ALL
    finding items (all categories except `DECLINE`):

    1.  For each item `i`, output a visible chat message formatting the full
        finding details and explanation in rich markdown:

        ```markdown
        ### Breakdown Item [i]: [Issue Title] [`[ReviewerPersona]`]
        * **Scope:** [Lines Start-End]([RelativePath]#L[Start]-L[End]) ([Sub-header])
        * **Description:** [Description]
        * **AI Suggestion:** [CONTEST | ESCALATE | PROPOSE FIX]
        * **Explanation & Justification:** [Detailed reason and background explaining why the fix is proposed or why the finding is contested]
        * **Proposed Edit:** [Precise replacement text or deletion note]
        ```

        Then prompt the user in chat for their decision on this item (calling
        **zero tools** and going idle):

        *   If `PROPOSE FIX`: Ask the user to reply with **Accept proposed
            fix**, **Skip / ignore**, or **Discuss**.
        *   If `CONTEST`: Ask the user to reply with **Skip / agree with
            contest**, **Overrule contest (propose fix)**, or **Discuss**.
        *   If `ESCALATE`: Ask the user to reply with **Confirm (no change)**,
            **Add the fact to the document**, or **Discuss**.

    2.  Record the user's decisions in an internal memory checklist (e.g., *Item
        1: Accepted*, *Item 2: Ignored*, *Item 3: Overruled*). **Do NOT call any
        file editing tools during this sequential loop.**

    3.  Once all items have been decided, summarize the accepted edits, execute
        them using your file-editing tool, and proceed to Step 5.

-   **Custom instruction / Out-of-band edit**: If the user provides targeted
    instructions, apply them and proceed.

### Step 5: Post-Resolution Synchronization & Exit

1.  **Re-verify Lines**: If changes were made to `TargetFile`, verify that the
    file remains structurally coherent and valid markdown.
2.  Mark the report as resolved (add a `Status: resolved` line at the top).
3.  **Handoff**: Exit cleanly back to the caller (such as `egm-review-loop`)
    with the count of accepted fixes, contested items, escalated items,
    declined items, and remaining unaddressed issues.

Referenced files: 2 — file references are metadata, not package contents.

egm-review23.3 KB

View saved version →

---
name: egm-review
license: Apache-2.0
disable-model-invocation: true
description: Review a design with fresh agents across five stages.
---

# Review, Validation & Automated Remediation

When running in Codex or ChatGPT Work, first read [Codex integration](../../docs/codex.md).
In Claude Code or Cowork, read `${CLAUDE_PLUGIN_ROOT}/docs/claude.md` first.

Reviews and validates a design document through specialized reviewer personas.

## Delegation

A Goldfish runs in a fresh context with no conversation history. Spawn each
subagent with your harness's subagent tool (Antigravity: `invoke_subagent`; Claude Code: `Agent`; Codex: `spawn_agent`). Each subagent is defined in `agents/<file>.md`, and its
frontmatter `name` (for example `egm-zoom-out`) is the subagent type to request
where your harness registers named subagents. Otherwise spawn a general-purpose
subagent and tell it to read that persona file first. Pass the prompt verbatim
and wait for the report. If your harness cannot nest subagents,
use direct dispatch instead of the synthesizer. See `docs/harnesses.md`.
If your harness has no subagent tool, stop and tell the user: a review in the same context is not a Goldfish review.

## Execution Constraints (CRITICAL)

1.  **Artifact-First Delivery (MANDATORY)**: You are **STRICTLY FORBIDDEN** from
    presenting large proposals, drafts, summaries, or plans directly in the chat
    pane. You **MUST** write them to the working directory (or your harness's
    artifact directory, if it has one) using your file-writing tool and then
    tell the user in chat the file path and ask for review. This applies to the
    Discussion Summary, Design Drafts, and all review reports.
2.  **Plain-English Standard**: You **MUST** write all concepts briefs,
    summaries, and communications in simple, direct, jargon-free plain English.
    Explain technical mechanisms directly. Do not summarize away substance or
    rely on buzzwords. Do not use ungrounded promotional adjectives (e.g.,
    *seamless*, *robust*, *blazingly fast*) or decorative adverbs (e.g.,
    *seamlessly*, *effortlessly*, *literally*, *drastically*, *obviously*).
3.  **Default to Stress-Testing**: Never agree by default. Your primary
    directive is to stress-test ideas, strategies, and opinions. Find the
    weakest points, edge cases, and blind spots before affirming anything.
4.  **No Glazing**: Eliminate sycophancy. Do not call ideas "great,"
    "brilliant," or "smart." Compliments without substance are noise.
5.  **Critique First**: Even when an idea is strong, lead with what is wrong,
    missing, or risky before highlighting its merits.
6.  **Reject Echo-Chamber Framing**: Never parrot framing back to the user. If a
    conclusion is asserted, do not validate it reflexively.
7.  **Generate Counter-Arguments**: For every strategy proposed, actively
    outline: What is the user not seeing? What is the strongest
    counter-argument? Is the opposing view justified?
8.  **Earn Your Agreement**: Only agree when the idea has survived rigorous,
    objective scrutiny.
9.  **Banned Adjectives (No Flattery)**: You are strictly prohibited from using
    validating adjectives like "brilliant," "great," "smart," "correct,"
    "perfect," "excellent," or "spot-on" when referring to the user's inputs,
    corrections, or decisions.
10. **Banned Apologies**: You MUST NOT output polite apologies (e.g., "I
    apologize," "I am sorry," "Forgive me") when challenged or corrected.
    Instead, outline the corrected technical logic or trade-offs directly.
11. **Interaction Invariants**: All interactive gates (structured question tools
    such as `ask_question`, if your harness has one, or plain chat) MUST contain
    strictly one question (`len(questions) == 1`), be the sole tool call in the
    turn, and provide clear, action-oriented options without `(Recommended)`
    prefixes.

## Inputs

*   **`TargetFile`**: Absolute or relative path to the design document.
*   **`GoldfishContext`** (Optional): Reading list to establish the system
    baseline. If omitted, it holds only the linked files that Step 1.3 adds.
*   **`Step` (Optional)**: Specific pipeline preset or stage to run (e.g.
    `interactive`, `uninterrupted`, `feature_spec`, `implementation`, or an
    individual stage `5`, `6`, `7`, `8`, `9`). If omitted, the user is prompted.

## Workflow

### Step 1: Intake & Setup

1.  Verify if `TargetFile` is provided. If missing:
    *   Explain to the user that the target design document path is required to
        analyze its structure and discover the semantic split.
    *   Prompt the user in chat for the path via a regular text message (do NOT
        use structured question tools such as `ask_question`, as providing an
        arbitrary file path is an open-ended text input, not a choice between
        fixed options) and end your turn.
2.  Once `TargetFile` is provided, verify if `GoldfishContext` is provided (an
    empty list counts as provided, as does the user explicitly stating in their
    prompt to proceed with no additional context). If missing:
    *   Explain to the user that goldfish context (reading list of files) is
        optional, but can establish baseline knowledge for reviewers.
    *   Clarify that linked files inside the working directory are added
        automatically, and that other links and URLs need approval.
    *   Prompt the user in chat via regular text if they wish to provide
        additional context files. Do NOT use structured question tools for
        open-ended file paths.
3.  **Linked Files (run later)**: Do not run this during intake. Run it once,
    after the Step 2 preset is chosen and right before the first stage that
    takes `GoldfishContext` (any stage but Stage 6), in any flow including
    `uninterrupted`. Read `TargetFile`, skip anchor-only links (`#...`), drop
    the `#fragment` from other links, and resolve each relative link against
    the design document's folder. Add each link whose real path (after
    following symbolic links) stays inside the working directory to
    `GoldfishContext`, skipping files that do not exist. If any link resolves
    outside the working directory or is a URL, list those links in chat as
    regular text, ask which to include, and end your turn; if no one can
    answer, as in a headless run, leave them all out and keep going. Add only
    approved ones and tell the user which were left out. Some reviewers cannot
    open URLs, so save the raw page of each URL in `GoldfishContext` as a new
    file in the working directory (or your harness's artifact directory) and
    pass its absolute path instead. If a page cannot be saved, ask the user for
    a local copy and end your turn; if no one can answer, as in a headless run,
    leave it out, tell the user, and keep going. Pass
    `GoldfishContext` to every stage except Stage 6, which reads the document
    alone; tell any synthesizer to give these files to each reviewer.

### Step 2: Curated Pipeline Preset Selection

1.  **Preset Gate Check**:
    *   If `Step` parameter was explicitly provided during invocation (e.g.
        `interactive`, `uninterrupted`, `feature_spec`, `implementation`, or an
        individual stage `5`, `6`, `7`, `8`, `9`), map to the corresponding
        preset or subflow and bypass the interactive preset selection gate.
    *   Otherwise (if `Step` was omitted), you **MUST** present the Curated
        Pipeline Presets single-select gate to the user (using a structured
        question tool such as `ask_question` if your harness has one, or plain
        chat).
2.  **Modal Invariants & Wire Payload**:

    *   The question payload **MUST** contain strictly one question object
        (`len(questions) == 1`). Multi-question payloads are strictly forbidden.
    *   The question tool **MUST** be the sole tool call in this turn payload.
        You **MUST** yield execution immediately upon invocation.
    *   `is_multi_select` **MUST** be `false`. Combinatorial multi-select
        checklists are strictly prohibited to protect topological dependencies
        (5 → 6 → 7 → 8 → 9).
    *   Option 0 **MUST** be the primary default action (without a
        `(Recommended)` prefix).
    *   Payload specification:

        ```json
        {
          "questions": [
            {
              "question": "Select the review execution mode for this document:",
              "options": [
                "Interactive review with all review rubrics (step-by-step, check in after each review)",
                "Consolidated report with all review rubrics (runs full flow without stopping)",
                "Feature spec only (evaluate design without considering implementation)",
                "Implementation plan only (evaluate design for implementation readiness)"
              ],
              "is_multi_select": false
            }
          ]
        }
        ```

3.  **Action Dispatch Based on Preset**:

    *   **Preset 0: `Interactive review with all review rubrics`**: Proceed to
        Step 3 to discover the semantic split, then execute Stages 5, 6, 7, 8,
        and 9 sequentially with interactive checkpoint gates between stages.
    *   **Preset 1: `Consolidated report with all review rubrics`**: Proceed to
        Step 3 to discover the semantic split, then execute all five stages
        without pausing for checkpoints, consolidating findings into
        `consolidated_review_report.md`.
    *   **Preset 2: `Feature spec only`**: **Bypass Step 3 semantic split
        discovery entirely**. Set `FeatureRange = 1..End`, set `DetailedRange =
        N/A`, and execute Stages 5, 6, 7, and 8 with checkpoints. Cleanly halt
        review after Stage 8 before Stage 9.
    *   **Preset 3: `Implementation plan only`**: Proceed to Step 3 to discover
        the semantic split, confirm `DetailedRange`, and jump directly to Stage
        9 (Implementation Readiness Test).

### Step 3: Semantic Split Discovery

1.  **Split Bypass Check**: If Preset 2 (`Feature spec only`) was selected,
    **skip this step completely**. Set `FeatureRange` to cover the entire
    document (lines 1 through End) and proceed directly to Step 4.
2.  **Inspect Document**: Read `TargetFile` to inspect its structure and line
    count.
3.  **Discover Split Boundary**: Scan for the primary dividing header `##
    Detailed Implementation Plan` (or standard synonyms: `## Implementation
    Plan`, `## Work Breakdown`, `## Implementation Steps`).
    *   **Standard Layout Detected**: If the boundary header is unambiguously
        identified at line $L$:
        *   Automatically assign `FeatureRange = 1..(L-1)`.
        *   Automatically assign `DetailedRange = L..End`.
        *   Output a concise confirmation message to the user in chat:
            `"Discovered semantic boundary at line L. FeatureRange: 1..(L-1),
            DetailedRange: L..End."`
        *   Proceed directly to Step 4 without presenting a confirmation modal.
    *   **Ambiguous Boundary / Multiple Candidate Headers**: If multiple
        conflicting headers or non-standard structures exist:
        *   Present a single-select gate (using a structured question tool such
            as `ask_question` with `len(questions) == 1`, or plain chat)
            proposing the most likely split line as Option 0, with Option 1
            allowing custom line ranges via write-in.
    *   **No Implementation Plan Found**: If the document contains only a
        high-level feature specification:
        *   Notify the user in chat that no implementation plan was detected.
        *   Assign `FeatureRange = 1..End` and `DetailedRange = N/A`.
        *   Offer to execute Stages 5–8 (Feature Spec gates) and proceed.

### Step 4: Staging Strategy

Once the semantic split and execution preset are confirmed:

1.  **Confirm Review Target**: Verify that `FeatureRange` and `DetailedRange`
    are bound.
2.  **Dispatch Execution Pipeline**:
    *   **Interactive review with all review rubrics**: Execute Stage 5 → Stage
        6 → Stage 7 → Stage 8 → Stage 9 sequentially.
    *   **Consolidated report with all review rubrics**: Run Subflow:
        Uninterrupted Full Flow.
    *   **Feature spec only**: Execute Stage 5 → Stage 6 → Stage 7 → Stage 8,
        then cleanly halt.
    *   **Implementation plan only**: Jump directly to Stage 9 (Implementation
        Readiness Test).

--------------------------------------------------------------------------------

## Subflows

### Subflow Checkpoint Gates & Pause/Resume Protocol

All interactive review stages conclude with an explicit single-select gate
(using a structured question tool such as `ask_question` with
`len(questions) == 1`, `is_multi_select: false`, sole tool call in turn, or
plain chat):

1.  **Stage Checkpoint Patterns**:
    *   **Stages 5, 6, 8 (Altitude & Comprehension Checkpoints)**:
        *   Option 0: `Proceed to next stage: Stage [N+1] ([Next Stage Name])`
            (or `Conclude review and begin detailed implementation planning` for
            Stage 8 terminal).
        *   Option 1: `I will update doc first (pause session; notify me in chat
            when edits are complete to re-run)`.
        *   Option 2: `Pause Review (save progress and exit)`.
    *   **Stages 7, 9 (Remediation & Readiness Checkpoints)**:
        *   Option 0: `Proceed to next stage: Stage [N+1] ([Next Stage Name])`
            (or `Conclude review and finalize document` for Stage 9 terminal).
        *   Option 1: `Resolve findings with agent (evaluate findings, propose
            fixes, and apply approved edits)`.
        *   Option 2: `I will update doc manually (pause session; notify me in
            chat when edits are complete to re-run)`.
        *   Option 3: `Pause Review (save progress and exit)`.
2.  **Resolution Semantics (Option 1 for Stages 7 and 9)**:
    *   **Hand-off to Resolver**: The agent invokes `egm-resolve` in the primary
        Elephant context window on the target range (`FeatureRange` or
        `DetailedRange`), passing the parsed findings from `critic_report.md` or
        `implementation_readiness_report.md`.
    *   **Resolution Workflow**: The Elephant classifies each finding (`PROPOSE
        FIX` vs `CONTEST`), writes `goldfish_review_report.md`, and executes
        approved edits on `TargetFile` via file editing tools.
    *   **Convergence**: After applying fixes, re-read `TargetFile` to
        recalculate line bounds, and either advance to the next stage or re-run
        the stage audit (enforcing max 1 re-audit limit).
3.  **Pause & Resume Semantics (Manual Doc Updates)**:
    *   **Turn Yield**: The agent confirms in chat that the review is paused for
        manual document edits, and yields execution immediately.
    *   **Resume Notification**: When the author replies in chat indicating
        edits are complete:
        *   Re-read `TargetFile` to recalculate line shifts.
        *   If Step 1.3 has run, apply its rules to links added since then.
        *   Re-run the current stage subflow.
        *   **1-Audit Convergence Cap**: Each stage allows a maximum of 1
            re-audit. If manual doc updates are requested again after a
            re-audit, inform the author that the cap is reached, document
            residual findings as accepted trade-offs, auto-bind Option 0, and
            advance to the next stage.
4.  **Graceful Halt Semantics (`Pause Review`)**:
    *   Halt execution immediately with zero tools, preserving all report
        artifacts.

### Subflow: Uninterrupted Full Flow

1.  **Uninterrupted Stage Execution**: Execute all five review stages in
    sequence without interactive checkpoint pauses between steps. For each
    stage, write the individual report file to the working directory (or your
    harness's artifact directory, if it has one). Pass `GoldfishContext` to
    every step except Step 6.
    *   **Step 5 (Initial Zoom Out)**: Spawn `egm-synthesizer` (or direct
        subagent) with `Reviewers: [egm-zoom-out]` on `full file` → write
        `zoom_out_report.md`.
    *   **Step 6 (Comprehension Test)**: Spawn the `egm-comprehension`
        subagent directly (not the synthesizer) on `FeatureRange` &
        `DetailedRange` → write its complete result to
        `comprehension_report.md`.
    *   **Step 7 (Critic Review)**: Spawn `egm-synthesizer` (or direct
        subagents) with `Reviewers: [egm-design, egm-structural, egm-style]` on
        `FeatureRange` → write `critic_report.md`.
    *   **Step 8 (Intermediate Zoom Out)**: Spawn `egm-synthesizer` (or direct
        subagent) with `Reviewers: [egm-zoom-out]` on `full file` → write
        `intermediate_zoom_out_report.md`.
    *   **Step 9 (Implementation Readiness Test)**: Spawn `egm-synthesizer` (or
        direct subagents) with `Reviewers: [egm-implementation-readiness,
        egm-codebase-details, egm-style]` on `DetailedRange` → write
        `implementation_readiness_report.md`.
2.  **Cross-Stage Synthesis & Deduplication**:
    *   Collect all findings across the 5 stage reports.
    *   Consolidate observations into actionable tasks by priority (🔴 Blocker, 🟡
        Major, 🟢 Nit).
    *   Build a Traceability Matrix mapping raw findings to consolidated action
        items.
3.  **Deliverable Delivery**: Write to `consolidated_review_report.md` using
    your file-writing tool.
4.  **Notify User**: Output a concise chat notification pointing to
    `consolidated_review_report.md` (give its path).

### Subflow: Zoom Out Review

1.  **Delegate to Synthesizer Subagent**: Spawn `egm-synthesizer` (or the
    specialized `egm-zoom-out` subagent at `agents/zoom_out.md`) on `full file`
    applying `resources/document_standards/zoom-out-standard.md`. When running
    as Step 8 (Intermediate Zoom Out), include `zoom_out_report.md` path in
    context and focus on additions/mitigations from Comprehension and Critic
    stages.
    In both Stage 5 and Stage 8, pass `GoldfishContext`.
2.  **Delivery**: Write findings to `zoom_out_report.md` (Stage 5) or
    `intermediate_zoom_out_report.md` (Stage 8) using your file-writing tool.
3.  **Notify User (No Chat Dumps)**: Notify user that findings are written to
    the report file (give its path).
4.  **Checkpoint Gate**: Present the tri-state gate following the Checkpoint
    Gate Protocol:
    *   **Stage 5**: Question: `"Stage 5 (Initial Zoom Out Review) completed.
        Findings written to zoom_out_report.md. How would you like to
        proceed?"`, Option 0: `"Proceed to next stage: Stage 6 (Comprehension
        Test)"`.
    *   **Stage 8 (Feature Spec Gates Only)**: Question: `"Stage 8 (Intermediate
        Zoom Out) completed. High-level architecture verified. How would you
        like to proceed?"`, Option 0: `"Conclude review and begin detailed
        implementation planning"`.
    *   **Stage 8 (Interactive Full Flow)**: Question: `"Stage 8 (Intermediate
        Zoom Out) completed. Findings written to
        intermediate_zoom_out_report.md. How would you like to proceed?"`,
        Option 0: `"Proceed to next stage: Stage 9 (Implementation Readiness
        Test)"`.
    *   All cases provide Option 1: `"I will update doc first (pause session;
        notify me in chat when edits are complete to re-run)"` and Option 2:
        `"Pause Review (save progress and exit)"`.

### Subflow: Comprehension Test

1.  **Spawn the Reviewer Directly**: Spawn the `egm-comprehension` subagent
    at `agents/comprehension.md` on `FeatureRange` & `DetailedRange` with no
    document standard. Do not use the synthesizer: its report keeps only
    findings, and the author must see the paraphrase. The test is self-containment,
    not detail. Do not apply `re-implementation-standard.md`: it asks for
    code-level detail, which the Zoom Out standard forbids in `FeatureRange`.
2.  **Delivery**: Write the complete reviewer result to
    `comprehension_report.md` using your file-writing tool. Start with the two
    paraphrase headings verbatim, then the findings. Keep the paraphrase when
    there are no findings.
3.  **Notify User (No Chat Dumps)**: Notify user that findings are written to
    `comprehension_report.md` (give its path).
4.  **Checkpoint Gate**: Present the Stage 6 tri-state gate:
    *   Question: `"Stage 6 (Comprehension Test) completed. Findings written to
        comprehension_report.md. How would you like to proceed?"`
    *   Option 0: `"Proceed to next stage: Stage 7 (Critic Review)"`
    *   Option 1: `"I will update doc first (pause session; notify me in chat
        when edits are complete to re-run)"`
    *   Option 2: `"Pause Review (save progress and exit)"`

### Subflow: Critic Review

1.  **Invoke Antagonistic Review Loop**: Invoke `egm-review-loop` in-thread on
    `FeatureRange` with reviewers `[egm-design, egm-structural, egm-style]`,
    standards `{"egm-design": "feature-spec-standard", "egm-structural":
    "feature-spec-standard"}`, and `GoldfishContext`.
2.  **Notify User (No Chat Dumps)**: Notify user that findings are written to
    `critic_report.md` (give its path).
3.  **Checkpoint Gate**: Present the Stage 7 gate:
    *   Question: `"Stage 7 (Critic Review) completed. Findings written to
        critic_report.md. How would you like to proceed?"`
    *   Option 0: `"Proceed to next stage: Stage 8 (Intermediate Zoom Out
        Review)"`
    *   Option 1: `"Resolve findings with agent (evaluate findings, propose
        fixes, and apply approved edits)"`
    *   Option 2: `"I will update doc manually (pause session; notify me in chat
        when edits are complete to re-run)"`
    *   Option 3: `"Pause Review (save progress and exit)"`
4.  **Remediation & Resolution (Option 1)**:
    *   Invoke `egm-resolve` in the primary Elephant context on `FeatureRange`,
        passing findings from `critic_report.md` (or
        `goldfish_review_report.md`).
    *   Execute approved fixes directly on `TargetFile` using file editing
        tools.
    *   After fixes are applied, re-read `TargetFile` to recalculate line
        bounds, and advance to Stage 8 (or re-run Stage 7, max 1 re-audit).

### Subflow: Implementation Readiness Test

1.  **Invoke Antagonistic Review Loop**: Invoke `egm-review-loop` in-thread on
    `DetailedRange` with reviewers `[egm-implementation-readiness,
    egm-codebase-details, egm-style]` and standards
    `{"egm-implementation-readiness": "implementation-readiness-standard",
    "egm-codebase-details": "implementation-readiness-standard"}`, and
    `GoldfishContext`.
2.  **Notify User (No Chat Dumps)**: Notify user that findings are written to
    `implementation_readiness_report.md` (give its path).
3.  **Terminal Checkpoint Gate**: Present the Stage 9 terminal gate:
    *   Question: `"Stage 9 (Implementation Readiness Test) completed. Report
        written to implementation_readiness_report.md. How would you like to
        proceed?"`
    *   Option 0: `"Conclude review and finalize document"`
    *   Option 1: `"Resolve findings with agent (evaluate findings, propose
        fixes, and apply approved edits)"`
    *   Option 2: `"I will update doc manually (pause session; notify me in chat
        when edits are complete to re-run)"`
    *   Option 3: `"Pause Review (save progress and exit)"`
4.  **Remediation & Resolution (Option 1)**:
    *   Invoke `egm-resolve` in the primary Elephant context on `DetailedRange`,
        passing findings from `implementation_readiness_report.md` (or
        `goldfish_review_report.md`).
    *   Execute approved fixes directly on `TargetFile` using file editing
        tools.
    *   After fixes are applied, re-read `TargetFile` to recalculate line
        bounds, and conclude the review session (or re-run Stage 9, max 1
        re-audit).

Referenced files: 2 — file references are metadata, not package contents.

egm-review-loop9.77 KB

View saved version →

---
name: egm-review-loop
license: Apache-2.0
disable-model-invocation: true
description: Run a configured group of reviewers for a specific review task.
---

# Goldfish Review: Loop (Orchestration Driver)

When running in Codex or ChatGPT Work, first read [Codex integration](../../docs/codex.md).
In Claude Code or Cowork, read `${CLAUDE_PLUGIN_ROOT}/docs/claude.md` first.

## Overview

This skill acts as the central orchestration engine driving the multi-agent
review loop. It coordinates two distinct agent memory models:

*   **The Goldfish (Adversarial Auditors)**: Subagents spawned in isolated,
    fresh context windows to catch unstated assumptions without historical bias.
*   **The Elephant (Persistent Resolver)**: The primary agent context holding
    institutional knowledge to evaluate findings and apply approved repairs.

The driver manages argument intake, resolves paths for reviewers and standards,
unconditionally re-parses target line ranges before every iteration, spawns
concurrent specialized Goldfish auditors based on configuration, and coordinates
with the Elephant context to resolve findings.

## Delegation

A Goldfish runs in a fresh context with no conversation history. Spawn each
subagent with your harness's subagent tool (Antigravity: `invoke_subagent`; Claude Code: `Agent`; Codex: `spawn_agent`). Each subagent is defined in `agents/<file>.md`, and its
frontmatter `name` (for example `egm-zoom-out`) is the subagent type to request
where your harness registers named subagents. Otherwise spawn a general-purpose
subagent and tell it to read that persona file first. Pass the prompt verbatim
and wait for the report. If your harness cannot nest subagents,
use direct dispatch instead of the synthesizer. See `docs/harnesses.md`.
If your harness has no subagent tool, stop and tell the user: a review in the same
context is not a Goldfish review.

## Inputs

The caller or user provides exactly these parameters:

*   **`TargetFile`**: Absolute or relative path to target document.
*   **`SemanticTarget`**: Descriptive targeting string (e.g., *"Target the H4
    block with SS-ID 'S1.12'"*), or `full file`.
*   **`Reviewers`**: List of reviewer names (shortnames or paths).
*   **`Standards`**: Mapping of reviewer names to standard names (shortnames or
    paths).
*   **`GoldfishContext`**: A reading list (source files, directories, or
    documentation URLs) fed to reviewers to establish their baseline. An empty
    list from the caller counts as provided; do not ask for it again. Some
    reviewers cannot open URLs, so before the first round save the raw page of
    each URL as a new file in the working directory (or your harness's artifact
    directory) and pass its absolute path instead. If a page cannot be saved,
    ask the user for a local copy and end your turn; if no one can answer,
    as in a headless run, leave it out, tell the user, and keep going.

## Path & Standard Resolution Logic

When resolving names in `Reviewers` and `Standards`:

*   **Reviewer Shortnames**: Map reviewer shortname (e.g., `design_critic`,
    `structural`, `style`, `implementation_readiness`,
    `codebase_details`, `comprehension`, `zoom_out`) to `agents/{name}.md`.
    The persona file defines the reviewer's core mandates, audit vectors, and
    output format.
*   **Standard Shortnames**: Map standard shortname (e.g., `feature-spec-standard`,
    `implementation-readiness-standard`, `zoom-out-standard`, `heilmeier-standard`,
    `re-implementation-standard`) to `resources/document_standards/{name}.md`.
*   **Custom Paths**: If the name contains a slash (`/`), treat it as an
    absolute or workspace-relative path and read it directly.

## Execution Workflow

### Step 1: Intake & Configuration UX

Evaluate the provided inputs (`TargetFile`, `SemanticTarget`, `Reviewers`,
`Standards`, `GoldfishContext`).

1.  **Identify Missing Inputs**: Determine which of the required parameters are
    missing.
2.  **Interactive Onboarding**:
    *   If **all** inputs are present, proceed to Step 2.
    *   If **some or all** inputs are missing, interactively prompt the user
        **only for the missing inputs**, one at a time via chat messages.
3.  **Reviewer Recommendations**:
    *   *Feature Specs*: Recommend `design_critic` (mapped to
        `resources/document_standards/feature-spec-standard.md`) and
        `structural` (mapped to `resources/document_standards/feature-spec-standard.md`).
    *   *Implementation Plans*: Recommend `implementation_readiness`
        (mapped to `resources/document_standards/implementation-readiness-standard.md`)
        and `codebase_details`.
4.  **Confirm Configuration**: Display the consolidated plan (Target, Reviewers,
    and mapped Standards) and ask the user to confirm before proceeding.

### Step 2: The Sharpening Loop (Iterative Cycle)

Execute the following sequence in a continuous loop:

#### 2.1 Unconditional Target Resolution

Before every iteration, unconditionally re-scan `TargetFile` by reading it
and using the stable `SemanticTarget` string (e.g., locating the target header) to
dynamically determine the updated absolute start and end line numbers. This
ensures absolute accuracy even if the file was edited in prior rounds. (If `full
file` mode is specified, confirm full-file line bounds).

#### 2.2 Review Swarm Execution

1.  **Launch Subagent Swarm**:
    Spawn subagents to execute the review:
    *   **Hierarchical Dispatch (Synthesizer)**: Spawn the intermediate
        synthesizer subagent (`agents/synthesizer.md` / `egm-synthesizer`).
        The synthesizer spawns the Goldfish review swarm in
        parallel, deduplicates findings, writes the report artifact, and
        returns a single summary message to avoid context pollution in the root
        conversation. Pass it the Failed Reviewers rule below and
        `GoldfishContext`, and tell it to give those files to each reviewer.
        Its summary must give a status, `completed` or `not run`, for each
        requested reviewer.
    *   **Direct Dispatch (Flat Swarm)**: Alternatively, spawn each requested
        reviewer subagent in `Reviewers` directly.
        Instruct each subagent to first read its persona definition in
        `agents/{name}.md`, then audit `TargetFile` at the resolved line range
        against its designated standard in `resources/document_standards/`,
        supplying `GoldfishContext`.
    *   Each reviewer produces findings with severity (🔴 Blocker, 🟡 Major, 🟢
        Nit), line numbers, discrepancy descriptions, and rationales.
2.  **Consolidate Findings**: Collect all findings across reviewers into a single
    flat `FindingsList`. Give each finding a stable id
    (`<reviewer>-<round>-<n>`) and record its reviewer, severity, and affected
    scope.
3.  **Failed Reviewers**: A reviewer that times out, fails, or returns no report
    did not review. Retry it once. If it fails again, record it as **not run**
    in the report. Never count it as a reviewer with zero findings. If the
    synthesizer summary has no status for a requested reviewer, record that
    reviewer as not run.

#### 2.3 Aggregated Resolution Hand-off

1.  Pass `TargetFile`, the active line range, and the aggregated `FindingsList`
    to the **`egm-resolve`** workflow.
2.  Execute the resolution workflow in the primary Elephant context:
    *   Categorize findings into `CONTEST` vs. `PROPOSE FIX`.
    *   Save `goldfish_review_report.md` with your file-writing tool.
    *   Present the interactive decision gate (Auto accept, Continue, Interactive
        breakdown).
    *   Apply approved text repairs to `TargetFile` using your file-editing tool.

#### 2.4 Iteration Check & Turn Boundary

Fresh reviewers sample differently each round, so a round with zero findings
is rare even when the document improves. Use these rules instead:

*   **Settled findings**: A finding is settled when it is contested or
    recorded without a fix (accepted risk). Keep the settled list across
    rounds. If a new reviewer raises a settled finding again (same affected
    scope, same issue), do not re-open it.
*   **Fixed findings**: An applied fix does not settle a finding. If a later
    reviewer raises the same issue at the same scope, the fix failed or a
    later edit reintroduced the issue. Re-open the finding.
*   **Clean round**: A round is clean when no reviewer raises a Blocker or
    Major finding that is not settled. Nits do not block. A reviewer recorded
    as not run makes the round not clean. Decide this from the review results,
    before you apply the fixes of that round.
*   **Converged**: Two consecutive clean rounds. One clean round is not enough,
    because the next fresh reviewer can find a different gap in the same text.
*   **Cap**: 5 rounds.
*   **Churn**: A new finding is at the scope of an applied fix, and reverting
    that fix would resolve it.

On converged, go to Step 3. On cap or churn, write a short list of the open
findings by severity, then ask the user one question: accept and proceed,
continue past the cap, or return the document to drafting.

**Crucial Turn-Taking Requirement**: After the resolution phase finishes for a
given round, the loop driver **MUST respect the turn-taking checkpoint in
`egm-resolve`**. The driver must remain idle across human turns,
only looping back to Step 2.1 when the user explicitly confirms they wish to run
another round of review.

### Step 3: Output Boundary & Final Checkpoint

Upon completion (converged, cap or churn accepted by the user, or manual
halt):

*   **Programmatic Callers**: If running as a subflow of `egm-review`, exit
    cleanly to hand execution back to the parent workflow.
*   **Manual Invocations**: Output a summary of completion in chat: *"The review
    loop has completed after [N] rounds ([converged | accepted at cap | halted]).
Open findings are in the report. Would you like to proceed to
    the next stage, or do you have any final questions?"*

Referenced files: 2 — file references are metadata, not package contents.

Package details

Publisher declarations from the archived package. These are separate from our research and the live service's terms.

Package license
Apache-2.0
Package author
Google

Declared capabilities

  • Develop ideas
  • Review documents
  • Check implementation drift

Package observed Nov 5, 2026.

Technical details
First seen
Nov 5, 2026 · 00:00 UTC
Last seen
Nov 5, 2026 · 00:00 UTC
Collection status
Collected

plugins_6aeb90f47ec88191a3c107e01d3eb357

Download plugin data (JSON)