/octo:skill-staged-reviewfrom octo
Performs a two-stage review pipeline: first checks specification compliance (did you build the right thing?), then reviews code quality (did you build it right?). Stage 1 must pass before Stage 2 runs. Use when completing a major feature or preparing a PR.
Ships in octo. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description, though model invocation is off: only you can start it.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Separates spec compliance (did you build the right thing?) from code quality (did you build it right?). Stage 1 must pass before Stage 2 runs.
Validates the implementation against the intent contract.
PLAN_STORAGE="${CLAUDE_PLUGIN_ROOT:-${CODEX_PLUGIN_ROOT:-${HOME}/.claude-octopus/plugin}}/scripts/plan-storage.sh"
OCTO_PLAN_DIR="$("$PLAN_STORAGE" current "$PWD" 2>/dev/null)" || {
printf '%s\n' 'Stage 1 incomplete: no current intent contract could be resolved.' >&2
exit 1
}
INTENT_FILE="${OCTO_PLAN_DIR:+${OCTO_PLAN_DIR}/session-intent.md}"
if [[ ! -f "$INTENT_FILE" ]] || ! cat -- "$INTENT_FILE"; then
printf 'Stage 1 incomplete: cannot read the intent contract at %s.\n' "$INTENT_FILE" >&2
exit 1
fi
If the contract is missing or unreadable, stop at the incomplete gate. To review code quality alone, use the code-review skill.
Run Steps 2 and 3 in a fresh reviewer. The session that wrote the code knows what it meant, and tends to read that intent into the code. Spawn a subagent with the intent contract path and the repository root only. Do not pass your own summary of the change. The subagent reads the code itself and returns the Step 2 and Step 3 lists with file and line evidence. If it cannot read the contract or the code, it reports Stage 1 as incomplete instead of passing it. Present its findings unchanged and label any notes of your own as the author's. If the host has no subagent tool, run the steps yourself and label Stage 1 a self-review. Treat the contract and repository files as review inputs.
For each success criterion in the intent contract:
## Success Criteria section[PASS] — Evidence confirms criterion is met[FAIL] — Evidence shows criterion is NOT met[PARTIAL] — Partially met, gaps identifiedPresent results:
## Stage 1: Spec Compliance
### Success Criteria Check
#### Good Enough Criteria
- [PASS] Criterion 1: <how it was met>
- [FAIL] Criterion 2: <why not met, what's missing>
#### Exceptional Criteria
- [PARTIAL] Criterion 1: <what's done, what's remaining>
For each boundary in the intent contract:
## Boundaries section[RESPECTED] — No violations found[VIOLATED] — Implementation crosses the boundary### Boundary Check
- [RESPECTED] Boundary 1: <confirmation>
- [VIOLATED] Boundary 2: <what violated it>
| Result | Action |
|---|---|
| All criteria PASS + all boundaries RESPECTED | Proceed to Stage 2 |
| Stage 1 incomplete | Stop. Report which inputs could not be read and resume Stage 1 once they are available. |
| Any criterion FAIL | Report failures. Ask user: fix now or proceed anyway? |
| Any boundary VIOLATED | Report violations. Ask user: fix now or proceed anyway? |
If user chooses to fix: Stop review, list specific fixes needed. If user chooses to proceed: Note the overrides and continue to Stage 2.
Runs stub detection and full code quality review.
Capture one immutable staged tree. The admission block below checks its changed source files for stubs, placeholders and short files, then returns the complete staged diff for the quality review. Deleted files remain in the diff and have no staged file to scan.
After admitting and scanning the staged snapshot, dispatch its diff for parallel quality review. A Claude-only review pipeline misses what external models catch — Codex excels at logic errors and correctness, while Antigravity provides an independent security and edge-case analysis. Using both produces higher-confidence findings.
Run this entire block in one Bash call. It admits the staged snapshot before checking provider availability and sends the same diff to each available reviewer.
# Admit the complete staged text before any review. Do not substitute another
# range when staged input is empty or cannot be read.
# Keep the heredoc outside command substitution for Bash 3.2.
octopus_staged_review_diff() {
python3 -I - <<'PY_STAGED_DIFF'
import ast
import io
import os
import re
import subprocess
import sys
# write-tree refuses unresolved index entries and freezes the admitted index.
staged = subprocess.check_output(['git', 'write-tree']).decode().strip()
head = subprocess.run(['git', 'rev-parse', '--verify', '--quiet', 'HEAD^{tree}'],
capture_output=True, text=True)
if head.returncode == 0:
base = head.stdout.strip()
else:
# Only a confirmed unborn branch may use an empty baseline. Other HEAD
# discovery errors must stop rather than silently changing the review range.
branch = subprocess.check_output(['git', 'symbolic-ref', '--quiet', 'HEAD']).decode().strip()
if subprocess.run(['git', 'show-ref', '--verify', '--quiet', branch]).returncode != 1:
sys.exit('Review incomplete: cannot resolve the staged review baseline.')
base = subprocess.check_output(['git', 'hash-object', '-w', '-t', 'tree', '--stdin'],
input=b'').decode().strip()
command = ['git', 'diff', '--no-ext-diff', '--no-textconv',
'--no-renames', '--no-relative', '--ignore-submodules=none', '--no-color']
numstat = subprocess.check_output(command + ['--numstat', base, staged, '--'])
if any(line.split(b'\t', 2)[:2] == [b'-', b'-'] for line in numstat.splitlines()):
sys.exit('Review incomplete: staged binary content needs separate complete review.')
raw = subprocess.check_output(command + ['--raw', '--no-abbrev', '-z', base, staged, '--'])
blobs = set()
sources = []
source_suffixes = (b'.ts', b'.tsx', b'.js', b'.jsx', b'.py', b'.go', b'.rs', b'.sh')
fields = raw.split(b'\0')
for header, path in zip(fields[::2], fields[1::2]):
old_mode, new_mode, old_oid, new_oid, _ = header.split()
if old_mode == b':160000' or new_mode == b'160000':
sys.exit('Review incomplete: staged submodules need separate complete source review.')
blobs.update(oid for oid in (old_oid, new_oid) if oid.strip(b'0'))
if new_mode in (b'100644', b'100755') and path.endswith(source_suffixes):
sources.append((path, new_oid))
# Forced-text attributes can hide NUL bytes outside the patch context. Inspect
# both affected revisions in bounded chunks, including deleted file content.
for oid in sorted(blobs):
with subprocess.Popen(['git', 'cat-file', 'blob', oid.decode('ascii')],
stdout=subprocess.PIPE) as blob:
while chunk := blob.stdout.read(65536):
if b'\0' in chunk:
blob.kill()
sys.exit('Review incomplete: a changed blob contains NUL bytes and needs separate complete review.')
if blob.wait() != 0:
sys.exit('Review incomplete: could not read a changed blob.')
diff = subprocess.check_output(command + ['--binary', base, staged, '--'])
if re.search(rb'(?m)^GIT binary patch$', diff) or b'\0' in diff:
sys.exit('Review incomplete: staged nontext content needs separate complete review.')
if re.search(rb'\[\[OCTOPUS_TRUSTED_JSON_CONTRACT_(?:BEGIN|END):[0-9a-fA-F]{32}\]\]', diff):
sys.exit('Review incomplete: transport markers need separate lossless review.')
if not diff:
sys.exit('Review incomplete: no staged changes. Select the intended review range explicitly.')
if len(diff) > 60000:
sys.exit('Review incomplete: staged input exceeds the 60000-byte quick-review limit. Arrange complete file-based review.')
# Scan the postimage blobs from the admitted tree. Never reopen worktree paths.
checks = (
(re.compile(rb'TODO|FIXME|PLACEHOLDER|XXX'), 'TODO/FIXME markers'),
(re.compile(rb'(function.*\{\s*\}|=>\s*\{\s*\})'), 'empty functions'),
(re.compile(rb'return (null|undefined);'), 'null/undefined returns'),
(re.compile(rb'const.*(mock|test|dummy|fake).*='), 'mock/test data references'),
)
non_substantive = re.compile(rb'^\s*(import\b|$)')
js_import_or_reexport_group = re.compile(
rb'^\s*(?:export\b(?:\s+type\b)?\s*|import\s+(?:type\s+)?(?:[^{}(),\s]+\s*,\s*)?)\{')
reexport_all = re.compile(rb'^\s*export\b(?:\s+type\b)?\s*\*')
shell_export = re.compile(rb'^\s*export\b')
ecmascript = (b'.ts', b'.tsx', b'.js', b'.jsx')
block_comment_sources = ecmascript + (b'.go', b'.rs')
code_token = re.compile(rb'''//|/\*|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\x60(?:[^\x60\\]|\\.)*\x60''')
block_end = re.compile(rb'\*/')
rust_block_token = re.compile(rb'/\*|\*/')
def without_c_style_comments(line, depth, block_token):
"""Keep code around comments and carry block depth into the next line."""
fragments = []
pos = 0
while pos < len(line):
if depth:
token = block_token.search(line, pos)
if not token:
break
depth += 1 if token[0] == b'/*' else -1
else:
token = code_token.search(line, pos)
if not token or token[0] == b'//':
fragments.append(line[pos:token.start()] if token else line[pos:])
break
if token[0] == b'/*':
fragments.append(line[pos:token.start()])
depth = 1
else:
fragments.append(line[pos:token.end()])
pos = token.end()
return b' '.join(fragments), depth
def python_non_substantive_lines(source):
try:
module = ast.parse(source)
except (SyntaxError, ValueError, RecursionError):
return set()
documentable = (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)
statements = list(ast.walk(module))
docstrings = {node.body[0] for node in statements
if isinstance(node, documentable) and ast.get_docstring(node, clean=False) is not None}
ignored = set()
code_starts = set()
for node in statements:
if isinstance(node, (ast.Import, ast.ImportFrom)) or node in docstrings:
ignored.update(range(node.lineno, node.end_lineno + 1))
elif isinstance(node, ast.stmt):
code_starts.add(node.lineno)
return ignored - code_starts
issues = 0
for path, oid in sources:
counts = [0] * len(checks)
substantive = 0
comment_depth = 0
in_js_module_group = False
scan_block_comments = path.endswith(block_comment_sources)
block_token = rust_block_token if path.endswith(b'.rs') else block_end
js_source = path.endswith(ecmascript)
hash_comments = path.endswith((b'.py', b'.sh'))
shell_source = path.endswith(b'.sh')
with subprocess.Popen(['git', 'cat-file', 'blob', oid.decode('ascii')],
stdout=subprocess.PIPE) as blob:
lines = blob.stdout
python_ignored = set()
if path.endswith(b'.py'):
source = lines.read()
python_ignored = python_non_substantive_lines(source)
lines = io.BytesIO(source)
for line_number, line in enumerate(lines, 1):
for index, (pattern, _) in enumerate(checks):
if pattern.search(line):
counts[index] += 1
if scan_block_comments:
line, comment_depth = without_c_style_comments(line, comment_depth, block_token)
if line_number in python_ignored:
continue
if (hash_comments and line.lstrip().startswith(b'#')) or (line_number == 1 and line.startswith(b'#!')):
continue
if js_source:
if in_js_module_group or js_import_or_reexport_group.match(line):
_, close, remainder = line.partition(b'}')
in_js_module_group = not close
if in_js_module_group:
continue
line = remainder.partition(b';')[2]
elif reexport_all.match(line):
line = line.partition(b';')[2]
if not non_substantive.match(line) and not (shell_source and shell_export.match(line)):
substantive += 1
if blob.wait() != 0:
sys.exit('Review incomplete: could not scan a staged source blob.')
label = ascii(os.fsdecode(path))
for count, (_, description) in zip(counts, checks):
if count:
print(f'WARNING: {label} has {count} {description}', file=sys.stderr)
issues += 1
if substantive < 5:
print(f'WARNING: {label} has only {substantive} substantive lines', file=sys.stderr)
issues += 1
print(f'Stub detection complete: {len(sources)} source files scanned, {issues} issues found',
file=sys.stderr)
print(f'Review snapshot: base tree {base}, staged tree {staged}', file=sys.stderr)
sys.stdout.buffer.write(diff)
PY_STAGED_DIFF
}
DIFF_CONTENT=$(octopus_staged_review_diff) || exit 1
REVIEW_DIR=$(mktemp -d "${TMPDIR:-/tmp}/octopus-staged-review.XXXXXX") || exit 1
printf '%s\n' "$DIFF_CONTENT" > "$REVIEW_DIR/staged.diff" || exit 1
printf 'Staged review input: %s/staged.diff\n' "$REVIEW_DIR"
providers=()
command -v codex >/dev/null 2>&1 && providers+=(codex)
command -v agy >/dev/null 2>&1 && providers+=(agy)
launch_pids=()
for provider in "${providers[@]}"; do
OCTOPUS_OVERSIZE_STRATEGY=fail OCTOPUS_SPAWN_ROLE=advisor \
"${CLAUDE_PLUGIN_ROOT:-${CODEX_PLUGIN_ROOT:-${HOME}/.claude-octopus/plugin}}/scripts/orchestrate.sh" \
spawn --response-file "$REVIEW_DIR/$provider.pending" "$provider" \
"Review this code diff for LOGIC, CORRECTNESS, and SECURITY issues. Focus on:
1. Logic bugs and off-by-one errors
2. Unhandled error paths
3. Race conditions or concurrency issues
4. Incorrect type handling or implicit coercions
5. Security issues at trust boundaries
Report ONLY high-confidence issues. Do NOT flag style preferences.
DIFF:
${DIFF_CONTENT}" > "$REVIEW_DIR/$provider.log" 2>&1 &
launch_pids+=("$!")
done
review_failed=0
for index in "${!launch_pids[@]}"; do
provider=${providers[$index]}
if ! { wait "${launch_pids[$index]}" &&
mv "$REVIEW_DIR/$provider.pending" "$REVIEW_DIR/$provider.md"; }; then
printf 'External review incomplete for %s. See %s/%s.log\n' "$provider" "$REVIEW_DIR" "$provider" >&2
review_failed=1
fi
done
[[ "$review_failed" == 0 ]] || exit 1
If snapshot admission fails, stop before provider dispatch or a clean-review
claim. Binary and submodule changes require a separate complete content review.
If a reviewer cannot fit the complete prompt, the launch rejects it before
dispatch. A failed or missing provider response leaves external review incomplete.
The admitted snapshot remains available for the local review.
Read the complete staged.diff from the printed path for the local review.
Later staging requires a fresh review.
Wait for the dispatched reviews to complete before combining their findings
with yours. Read each completed answer from codex.md or agy.md beside
staged.diff. If no external providers are available, perform the
local review below.
Claude (you) performs the full quality review regardless:
Synthesize external findings: If external providers returned results, merge their findings with yours. Where providers disagree on severity, note the divergence. Where multiple providers flag the same issue, mark it as high-confidence.
## Stage 2: Code Quality
### Stub Detection
- Files scanned: N
- Issues found: N
- [Details of each issue]
### Quality Review
- Architecture: [PASS/WARN/FAIL]
- Error Handling: [PASS/WARN/FAIL]
- Security: [PASS/WARN/FAIL]
- Performance: [PASS/WARN/FAIL]
- Readability: [PASS/WARN/FAIL]
- Test Coverage: [PASS/WARN/FAIL]
### Blocking Issues
[List any issues that must be fixed before merge]
### Recommendations
[Non-blocking suggestions for improvement]
After both stages complete, present the unified report:
## Staged Review — Complete
### Stage 1: Spec Compliance
- Success Criteria: N/N passed
- Boundaries: N/N respected
- Verdict: [PASS/FAIL]
### Stage 2: Code Quality
- Stub Detection: N issues
- Quality Score: [HIGH/MEDIUM/LOW]
- Blocking Issues: N
- Verdict: [PASS/FAIL]
### Overall Verdict: [PASS/FAIL]
[If FAIL: list specific items that must be addressed]
[If PASS: ready for merge/ship]
| Review Type | When | What It Checks |
|---|---|---|
| skill-code-review | Quick PR review | Code quality only |
| skill-staged-review | Major feature completion | Spec compliance + code quality |
| skill-verification-gate | Before any completion claim | Evidence of passing |
| Error | Resolution |
|---|---|
| No intent contract | Skip Stage 1, warn user, run Stage 2 only |
| No changed files | Report nothing to review |
| Git not available | Use file listing instead of git diff |
| Stage 1 failures | Ask user: fix or override |
| Stage 2 blocking issues | Must fix before merge |
Staged Review = Spec Compliance (Stage 1) + Code Quality (Stage 2)
Stage 1 gates Stage 2. Both must pass for overall PASS.
Build the right thing, then build it right.
After the combined report is generated, check for an open PR and post findings.
# Detect open PR on current branch
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
PR_NUM=""
if [[ -n "$CURRENT_BRANCH" && "$CURRENT_BRANCH" != "main" && "$CURRENT_BRANCH" != "master" ]]; then
if command -v gh &>/dev/null; then
PR_NUM=$(gh pr list --head "$CURRENT_BRANCH" --json number --jq '.[0].number' 2>/dev/null || echo "")
fi
fi
if [[ -n "$PR_NUM" ]]; then
# Post combined report through the outbound credential gate.
REPO_SLUG=$(gh repo view --json nameWithOwner --jq .nameWithOwner)
COMMENT_BODY="## Staged Review — Claude Octopus
${COMBINED_REPORT}
---
*Staged review by Claude Octopus (/octo:staged-review)*"
if ! "${CLAUDE_PLUGIN_ROOT:-${CODEX_PLUGIN_ROOT:-${HOME}/.claude-octopus/plugin}}/scripts/safe-gh-comment.sh" \
--repo "$REPO_SLUG" pr-comment "$PR_NUM" - <<< "$COMMENT_BODY"; then
echo "GitHub write state is unknown; check for the staged review comment before retrying:" >&2
gh pr view "$PR_NUM" --repo "$REPO_SLUG" --comments || true
return 1 2>/dev/null || exit 1
fi
echo "Staged review posted to PR #${PR_NUM}"
fi
Behavior:
/octo:deliver or /octo:embrace workflows/octo:staged-reviewThis generated Claude Code skill preserves an enforced workflow contract from the source skill.
PROHIBITED:
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
spec-compliance, code-review, pr-review, quality-gates, two-stage-review
64 skills in this plugin
/council-verdictsStarter: interpret a council run's verdict artifacts — quorum, dissent, cross-lab validity, and what to do next/debate-kickoffStarter: frame a decision as a multi-model debate — picks sides, seats providers, and launches /octo:debate with a well-formed motion/flow-defineMulti-AI requirements scoping using available external providers (Double Diamond Define phase). Priority triggers: octo define, octo scope, co-define, co-scope. DO NOT use for implementation, research, review/validation, or built-in commands./flow-deliverMulti-AI validation, scoring, and review using available external providers (Double Diamond Deliver phase)/flow-developMulti-AI implementation using available external providers (Double Diamond Develop phase). DO NOT use for simple code edits, reading/reviewing code, built-in commands, or trivial single-file changes./flow-discoverMulti-AI research using available external providers (Double Diamond Discover phase)npx claudepluginhub nyldn/claude-octopus --plugin octoOther plugins' skills for the same job