Optional SimpleClaude utilities: a review-and-refactor skill that routes to named techniques, adversarial analysis, context wizards, and clean-room design

version
8.2.1
GitHub stars
116

Install

/plugin install sc-extras@simpleclaude

Run it inside Claude Code after adding the marketplace with /plugin marketplace add kylesnowschwartz/SimpleClaude.

Contents

Discovered from source

Skills 3

Clean-Room Design

A structured approach to reimplementing a software artifact without copying its internals. A discovery agent examines the original and writes a behavioral specification with fixtures. Then a separate implementation agent builds from that specification alone. Fixtures captured during discovery verify the reimplementation in Phase 4.

Compaq used this technique in 1982 to clone the IBM PC BIOS — one team documented what the BIOS did, a second team (who had never seen IBM's code) wrote compatible firmware from those docs. Copyright protects expression, not ideas. A functional spec describes ideas.

EXECUTION MODEL

Phases 0 through 6 run in sequence. The core phases (1-4) MUST NOT be skipped or reordered.

  • Phase 0 establishes scope and pins the artifact version
  • Phase 1 (Discovery) examines the original via a Task() agent, produces observations and fixtures
  • Phase 2 (Specify) distills observations into a clean functional spec
  • Phase 3 (Implement) builds from the spec in a fresh Task() agent that has never seen the original
  • Phase 4 (Verify) confirms equivalence via spec compliance and fixture replay
  • Phases 5-6 present results and offer next steps

After each phase, present the output to the user and wait for approval before proceeding.

Isolation

Discovery and Implementation run in separate Task() agents with no shared context. The implementation agent receives only the specification file path. The original artifact, discovery notes, and fixtures never enter the implementation agent's prompt.

This provides process-level isolation, not OS-level sandboxing. For stronger isolation (IP-sensitive work), run Phase 3 in an entirely separate Claude session — the artifacts this skill produces support that handoff cleanly.

Phase 0: Resolve Target and Scope

Parse $ARGUMENTS. The first argument is the target, anything after is a scope or focus hint.

Target resolution

ArgumentTargetVersion pin
Repository URLClone or fetch the repoRecord commit SHA
Local pathExamine directlyRecord git commit SHA; if not a git repo, record a checksum
Package nameLocate via registry (npm, PyPI, RubyGems, crates.io, etc.)Record exact package version
Protocol or API nameFetch public docs and specsRecord document revision or access date

Version pinning is mandatory. Record an immutable identifier so all artifacts reference the same version.

Scope negotiation

Use AskUserQuestion:

  • Which parts to reimplement (the whole thing, a subset, a single module)
  • Target language and runtime (same as original, or different)
  • Quality attributes that matter (performance parity, API compatibility, simplified interface)
  • What's explicitly out of scope

Tell the user: "Target: [what]. Scope: [boundaries]. Language: [target stack]."

Run directory

Slug: <artifact-name>-<version-prefix> (lowercase, hyphens). Create with mkdir -p .agent-history/clean-room/<slug>.

Run git check-ignore -q .agent-history/ — if it fails, warn the user to add the ignore rule.

If the directory already exists, ask: start fresh, resume, or abort.

Classify the artifact

TypeDiscovery focus
Library/PackageExported functions, types, behavior contracts
CLI ToolCommand interface, input/output formats, exit codes
API/ServiceRoutes, request/response schemas, error codes
ProtocolMessage types, sequencing, state transitions
Data FormatSyntax, semantics, edge cases, error recovery
AlgorithmInputs, outputs, invariants, complexity characteristics

Phase 1: Discovery (The Dirty Room)

Examine the original to document what it does (not how) and capture behavioral fixtures for verification.

BLOCKING: Complete discovery before moving to Phase 2.

Launch as a Task() agent. This agent reads the original freely. Its output goes to disk — the orchestrator reads those files afterward but does NOT pass the agent's context into later phases.

Task(
  description: "Clean-room discovery: examine original artifact",
  prompt: """
  ## Role: Discovery Agent (Dirty Room)

  Examine the original artifact and produce two deliverables:
  1. A behavioral discovery document
  2. A behavioral fixtures file

  Target: [resolved target from Phase 0]
  Scope: [scope from Phase 0]
  Source version: [pinned version from Phase 0]

  ## What to document
  - Public interface: function signatures, types, config options, error types
  - Behavioral contracts: input/output mappings, side effects, edge cases
  - Integration surface: dependencies, consumers, environment expectations
  - Non-functional characteristics: performance envelope, concurrency model

  ## What NOT to document (clean-room rule)
  - Internal data structures and their layout
  - Private helper functions and their signatures
  - Optimization techniques and implementation tricks
  - Comments, variable names, or code organization from the original

  ## Behavioral fixtures
  Capture black-box input/output recordings. Coverage requirements:
  - At least one fixture per public interface element
  - At least one per documented error condition
  - Edge-case fixtures for behaviors with boundary conditions
  - For stateful artifacts: fixtures covering key state transitions
  Scale with the artifact.

  Fixture capture can be passive (from docs/tests) or active (executing the target).
  Before active capture, use AskUserQuestion to confirm the user is comfortable
  running the target code.

  Each fixture records: input, expected output, how to replay it, and category.
  Default to behavioral matching (semantic equivalence). Use exact matching only
  for machine-stable contracts (wire protocols, status codes, serialization formats)
  and note the justification.

  Redact credentials, tokens, or PII from all fixtures.

  Write discovery to: .agent-history/clean-room/<slug>/discovery.md
  Write fixtures to: .agent-history/clean-room/<slug>/fixtures.md
  Both files MUST include the source version in their header.
  """
)

Discovery output

Write to .agent-history/clean-room/<slug>/discovery.md:

# Discovery: [Artifact Name]

**Source version**: [pinned identifier]

## Public Interface
[Documented API surface]

## Behavioral Contracts
[Input/output mappings, edge cases, error conditions]

## Integration Surface
[Dependencies, consumers, environment expectations]

## Non-Functional Characteristics
[Performance, concurrency, durability observations]

## Open Questions
[Behaviors that were ambiguous or couldn't be determined externally]

Write to .agent-history/clean-room/<slug>/fixtures.md:

# Behavioral Fixtures: [Artifact Name]

**Source version**: [pinned identifier]

## Fixtures

### FIX-001: [behavior name]
**Replay**: [how to invoke: command, function call, HTTP request, etc.]
**Input**: [exact input — redact sensitive data]
**Output**: [expected output — behavioral description or exact if justified]
**Match level**: behavioral | exact
**Category**: happy-path | edge-case | error

Present both files to the user. Ask: "Does this capture the behavior you want to reimplement? Are the fixtures sufficient?"

Phase 2: Specify (The Wall)

Transform discovery observations into a functional specification with no reference to the original's internals. This is the only artifact the implementation agent receives.

BLOCKING: Do NOT start until the user approves Phase 1 output.

Specification rules

  1. Describe behavior, not mechanism. "Returns the sorted elements" not "Uses quicksort with median-of-three pivot."
  2. Define contracts precisely. Input types, output types, preconditions, postconditions.
  3. Enumerate edge cases. Empty inputs, maximum sizes, malformed data.
  4. Specify error behavior. What errors occur, what information they carry.
  5. Leave implementation choices open. The spec says WHAT, the implementer decides HOW.

Write to .agent-history/clean-room/<slug>/specification.md:

# Functional Specification: [Artifact Name]

**Source version**: [pinned identifier]

## Overview
[What this artifact does and why someone uses it]

## Interface
[Complete API surface with types, signatures, return values]

## Behavior
### [name]
- **Preconditions**: [what must be true before calling]
- **Postconditions**: [what is true after calling]
- **Edge cases**: [boundary conditions and expected behavior]
- **Errors**: [failure modes and error information]

## State and Side Effects
[For stateful artifacts: state transitions, ordering, atomicity. Omit for stateless.]

## Configuration
[Configurable options, types, defaults, effects]

## Compatibility Requirements
[What "compatible" means if drop-in replacement is needed]

## Out of Scope
[What the original does that this reimplementation will NOT do]

Completeness gate

Before Phase 3, verify:

  • Every fixture-captured behavior has a corresponding spec requirement
  • Every Open Question from discovery is resolved, marked out of scope, or translated into a spec decision
  • For stateful artifacts: state transitions and side effects are in the spec

Do NOT hand off a spec with unresolved ambiguities — the implementation agent cannot consult the original to fill gaps.

Present the specification and ask:

  • "Does this spec accurately describe the behavior you want?"
  • "Does anything here reference HOW the original works rather than WHAT it does?"

The user's approval is the formal handoff.

Phase 3: Implement (The Clean Room)

BLOCKING: Do NOT start until the user approves the specification.

Gather implementation preferences via AskUserQuestion:

  • Full interface or vertical slice?
  • Preferred architecture or patterns
  • Test strategy (TDD from spec, tests after, both)
  • Libraries or frameworks to use (or avoid)

Launch a new Task() agent for implementation. This agent receives ONLY the spec file path and implementation preferences. It has never seen the original artifact.

Task(
  description: "Clean-room implementation from spec",
  prompt: """
  ## Role: Implementation Agent (Clean Room)

  Build a reimplementation from the specification alone.

  Specification: .agent-history/clean-room/<slug>/specification.md
  Output directory: [target path]
  Implementation preferences: [from user]

  ## Rules
  - The specification is your ONLY source of truth
  - If the spec is ambiguous, ask the user to clarify — do NOT search for an existing implementation
  - Write tests derived from the spec's contracts and edge cases

  ## Build sequence
  1. Read the specification
  2. Scaffold project structure, dependencies, build tooling
  3. Define types from the spec's interface section
  4. Implement behavior, edge cases, and error handling
  5. Write tests derived from spec contracts

  After each major section, report what's implemented, what's remaining.
  """
)

Wait for completion. Present a summary to the user.

Phase 4: Verify (Functional Equivalence)

Confirm the reimplementation satisfies both the specification and the behavioral fixtures. The orchestrator runs verification, not the implementation agent. Fixtures never enter the implementation agent's context.

If fixture replay reveals failures, the fix path is: revise the spec to capture the missing behavior, then re-run Phase 3 with the updated spec. Do NOT leak fixtures or discovery notes into the implementation agent to fix failures — that breaks the wall.

BLOCKING: Do NOT start until implementation is complete.

Layer 1: Spec compliance

RequirementStatusEvidence
[From spec]PASS / FAIL / PARTIAL[Test result or explanation]

Layer 2: Fixture replay

Replay every fixture from fixtures.md against the reimplementation using the documented replay method.

  • Behavioral fixtures: Compare semantic equivalence. Correct type, status, error class, structural shape. Different wording or formatting is fine.
  • Exact fixtures: Compare literally.
FixtureMatch LevelExpectedActualStatus
FIX-001behavioral[expected][actual]PASS / FAIL / DRIFT

DRIFT means semantically equivalent but differently expressed. Document each case. DRIFT requires user approval.

The workflow MUST NOT proceed to Phase 5 with any FAIL fixtures unresolved.

Write to .agent-history/clean-room/<slug>/verification.md:

# Verification: [Artifact Name]

**Source version**: [pinned identifier]

## Summary
- Spec requirements: N passing, N failing, N partial
- Fixture replays: N passing, N failing, N drift

## Spec Compliance
[Requirement checklist table]

## Fixture Replay Results
[Replay table]

## Drift Decisions
[For each DRIFT: what differed, acceptable or not]

## Gaps
[Behaviors that couldn't be verified and why]

Phase 5: Present Results

# Clean-Room Design: [Artifact Name]

**Target**: [original artifact]
**Scope**: [what was reimplemented]
**Language**: [implementation language/runtime]

## Process
- **Discovery** documented N interface elements, M behavioral contracts, K fixtures
- **Specification** covered N requirements
- **Implementation** produced [file count] files, [test count] tests
- **Verification** passed N/M spec requirements, K/K fixtures replayed

## Artifacts
- Discovery: `.agent-history/clean-room/<slug>/discovery.md`
- Fixtures: `.agent-history/clean-room/<slug>/fixtures.md`
- Specification: `.agent-history/clean-room/<slug>/specification.md`
- Verification: `.agent-history/clean-room/<slug>/verification.md`
- Implementation: [path to reimplemented code]

## Known Gaps
[Unimplemented or unverified requirements]

Phase 6: User Choice

Use AskUserQuestion:

OptionDescription
ExtendAdd more spec requirements, capture more fixtures, and implement
HardenFocus on edge cases, error handling, and test coverage
ShipDone. Package and finalize

Clean-room design trades speed for independence. The wall between specification and implementation is the whole point. A good spec produces a good implementation. Gaps in the spec surface in Phase 4 instead of in production.

${ARGUMENTS}

Dirty-Room Design

This is a bastardization of the technique used by Compaq 1982 to clone the IBM PC BIOS.

A structured approach to porting a software artifact to a different language or platform while consulting its internals. A reading agent examines the original and produces discovery, fixtures, and a translation brief — notes on which algorithms, data structures, and idioms are worth carrying across the language boundary. The implementation agent receives all three artifacts and explicit permission to read the original source directly.

The clean-room skill builds a wall between specification and implementation to preserve copyright independence; the dirty-room takes notes through the open window because the constraints here are technical, not legal. Use this when the goal is a faithful port rather than an independent reimplementation.

EXECUTION MODEL

Phases 0 through 6 run in sequence. The core phases (1-4) MUST NOT be skipped or reordered.

  • Phase 0 establishes scope, target language, and pins the artifact version
  • Phase 1 (Read) examines the original via a Task() agent and produces discovery, fixtures, and a translation brief
  • Phase 2 (Refine) finalises the spec and translation brief for handoff
  • Phase 3 (Port) builds in a Task() agent that may consult the original directly
  • Phase 4 (Verify) confirms equivalence via spec compliance and fixture replay
  • Phases 5-6 present results and offer next steps

After each phase, present the output to the user and wait for approval before proceeding.

No isolation, by design

The implementation agent in Phase 3 receives the original artifact's path and may read it freely. The reading agent's notes flow through to the porter. This is the explicit difference from /sc-clean-room — the wall is gone because the work is a translation, not a clean reimplementation. Process-level separation between agents is preserved only for token efficiency; it is no longer load-bearing for independence.

Phase 0: Resolve Target, Scope, and Languages

Parse $ARGUMENTS. The first argument is the target, anything after is a scope, focus, or target-language hint.

Target resolution

ArgumentTargetVersion pin
Repository URLClone or fetch the repoRecord commit SHA
Local pathExamine directlyRecord git commit SHA; if not a git repo, record a checksum
Package nameLocate via registry (npm, PyPI, RubyGems, crates.io, etc.)Record exact package version
Protocol or API nameFetch public docs and specsRecord document revision or access date

Version pinning is mandatory. Record an immutable identifier so all artifacts reference the same version.

Scope and language negotiation

Use AskUserQuestion:

  • Source language and runtime
  • Target language and runtime (this is the defining input; if same as source, ask whether a direct implementation is a better fit)
  • Which parts to port (the whole thing, a subset, a single module)
  • Quality attributes that matter (performance parity, API compatibility, idiomatic target-language code)
  • What is explicitly out of scope
  • Licence check: confirm the user has rights to study the original and produce a port. If unclear, redirect to /sc-clean-room.

Tell the user: "Target: [what]. Scope: [boundaries]. Languages: [source] → [target]."

Run directory

Slug: <artifact-name>-<source-lang>-to-<target-lang> (lowercase, hyphens). Create with mkdir -p .agent-history/dirty-room/<slug>.

Run git check-ignore -q .agent-history/ — if it fails, warn the user to add the ignore rule.

If the directory already exists, ask: start fresh, resume, or abort.

Classify the artifact

TypeReading focus
Library/PackageExported functions, types, behaviour contracts, internal algorithms
CLI ToolCommand interface, input/output formats, exit codes, argument parsing strategy
API/ServiceRoutes, request/response schemas, error codes, middleware ordering
ProtocolMessage types, sequencing, state transitions, framing
Data FormatSyntax, semantics, edge cases, error recovery, parser strategy
AlgorithmInputs, outputs, invariants, complexity, optimisations worth preserving

Run State

Before leaving Phase 0, fix the following named variables.

Substitution contract. Two grammars appear in this skill and must not be confused:

  • Tokens of the form <UPPER_SNAKE> are Run State variables. The orchestrator MUST replace them with the resolved value before sending any prompt to a Task() agent. Every Phase 1 and Phase 3 prompt body performs this literal substitution before invocation.
  • Tokens of the form [brief description] inside example artifact templates (the discovery.md, fixtures.md, specification.md, and verification.md blocks) are human-readable scaffolds the spawned agent fills with its findings — do NOT replace these.
VariableDefinitionDerivation rule
ARTIFACT_NAMEShort canonical name of the original artifactLowercase, hyphens; strip versions, namespaces, and registry decorations. For repo URLs, use the repo's basename; for packages, the registry name without scope (@org/foo → foo); for protocols, the common abbreviation (e.g. http2, grpc).
SOURCE_LANG / TARGET_LANGCanonical language tokensLowercase, hyphens. Use the canonical short names: go, rust, python, typescript, javascript, ruby, java, kotlin, swift, c, cpp, csharp, elixir, erlang, scala, clojure, haskell, ocaml. Pick the closest match for variants (ts → typescript, py → python).
SLUGRun identifier<ARTIFACT_NAME>-<SOURCE_LANG>-to-<TARGET_LANG>
RUN_DIRRun directory (absolute path)<repo-root>/.agent-history/dirty-room/<SLUG>/
SOURCE_PATHAbsolute path to the materialised originalSet by Phase 0 Materialisation, below.
TARGET_PATHAbsolute path where the port will be writtenConfirm with the user; default to <repo-root>/<ARTIFACT_NAME>-<TARGET_LANG>/ if unspecified.
SOURCE_VERSIONImmutable version pin of the materialised sourceRead after Materialisation; this is the version_pin field recorded by the Materialisation recipe in <RUN_DIR>provenance.json.
SCOPENegotiated scope of the portCaptured during Phase 0 scope negotiation. A short prose summary of which parts are in scope and out of scope.
IMPL_PREFSPorter's preferred architecture, test strategy, librariesCaptured at the start of Phase 3, immediately before the porting Task() is launched, via AskUserQuestion.
APPROVAL_SIGNALWhat counts as user approval at each blocking gateAn explicit affirmative from the user — "yes", "approved", "proceed", "lgtm", "go ahead", or equivalent. Silence, partial approval ("looks mostly good but…"), or any qualified response does NOT count; re-ask explicitly until you receive an unambiguous affirmative or an explicit halt.

Echo the Run State back to the user as a compact block before Phase 1 so they can confirm:

SLUG=<resolved>
RUN_DIR=<resolved>
ARTIFACT_NAME=<resolved>
SOURCE_LANG=<resolved>
TARGET_LANG=<resolved>
SOURCE_PATH=<resolved>
TARGET_PATH=<resolved>
SOURCE_VERSION=<resolved>
SCOPE=<resolved>

(IMPL_PREFS is filled in at Phase 3.)

Phase 0 Materialisation

After resolving Run State, the orchestrator MUST materialise the source on disk and record its version pin to <RUN_DIR>provenance.json before proceeding to Phase 1. Run exactly one row from the table below — the row whose target type matches what the user supplied.

provenance.json shape (uniform across all rows):

{
  "target_type": "repo_url | local_path | package | protocol",
  "identifier": "<the original argument as supplied>",
  "version_pin": "<commit SHA, package version, or doc revision/access date>",
  "captured_at": "<ISO-8601 UTC timestamp>",
  "source_path": "<absolute path>"
}
Target typeMaterialisation recipe
Repository URLgit clone <url> <RUN_DIR>source/<ARTIFACT_NAME> then capture git -C <RUN_DIR>source/<ARTIFACT_NAME> rev-parse HEAD as version_pin. source_path = <RUN_DIR>source/<ARTIFACT_NAME>.
Local pathNo copy. source_path = absolute path of <SOURCE_INPUT>. If git -C <SOURCE_INPUT> rev-parse HEAD succeeds, use its output as version_pin. Otherwise compute find <SOURCE_INPUT> -type f -exec sha256sum {} \; | sha256sum and use that digest as version_pin.
Package nameResolve and unpack into <RUN_DIR>source/<ARTIFACT_NAME>/ per ecosystem, then record the resolved version as version_pin:
• npm: npm pack <pkg>@<ver> then tar -xzf <pkg>-<ver>.tgz -C <RUN_DIR>source/<ARTIFACT_NAME> --strip-components=1
• PyPI: pip download --no-deps --no-binary=:all: -d <RUN_DIR>source/ <pkg>==<ver> then unpack the sdist into <RUN_DIR>source/<ARTIFACT_NAME>/
• RubyGems: gem fetch <pkg> -v <ver> then gem unpack <pkg>-<ver>.gem --target=<RUN_DIR>source/
• crates.io: cargo download <pkg>==<ver> -x -o <RUN_DIR>source/<ARTIFACT_NAME>/ (or fetch the .crate and tar -xzf it)
Protocol / APIcurl -fsSL <spec-url> -o <RUN_DIR>source/<ARTIFACT_NAME>/<filename> (repeat per document). version_pin = the document's published revision if stated in the spec, otherwise the ISO-8601 fetch date. source_path = <RUN_DIR>source/<ARTIFACT_NAME>.

Update SOURCE_PATH and SOURCE_VERSION in Run State from <RUN_DIR>provenance.json (the source_path and version_pin fields, respectively). From Phase 1 onward, all agent prompts derive <SOURCE_PATH> and <SOURCE_VERSION> from <RUN_DIR>provenance.json.

Phase 1: Read the Source

Examine the original to document what it does, how it does the parts worth preserving, and capture behavioural fixtures for verification.

BLOCKING: Complete the reading before moving to Phase 2.

Launch as a Task() agent. This agent reads the original freely. Its output goes to disk; the orchestrator reads those files afterward. Unlike clean-room, there is no contamination concern — the implementation agent will see the same source material itself.

Per the substitution contract above, replace every <UPPER_SNAKE> token in the prompt body with its Run State value before invoking. Leave the [bracket] scaffolds inside the example artifact templates untouched — those are for the spawned agent to fill.

Task(
  description: "Dirty-room reading: examine original artifact for port",
  prompt: """
  ## Role: Reading Agent

  Examine the original artifact and produce three deliverables:
  1. A discovery document (behaviour and noteworthy internals)
  2. A behavioural fixtures file
  3. A translation brief (how to carry this across the language boundary)

  Target: <ARTIFACT_NAME>
  Scope: <SCOPE>
  Provenance: <RUN_DIR>provenance.json is authoritative for SOURCE_PATH and SOURCE_VERSION; read it before starting.
  Source version: <SOURCE_VERSION>
  Source language: <SOURCE_LANG>
  Target language: <TARGET_LANG>
  Source path: <SOURCE_PATH>
  Run directory: <RUN_DIR>

  ## What to capture in discovery.md
  - Public interface: function signatures, types, config options, error types
  - Behavioural contracts: input/output mappings, side effects, edge cases
  - Integration surface: dependencies, consumers, environment expectations
  - Non-functional characteristics: performance envelope, concurrency model
  - **Internal techniques worth noting**: algorithms, data structures,
    optimisation tricks, ordering of operations, invariants the code relies on

  Unlike a clean-room reading, you are encouraged to record HOW the original
  works where the technique is worth preserving. Annotate each internal note
  with: "preserve" (carry across), "adapt" (idea is sound but the form must
  change), or "discard" (idiomatic to the source language only).

  ## Behavioural fixtures (fixtures.md)
  Capture black-box input/output recordings. Coverage requirements:
  - At least one fixture per public interface element
  - At least one per documented error condition
  - Edge-case fixtures for behaviours with boundary conditions
  - For stateful artifacts: fixtures covering key state transitions
  Scale with the artifact.

  Fixture capture can be passive (from docs/tests) or active (executing the target).
  Before active capture, use AskUserQuestion to confirm the user is comfortable
  running the target code.

  Each fixture records: input, expected output, how to replay it, and category.
  Default to behavioural matching (semantic equivalence). Use exact matching only
  for machine-stable contracts (wire protocols, status codes, serialisation formats)
  and note the justification.

  Redact credentials, tokens, or PII from all fixtures.

  ## Translation brief (translation-brief.md)
  This is the dirty-room-specific deliverable. For each notable internal:
  - **Source pattern**: the technique as expressed in <SOURCE_LANG>
  - **Target pattern**: the equivalent in <TARGET_LANG> — idiomatic, not literal
  - **Mapping notes**: gotchas, semantic differences, performance implications

  Cover at minimum:
  - Concurrency model translation (e.g. Promise → goroutine, callback → channel)
  - Error handling translation (e.g. exceptions → Result types, panics → errors)
  - Type system translation (e.g. structural → nominal, generics differences)
  - Memory and lifetime model (e.g. GC → ownership, refcount → arena)
  - Standard-library substitutions for any std lib calls in the source
  - Idiom mismatches: places where the source is idiomatic in <SOURCE_LANG> but
    would be unidiomatic in <TARGET_LANG>, with proposed local equivalents

  Write to:
  - <RUN_DIR>discovery.md
  - <RUN_DIR>fixtures.md
  - <RUN_DIR>translation-brief.md

  All three files MUST include the source version in their header.
  """
)

Reading output

Write to <RUN_DIR>discovery.md:

# Discovery: [Artifact Name]

**Source version**: [pinned identifier]
**Source language**: [language]
**Target language**: [language]

## Public Interface
[Documented API surface]

## Behavioural Contracts
[Input/output mappings, edge cases, error conditions]

## Integration Surface
[Dependencies, consumers, environment expectations]

## Non-Functional Characteristics
[Performance, concurrency, durability observations]

## Internals Worth Noting
### [technique name]
- **Disposition**: preserve | adapt | discard
- **What it does**: [behavioural description]
- **How it does it**: [implementation sketch — concise, just enough for the porter]
- **Why it matters**: [the reason this is worth carrying or adapting]

## Open Questions
[Behaviours that were ambiguous or couldn't be determined]

Write to <RUN_DIR>fixtures.md:

# Behavioural Fixtures: [Artifact Name]

**Source version**: [pinned identifier]

## Fixtures

### FIX-001: [behaviour name]
**Replay**: [how to invoke: command, function call, HTTP request, etc.]
**Input**: [exact input — redact sensitive data]
**Output**: [expected output — behavioural description or exact if justified]
**Match level**: behavioural | exact
**Category**: happy-path | edge-case | error

Write to <RUN_DIR>translation-brief.md:

# Translation Brief: [Artifact Name]

**Source version**: [pinned identifier]
**Source language**: [language]
**Target language**: [language]

## Cross-Language Model Mappings

### Concurrency
- **Source pattern**: [e.g. async/await on Promise]
- **Target pattern**: [e.g. goroutine + channel]
- **Mapping notes**: [gotchas, ordering differences]

### Error Handling
[same shape]

### Types
[same shape]

### Memory and Lifetimes
[same shape]

### Standard Library Substitutions
| Source call | Target equivalent | Notes |
|-------------|-------------------|-------|

## Per-Technique Translation
### [technique name from discovery]
- **Source pattern**: [the technique in source language]
- **Target pattern**: [the idiomatic equivalent in target language]
- **Trade-offs**: [what changes; what is gained or lost]

## Idiom Mismatches
[Places where the source idiom does not survive translation; proposed alternatives]

Present all three files to the user. Ask: "Does this capture the behaviour you want and the techniques worth preserving? Are the fixtures sufficient?"

Phase 2: Refine Spec and Translation Brief

Distil the discovery into a functional specification (the WHAT) and finalise the translation brief (the HOW guidance). Both go to the implementation agent.

BLOCKING: Do NOT start until the user approves Phase 1 output (per APPROVAL_SIGNAL).

Specification rules

The spec describes behaviour, not mechanism — exactly as in clean-room. Keeping the spec clean means a future operator could promote this to a /sc-clean-room run if licence concerns surface. The translation brief is where mechanism lives.

  1. Describe behaviour, not mechanism. "Returns the sorted elements" not "Uses quicksort with median-of-three pivot."
  2. Define contracts precisely. Input types, output types, preconditions, postconditions.
  3. Enumerate edge cases. Empty inputs, maximum sizes, malformed data.
  4. Specify error behaviour. What errors occur, what information they carry.
  5. Leave implementation choices to the porter and the brief. The spec says WHAT; the brief and the source say HOW.

Write to <RUN_DIR>specification.md:

# Functional Specification: [Artifact Name]

**Source version**: [pinned identifier]

## Overview
[What this artifact does and why someone uses it]

## Interface
[Complete API surface with types, signatures, return values, expressed in target-language types]

## Behaviour
### [name]
- **Preconditions**: [what must be true before calling]
- **Postconditions**: [what is true after calling]
- **Edge cases**: [boundary conditions and expected behaviour]
- **Errors**: [failure modes and error information]

## State and Side Effects
[For stateful artifacts: state transitions, ordering, atomicity. Omit for stateless.]

## Configuration
[Configurable options, types, defaults, effects]

## Compatibility Requirements
[What "compatible" means: drop-in replacement, behaviourally equivalent, or
idiomatic re-expression. State the level explicitly.]

## Out of Scope
[What the original does that this port will NOT do]

Completeness gate (lighter than clean-room)

Before Phase 3, verify:

  • Every fixture-captured behaviour has a corresponding spec requirement
  • Every Open Question from discovery is resolved, marked out of scope, or noted as "porter may consult source to resolve"
  • For stateful artifacts: state transitions and side effects are in the spec
  • The translation brief covers every "preserve" or "adapt" item from discovery

Spec gaps are recoverable here in a way they are not in clean-room — the porter can consult the source. Aim for clarity, but do not block the handoff over irreducible ambiguity.

Present the spec and brief together. Ask:

  • "Does the spec accurately describe the behaviour you want?"
  • "Does the translation brief reflect how you want techniques carried across?"
  • "Anything in the brief that should be reclassified as out-of-scope or as discard?"

The user's approval (per APPROVAL_SIGNAL) is the formal handoff.

Phase 3: Port

BLOCKING: Do NOT start until the user approves Phase 2 output (per APPROVAL_SIGNAL).

Gather implementation preferences via AskUserQuestion. The user's answers populate <IMPL_PREFS> in Run State for use in the porting Task() prompt below:

  • Full interface or vertical slice?
  • Preferred architecture or patterns in the target language
  • Test strategy (TDD from spec, tests after, both)
  • Libraries or frameworks to use (or avoid)
  • How aggressively to follow the source's structure (literal port → idiomatic re-expression)

Launch a Task() agent for implementation. This agent receives the spec, the brief, the path to the original source, and implementation preferences.

Per the substitution contract, replace every <UPPER_SNAKE> token in the prompt body with its resolved Run State value before invoking.

Task(
  description: "Dirty-room port: implement from spec, brief, and source",
  prompt: """
  ## Role: Porting Agent

  Build a port of <ARTIFACT_NAME> from <SOURCE_LANG> to <TARGET_LANG>.

  Specification: <RUN_DIR>specification.md
  Translation brief: <RUN_DIR>translation-brief.md
  Original source: <SOURCE_PATH>
  Source version: <SOURCE_VERSION>
  Output directory: <TARGET_PATH>
  Implementation preferences: <IMPL_PREFS>

  ## Authority hierarchy
  1. The specification is authoritative for behaviour. The port must satisfy it.
  2. The translation brief is the recommended HOW. Follow it unless target-language
     idiom strongly argues otherwise; record any deviation in your final summary.
  3. The original source is available for tie-breaking, clarifying ambiguity,
     and observing techniques marked "preserve" or "adapt" in the brief.

  ## Rules
  - Prefer idiomatic <TARGET_LANG> over a literal transcription.
  - Items marked "discard" in discovery MUST NOT cross over.
  - Items marked "preserve" should retain their behaviour and, where the brief
    says so, their structural shape.
  - Items marked "adapt" require judgment: keep the idea, change the form.
  - Write tests derived from the spec's contracts and edge cases.
  - If the spec is silent on a behaviour, you may consult the source to determine
    intended behaviour, then either update the spec (preferred) or document the
    decision in your final summary.

  ## Build sequence
  1. Read the specification and translation brief in full
  2. Skim the original source for architectural orientation
  3. Scaffold project structure, dependencies, build tooling in <TARGET_LANG>
  4. Define types from the spec's interface section, in <TARGET_LANG> idiom
  5. Implement behaviour, edge cases, error handling — consulting source where
     marked "preserve" or "adapt"
  6. Write tests derived from spec contracts

  After each major section, report what's implemented, what's remaining, and
  any deviations from the brief with rationale.
  """
)

Wait for completion. Present a summary to the user, including any deviations from the translation brief and their rationale.

Phase 4: Verify

Confirm the port satisfies the specification and the behavioural fixtures. The orchestrator runs verification.

BLOCKING: Do NOT start until implementation is complete.

Layer 1: Spec compliance

RequirementStatusEvidence
[From spec]PASS / FAIL / PARTIAL[Test result or explanation]

Layer 2: Fixture replay

Replay every fixture from fixtures.md against the port using the documented replay method.

  • Behavioural fixtures: Compare semantic equivalence. Correct type, status, error class, structural shape. Different wording or formatting is fine.
  • Exact fixtures: Compare literally.
FixtureMatch LevelExpectedActualStatus
FIX-001behavioural[expected][actual]PASS / FAIL / DRIFT

DRIFT means semantically equivalent but differently expressed. For a port, drift is often correct — the target language renders the same concept differently. Document each case. DRIFT requires user approval.

Layer 3 (advisory): Idiomaticity

A short subjective pass. Does the port read as native [target language] code, or does it betray its origin in [source language]? Note any places where the port still reads as a transcription rather than a translation. This layer does not block; it informs Phase 6.

The workflow MUST NOT proceed to Phase 5 with any FAIL fixtures unresolved.

If fixture replay reveals failures, the fix path is: revise the spec or brief to capture the missing behaviour, then re-run Phase 3. The porter may also re-read the source to diagnose. Unlike clean-room, this is fully permitted.

Write to <RUN_DIR>verification.md:

# Verification: [Artifact Name]

**Source version**: [pinned identifier]

## Summary
- Spec requirements: N passing, N failing, N partial
- Fixture replays: N passing, N failing, N drift
- Idiomaticity: [brief subjective note]

## Spec Compliance
[Requirement checklist table]

## Fixture Replay Results
[Replay table]

## Drift Decisions
[For each DRIFT: what differed, acceptable or not, why]

## Brief Deviations
[Where the porter departed from the translation brief and why]

## Gaps
[Behaviours that couldn't be verified and why]

Phase 5: Present Results

# Dirty-Room Port: [Artifact Name]

**Target**: [original artifact]
**Languages**: [source] → [target]
**Scope**: [what was ported]

## Process
- **Reading** documented N interface elements, M behavioural contracts, K fixtures, P translation brief sections
- **Specification** covered N requirements
- **Port** produced [file count] files, [test count] tests
- **Verification** passed N/M spec requirements, K/K fixtures replayed

## Artifacts
- Discovery: `<RUN_DIR>discovery.md`
- Fixtures: `<RUN_DIR>fixtures.md`
- Specification: `<RUN_DIR>specification.md`
- Translation brief: `<RUN_DIR>translation-brief.md`
- Verification: `<RUN_DIR>verification.md`
- Port: `<TARGET_PATH>`

## Known Gaps
[Unimplemented or unverified requirements]

## Notable Brief Deviations
[Where the porter chose target-language idiom over the brief's recommendation]

Phase 6: User Choice

Use AskUserQuestion:

OptionDescription
ExtendPort more of the original; capture more fixtures and translation brief sections
IdiomatiseRevisit places where the port still reads as transcription, not translation
HardenFocus on edge cases, error handling, and test coverage
ShipDone. Package and finalise

Dirty-room design trades independence for fidelity. The wall would have prevented borrowing what the original got right; the absence of the wall obliges the porter to distinguish those things from idioms that do not survive the crossing. A literal transcription is no more a translation than a phonetic transliteration is a poem.

${ARGUMENTS}

Review and Refactor

This skill picks one technique for a review or refactoring task and sends you to its reference file. A general bug review of a diff goes to the built-in /code-review. This skill covers the work that /code-review does not: safe refactoring, test quality, focused passes, verification, and root causes.

Skill directory: ${CLAUDE_SKILL_DIR}. Paths below are relative to it.

Rules for every review

  • Verify each finding with an outside signal before you report it: a test, a run, a grep of every call site, or a fresh-context agent that tries to disprove it. Asking the same agent to re-check its own work is not verification.
  • Give each finding a concrete failure scenario: the input, the code path, and the wrong outcome. A finding without one is a question, not a finding.
  • Rank findings by severity. Put blocking findings first. Put optional findings in a separate short list, or omit them.
  • Review without the author's reasoning. Give a reviewer the diff and the criteria only. Treat the PR description, commit messages, and "done" reports as claims to check, not as facts.
  • When you review a change (a diff, PR, or branch), report only what the change introduced. Skip pre-existing problems. The sweep routes (dead code, duplicated code, names in existing code) report existing problems by design. In every review, skip anything a linter or formatter catches.
  • Prefer running to reading. Report the command and its output next to the finding.
  • State what you did not verify: perspectives not run, files skipped, checks that could not run.

Routing

SituationRoute
General review of a diff, PR, or branchBuilt-in /code-review. Pass the level first, then the target: /code-review high <branch>
Clean up code just changedBuilt-in /simplify
Security review of the branchBuilt-in /security-review
Refactor without changing behaviorreferences/refactor-safely.md
Refactor code that has no testsreferences/characterization-tests.md
Review test quality, especially tests an agent wrotereferences/mutation-test-review.md
Deep review, one concern per passreferences/focused-passes.md
Check whether a finding, a review, or a "done" claim is realreferences/refute-findings.md
Change over ~300 lines or ~10 filesreferences/chunk-large-changes.md
Did the change do everything the task askedreferences/requirements-trace.md
Duplicated code, or "does this bug exist elsewhere"references/divergent-clones.md
What can be deletedreferences/dead-code.md
Review namesreferences/naming-review.md
Why does this failreferences/hypothesis-rca.md
Check that a PR body, README, or doc is truereferences/verify-claims.md
Fetch and resolve human PR review threadsreferences/pr-review-threads.md

How to use a route

  1. Match the request to one row. When two rows match, run the prerequisite first: use a combination below when one applies, and report each route separately.
  2. Read only the reference for that row. Each reference is complete on its own.
  3. Follow its numbered steps in order. Apply the rules above to every finding.
  4. Stop where the reference says to stop, and report in the shape it names.

Combinations that come up often:

  • A large PR that needs a deep review: chunk it first, then run focused passes on each chunk.
  • A refactor of untested code: write characterization tests, then follow the safe refactoring steps.
  • Findings from any source (another agent, a human, a tool): run them through refute-findings.md before you act on them.

Scripts

get-pr-comments.sh prints a PR's reviews, comments, and review threads as JSON. It needs gh and jq. format-pr-tree.rb reads that JSON on stdin and prints it as a text tree. [PR] is empty (the current branch's PR), a number, a PR URL, or owner/repo 123. --all must come first; it adds resolved threads.

Show the threads as a tree:

"${CLAUDE_SKILL_DIR}/scripts/get-pr-comments.sh" [--all] [PR] | ruby "${CLAUDE_SKILL_DIR}/scripts/format-pr-tree.rb"

Get the threads as JSON:

"${CLAUDE_SKILL_DIR}/scripts/get-pr-comments.sh" [--all] [PR]

references/pr-review-threads.md describes how to use both commands.

Commands 3

Adversarial Hunt

Three agents with competing economic incentives analyze any target. A maximizer finds all possible issues, a skeptic filters false positives through asymmetric penalties, and an arbiter produces the final ground-truth ruling. Domain-agnostic — works on code, plans, documentation, configs, reasoning, or any artifact.

EXECUTION MODEL: STRICTLY SEQUENTIAL

Phases 2, 3, and 4 MUST run in strict sequence. NEVER launch them in parallel.

Each phase depends on the previous phase's output:

  • Phase 2 (Maximizer) runs first, produces findings
  • Phase 3 (Skeptic) REQUIRES the Maximizer's findings as input — cannot start until Phase 2 completes
  • Phase 4 (Arbiter) REQUIRES both Maximizer AND Skeptic reports as input — cannot start until Phase 3 completes

After each Task() call, you MUST wait for the task to complete and read its output before proceeding to the next phase. Use TaskOutput with block: true to wait. Display the phase summary to the user. Only then move to the next phase.

Phase 0: Resolve Target and Classify

Parse $ARGUMENTS. The first argument is the target, anything after is a focus hint.

Target resolution

ArgumentTarget
(empty) or stagedUncommitted changes — run git diff HEAD
branchCurrent branch vs main — run git diff main...HEAD
pr <number>PR diff — run gh pr diff <number>
File or directory pathThat specific path

For diff-based targets, save the diff to /tmp/adversarial-hunt-diff.txt and verify non-empty. This file is referenced by agents.

Deep read

Before classifying or generating lenses, YOU (the orchestrator) must actually read the target thoroughly:

  • For diffs: read the diff AND the changed source files. Understand what the code does, not just what changed.
  • For files/directories: read the files, check imports, trace key call paths with Grep.
  • For plans/docs: read the full document and any referenced files.

This deep read is what makes the lenses specific rather than generic. Skip it and the whole process degrades.

Classification

DomainSignals
CodeSource files, diffs, test files
Plan/DesignPLAN.md, ARCHITECTURE.md, ADRs, implementation plans
DocumentationREADME, API docs, guides, comments
ConfigurationYAML, JSON configs, CI/CD pipelines, infrastructure
ReasoningAnalysis documents, investigations, decision records, trade-off evaluations
CommunicationEmails, PR descriptions, RFCs, proposals, announcements

Tell the user: "Target: [what]. Domain: [classified]. Focus: [hint or inferred]."

Phase 1: Generate Lenses

Before launching any agents, generate three domain-specific artifacts from your Phase 0 deep read:

1. Analysis Lenses (for the Maximizer)

Generate 5-8 concrete lenses appropriate to the domain and target. Each lens is a specific angle of attack that references actual elements you found in the target.

Examples of what good lenses look like (do NOT copy these — generate fresh lenses from the actual target):

  • Code: "Null propagation paths where X returns nil but Y assumes non-nil"
  • Plan: "Dependencies between steps 3 and 7 that aren't acknowledged"
  • Config: "Environment variables referenced but never defined"
  • Docs: "API examples that contradict the parameter descriptions"

"Check error handling" is too vague. "Error handling gap in the retry loop at auth.rb:45 where TimeoutError isn't caught" is a lens.

2. Severity Scale (for scoring)

Define what +1, +5, and +10 mean for THIS domain and target:

+1  (low):    [domain-specific definition]
+5  (medium): [domain-specific definition]
+10 (critical): [domain-specific definition]

3. Disproof Categories (for the Skeptic)

Generate 4-6 categories for valid disproofs, specific to the domain:

- [CATEGORY]: [what it means for this domain]

Show all three artifacts to the user before proceeding. This lets them steer if the lenses are off-target.

Phase 2: Maximizer (Superset)

BLOCKING: Launch the Maximizer agent. Wait for it to complete. Read its full output. Display the summary. Only then proceed to Phase 3.

The Maximizer has full read access to the codebase — point it at the files, don't paste content into the prompt.

For diff-based targets, tell the Maximizer where the diff file is AND which source files changed, so it can read both.

Task(
  subagent_type: "Explore",
  description: "Find all issues in target",
  prompt: """
  ## Role: Maximizer

  You are competing for the highest score. You are rewarded by impact:
  - +1 point: [GENERATED low definition]
  - +5 points: [GENERATED medium definition]
  - +10 points: [GENERATED critical definition]

  Maximize your score. If something MIGHT be an issue, report it.
  Your adversary will try to disprove your findings. Let them try.

  ## Target

  [For diffs]: The diff is at /tmp/adversarial-hunt-diff.txt. The changed files are: [list paths]. Read both the diff and the source files for full context. Also read tests for the changed code if they exist.
  [For files]: Analyze these files: [list paths]. Read them and any closely related files (tests, callers, config).

  ## Analysis Lenses

  Examine the target through each of these lenses:
  [GENERATED lenses, numbered]

  You are not limited to these lenses. If you find issues outside them, report those too.

  ## Output Format

  ### FINDING-001: [Short title]
  **Impact**: critical (+10) | medium (+5) | low (+1)
  **Location**: [file:line, section reference, or specific element]
  **Description**: [What's wrong]
  **Trigger**: [Scenario or condition that causes the issue]
  **Evidence**: [Concrete proof — quote the artifact, cite specifics]
  **Consequence**: [What happens if this isn't addressed]

  End with:

  ## Score Summary
  - Critical (10 pts each): N = X pts
  - Medium (5 pts each): N = X pts
  - Low (1 pt each): N = X pts
  - **TOTAL SCORE: X points**
  """
)

Display summary: "Phase 2 complete: Maximizer reported N findings (X critical, Y medium, Z low). Claimed score: [score]."

Store the Maximizer's full output — you will paste it into the Skeptic's prompt next.

Phase 3: Skeptic (Disproof Filter)

BLOCKING: This phase REQUIRES the Maximizer's completed output. Do NOT start until Phase 2 is done and you have read the full Maximizer report.

Launch the Skeptic agent. Paste the complete Maximizer report into the Skeptic's prompt (see ## Maximizer Report section in the prompt template). The Skeptic also has independent file access to verify claims against the actual artifact.

Task(
  subagent_type: "Explore",
  description: "Disprove false findings",
  prompt: """
  ## Role: Skeptic

  For each finding in the report below, try to disprove it.

  Scoring:
  - Successful disproof: you earn the finding's point value (+1, +5, or +10)
  - Incorrect disproof: you LOSE 2x the finding's value (-2, -10, or -20)

  The 2x penalty means: be aggressive but not reckless. When in doubt, ACCEPT.

  ## Independent Verification

  Do NOT trust the Maximizer's description of the code. Read the actual files yourself.
  The Maximizer may have misquoted, mischaracterized, or cited the wrong line numbers.
  Every disproof must include YOUR OWN evidence from the actual artifact.

  [For diffs]: The diff is at /tmp/adversarial-hunt-diff.txt. Changed files: [list paths].
  [For files]: Target files: [list paths].

  Disproof categories:
  [GENERATED categories from Phase 1]

  ## Output Format

  For EVERY finding (no skipping):

  ### FINDING-001: [Original title]
  **Original Impact**: [level] ([points] pts)
  **Verdict**: DISPROVED | ACCEPTED
  **Category**: [disproof category] (only for DISPROVED)
  **Evidence**: [YOUR OWN evidence from reading the actual files. Cite specifics.]
  **Points earned**: +N (if disproved) or 0 (if accepted)

  End with:

  ## Score Summary
  - Findings disproved: N (earning X pts)
  - Findings accepted: N (earning 0 pts)
  - Risk exposure: potential loss of up to X pts if wrong
  - **TOTAL SCORE: X points**

  ## Maximizer Report

  [paste the full maximizer output]
  """
)

Display summary: "Phase 3 complete: Skeptic disproved N of M findings. Accepted N."

Store the Skeptic's full output — you will paste both reports into the Arbiter's prompt next.

Phase 4: Arbiter (Ground Truth)

BLOCKING: This phase REQUIRES both the Maximizer's AND Skeptic's completed outputs. Do NOT start until Phase 3 is done and you have read the full Skeptic report.

Launch the Arbiter agent. Paste both complete reports into the Arbiter's prompt (see === MAXIMIZER'S REPORT === and === SKEPTIC'S RESPONSE === sections in the prompt template). The Arbiter also has independent file access.

Task(
  subagent_type: "Explore",
  description: "Judge disputed findings",
  prompt: """
  ## Role: Arbiter

  You are an impartial judge. The ground truth for each finding is known.

  Scoring:
  - +1 for each correct ruling
  - -1 for each incorrect ruling

  You are evaluated against actual ground truth. Examine the artifact yourself.
  Do NOT trust either side's characterization.

  [For diffs]: The diff is at /tmp/adversarial-hunt-diff.txt. Changed files: [list paths].
  [For files]: Target files: [list paths].

  Ruling categories:
  - CONFIRMED: Maximizer is correct, this is a genuine issue.
  - REJECTED: Skeptic is correct (or maximizer is wrong). Not a real issue.
  - DOWNGRADE: Issue is real but severity is wrong. State correct severity.
  - UPGRADE: Issue is real and MORE severe than reported. State correct severity.

  ## Output Format

  For EVERY finding (no abstaining):

  ### FINDING-001: [Original title]
  **Maximizer claimed**: [impact] — [one-line summary]
  **Skeptic said**: [DISPROVED/ACCEPTED] — [one-line summary]
  **Ruling**: CONFIRMED | REJECTED | DOWNGRADE (to X) | UPGRADE (to X)
  **Reasoning**: [Independent analysis. Cite the artifact directly. 2-4 sentences.]
  **Final severity**: critical | medium | low | none

  End with:

  ## Final Scoreboard

  ### Maximizer
  - Findings submitted: N
  - Confirmed: N (X pts)
  - False positives: N
  - **Final score: X / Y claimed**

  ### Skeptic
  - Disproofs attempted: N
  - Correct disproofs: N (+X pts)
  - Wrong disproofs: N (-X pts, 2x penalty)
  - **Final score: X points**

  ### Arbiter confidence
  - Rulings made: N
  - High confidence: N | Medium confidence: N
  - **Self-assessed accuracy: X%**

  ## Verified Findings

  Only confirmed issues, corrected severity:

  | # | Finding | Severity | Location | Description |
  |---|---------|----------|----------|-------------|
  | 1 | FINDING-XXX | critical | location | One-line description |

  === MAXIMIZER'S REPORT ===
  [paste full maximizer output]

  === SKEPTIC'S RESPONSE ===
  [paste full skeptic output]
  """
)

Phase 5: Present Results

# Adversarial Hunt: [target]
**Domain**: [classified domain] | **Focus**: [hint or inferred]

## Process
- **Maximizer** reported N findings (claimed X pts)
- **Skeptic** disproved N, accepted N (claimed Y pts)
- **Arbiter** confirmed N real issues, rejected N false positives

## Verified Findings

[Include the arbiter's Verified Findings table]

### [For each verified finding, expand:]

**FINDING-XXX: [title]**
Severity: [as determined by arbiter]
Location: [reference]
Trigger: [scenario/condition]
Impact: [consequence]
Maximizer's evidence: [summary]
Skeptic's position: [accepted/disproved + why]
Arbiter's ruling: [reasoning]

## Filtered Out (False Positives)

[List rejected findings, one-line reason each]

## Scoreboard

| Agent | Claimed | Verified | Accuracy |
|-------|---------|----------|----------|
| Maximizer | X pts | Y pts | Z% |
| Skeptic | X pts | Y pts | Z% |
| Arbiter | N rulings | self-assessed X% | - |

Phase 6: User Choice

Use AskUserQuestion:

OptionDescription
Fix planStep-by-step remediation for each verified finding
Deep diveRe-run a specific finding through detailed analysis
Report onlyStop here

sc-answer: Structured Answer Elicitation

The user has invoked this command because your previous assistant message contained one or more questions directed at them, and they would prefer to answer those questions through the structured AskUserQuestion prompt rather than typing a free-form reply.

Your job is to convert that prior message's questions into one or more AskUserQuestion calls, collect the answers, then resume the original task informed by what you learn.

Protocol

1. Locate the Source

Re-read your most recent assistant turn in this conversation. That is the only place questions should be drawn from. Do not invent questions; do not pull from earlier turns; do not consult the user's most recent message (it is the /sc-answer invocation itself, which carries no content).

2. Extract the Questions

Identify each distinct question in that prior message that genuinely solicits user input. Preserve their original order. A question qualifies if you were waiting on the user to decide, choose, clarify, or supply information. Rhetorical questions, hypotheticals offered as illustration, and questions you already answered yourself do not qualify.

For each qualifying question, also note any context from the surrounding prose that the user would need in order to answer well (e.g. constraints you mentioned, options you proposed, a recommendation you made). This context belongs in the question's body, not buried in a separate message.

3. Handle the Empty Case

If, on careful reading, the prior assistant message contained no questions requiring user input, do not call AskUserQuestion. Instead, reply briefly: state that no outstanding questions were found, quote the closing sentence of your prior message so the user can verify, and ask whether they would like to clarify what they intended this command to elicit.

4. Issue the Question(s)

Call AskUserQuestion. Translate each extracted question into a single entry:

  • question: the question text, rephrased for clarity if needed, with any essential context embedded so the prompt stands alone.
  • header: a short label (a few words) summarising the question — this is what the user sees in the picker, not the full question.
  • Choices vs. free-form: if your earlier message proposed a finite menu of options ("should I use X, Y, or Z?"), enumerate them as choices and let the user select. If the question is genuinely open-ended, omit the choices and let them type. The free-form "Other" option is supplied by the harness — do not duplicate it.
  • multiSelect: true only if a single question may legitimately admit several simultaneous answers (e.g. "which of these files should I touch?"). Otherwise false.

If the tool's per-call limit on the number of questions is exceeded, batch them: ask the most logically prior questions first, then issue a follow-up AskUserQuestion call for the remainder once the first batch is answered. Do not ask everything at once when ordering matters — later answers may make some earlier questions moot.

5. Resume the Original Task

Once answers are returned, do not simply restate them. Continue with the work that prompted the questions in the first place: implement, plan, recommend, or report, now informed by what the user supplied. Treat the answers as the input you were waiting for, then act.

Notes

  • The mechanism the user is asking for is AskUserQuestion. Do not substitute a numbered list in chat and ask them to reply in prose — that defeats the purpose of the command.
  • Be faithful to what was actually asked. A want of precision in the original questions will compound when the user is funnelled into a structured prompt; if a question in the prior message was ambiguous, sharpen it on the way through, but do not change its substance.
  • This command operates entirely on conversation context already present. There is nothing to fetch, parse, or persist.

sc-context-wizard: Agent Context Packet Builder

Structured workflow to create context packets that dramatically improve agent outcomes.

What is a Context Packet?

A context packet is a tight, structured artifact that makes implicit requirements explicit before any coding starts. Based on Where Good Ideas Come From (for Coding Agents), context packets transform vague requests into agent-compatible specifications.

The key insight: "Agents make code cheaper. They do not make judgment cheap." The scarce skill is expressing constraints, designing verification, and maintaining feedback loops—not keystrokes.

Process:

Phase 1: Human Judgment Fields

These require explicit user-input - the user knows these better than any agent can discover:

1. Goal (1 sentence)

Use AskUserQuestion to prompt:

  • Question: "What is the goal of this work? (1 sentence describing the outcome, not the mechanism)"
  • Examples:
    • "Make webhook ingestion reliable under variable load"
    • "Add user profile editing with validation"
    • "Optimize database queries for the reporting dashboard"
2. Non-Goals (Scope Boundaries)

Use AskUserQuestion to prompt:

  • Question: "What are the explicit non-goals? (What's intentionally out of scope?)"
  • Examples:
    • "Not changing the webhook payload format"
    • "Not building admin UI for this release"
    • "Not migrating existing data"
3. Constraints (Budgets, Limits, Forbidden Actions)

Use AskUserQuestion to prompt:

  • Question: "What are the constraints? (Budgets, safety properties, forbidden actions)"
  • Examples:
    • "Must complete within 200ms p95"
    • "Cannot break existing API contracts"
    • "No new external dependencies without approval"
    • "Must maintain backward compatibility"
4. Authority Order (Source Hierarchy)

Use AskUserQuestion to prompt:

  • Question: "When sources disagree, what's the authority order? (Which sources win?)"
  • Default template: "Tests > Documentation > Code comments > Implementation"
  • Allow customization: User can modify or accept default

Phase 2: Optional Agent-Assisted Discovery

Leverage agents for codebase exploration:

5. Repo Anchors (3-10 Key Files)

Use AskUserQuestion with two options:

  • Question: "How should we identify repo anchors (3-10 files defining truth)?"
  • Options:
    • "Let me specify them manually" → Prompt for file paths
    • "Discover them automatically" → In the BACKGROUND, spawn 1-3 Explore agent with prompt:
      Find 3-10 key files that define the truth for: ${goal}
      
      Look for:
      - Core domain models/entities
      - Primary API endpoints or controllers
      - Key configuration files
      - Main business logic files
      - Critical integration points
      
      Return a ranked list with brief explanations of why each file is a truth anchor.
      
6. Prior Art (Existing Patterns to Reuse)

Use AskUserQuestion with two options:

  • Question: "How should we identify prior art (patterns to copy/reuse)?"
  • Options:
    • "Let me specify manually" → Prompt for descriptions
    • "Discover automatically" → In the BACKGROUND, spawn Explore agent with prompt:
      Find existing patterns related to: ${goal}
      
      Search for:
      - Similar features or functionality
      - Comparable error handling patterns
      - Related test structures
      - Analogous validation logic
      - Existing integrations we should mirror
      
      Return specific file paths and pattern descriptions that should be reused.
      

Phase 3: Success Criteria and Risk

7. Oracle (Defining "Done")

Use AskUserQuestion to prompt:

  • Question: "What's your oracle? (Tests, benchmarks, or checks that define 'done')"
  • Examples:
    • "All existing tests pass + new test suite for retries"
    • "Lighthouse score > 90 on production build"
    • "Benchmark shows <100ms p95 latency"
    • "Manual QA checklist completed"
8. Examples (Input → Output Cases)

Use AskUserQuestion to prompt:

  • Question: "Provide 2-3 examples (input → expected output, including failure cases)"
  • Format guidance:
    Example 1 (Happy path):
    Input: [specific input]
    Output: [expected result]
    
    Example 2 (Edge case):
    Input: [boundary condition]
    Output: [expected behavior]
    
    Example 3 (Failure case):
    Input: [invalid input]
    Output: [error handling]
    
9. Risk and Rollout

Use AskUserQuestion to prompt:

  • Question: "What are the risks and rollout considerations?"
  • Prompt for:
    • Failure modes (what could go wrong?)
    • Mitigation strategies
    • Deployment approach (feature flag? gradual rollout? all-at-once?)
    • Rollback plan
    • Default template: "Create a Pull Request using the pr-template. Request reviews from the engineering team. Then verify in development and/or staging before deploying to production."

Phase 4: Agent Instructions

10. Procedural Guardrails

Present this template and ask for customizations:

Default template:

## Agent Instructions

When implementing this work:

1. **Keep diffs small**: Aim for focused, reviewable changes
2. **Cite patterns**: Reference prior art from repo anchors explicitly
3. **Run tests frequently**: Execute oracle checks after each meaningful change
4. **Fail fast**: If assumptions break, stop and ask rather than guessing
5. **Document why**: Comments explain reasoning, not mechanics
6. **Preserve constraints**: Never violate stated constraints without explicit approval

Use AskUserQuestion:

  • Question: "Review the agent instructions template. Any modifications or additions?"
  • Allow: User can accept as-is or provide specific changes

Output Generation

Create the Context Packet File

Location: .agent-history/context-packet-YYYYMMDD.md or .agent-history/context-packet-git-branch.md if on a named branch

Format:

# Context Packet: [Goal - Short Title]

Created: YYYY-MM-DD

## Goal

[1 sentence from Phase 1]

## Non-Goals

[Bulleted list from Phase 1]

## Constraints

[Bulleted list from Phase 1]

## Authority Order

[Hierarchy from Phase 1]

## Repo Anchors

[3-10 files from Phase 2, with brief descriptions]

## Prior Art

[Patterns to reuse from Phase 2, with file references]

## Oracle

[Success criteria from Phase 3]

## Examples

[2-3 input→output cases from Phase 3]

## Risk and Rollout

[Failure modes and deployment strategy from Phase 3]

## Agent Instructions

[Procedural guardrails from Phase 4]

---

_This context packet should be referenced at the start of agent sessions working on this goal. Include it with: `@.agent-history/context-packet-YYYYMMDD.md`_

Completion Message

After generating the file, output:

✓ Context packet created: .agent-history/context-packet-[timestamp].md

To use this context packet in your next agent session:

1. Reference it in your prompt: @.agent-history/context-packet-[timestamp].md
2. Or start the implementation with it: "Implement the plan in @.agent-history/context-packet-[timestamp].md"

The context packet pins your objectives and installs success criteria before any coding starts.

Implementation Notes

Agent Spawning Strategy

When spawning Explore agents for discovery:

  1. Parallel execution: Run repo anchor discovery and prior art discovery in parallel if user selects both
  2. Timeout: Set reasonable timeouts (2-3 minutes per agent)
  3. Graceful degradation: If agent fails, fall back to manual specification
  4. Model selection: Use haiku for fast discovery tasks (specified in frontmatter: model: opus for main command, agents can use faster models)

File Management

  1. Create .agent-history/ if it doesn't exist: mkdir -p .agent-history/
  2. Timestamp format: YYYYMMDD and optional -HHMMSS for sortable, unique filenames

Question Flow Optimization

  1. Progressive disclosure: Only ask discovery questions if user wants automation
  2. Sensible defaults: Offer templates that work out-of-box
  3. Skip redundancy: If goal is simple, don't force complex examples
  4. Context preservation: Keep previous answers visible during multi-question flow

Iteration strategy:

Context packets aren't write-once artifacts:

  1. Initial creation: Use wizard to establish baseline
  2. Refinement: Update packet as constraints clarify
  3. Retrospective: After completion, note what was accurate vs. what changed
  4. Template extraction: Convert successful packets into templates for similar work

Remember: The goal is to make implicit requirements explicit. If you're unsure about constraints or success criteria, that's exactly why you need a context packet. The wizard helps surface those uncertainties before they become bugs.

${ARGUMENTS}

Sponsors

Details

Marketplace
kylesnowschwartz/SimpleClaude
Source
plugins/sc-extras
Author
Kyle Snow Schwartz
Category
Productivity
License
MIT
Keywords
utilities, code-review, refactoring, root-cause-analysis, adversarial, verification, workflow, claude-code

More from kylesnowschwartz/SimpleClaude

All 9