Junhanliu-dev/espalier-engineering / skills/espalier-init
espalier-init
VerifiedAnalyze any existing codebase, discover its patterns and best practices, and generate an Espalier structure (rules, skills, wiki, pipeline) so AI coders produce code matching that project's language and conventions. Greenfield repos take the two-pass Decide-Then-Bind path (/espalier-map charts the conventions, init binds them); boilerplate repos run init normally, then map the product. Wires into Claude Code, Codex, and/or GitHub Copilot (.claude/, .agents/skills/ + .codex/, .github/).
templates/skills/espalier-fix.md
View on GitHub---
name: espalier-fix
description: Bug-fix orchestrator — 7 stages (0–7, no Stage 2) with auto-link to the change that introduced the bug
---
# Espalier Fix Runner
## When to Use
- "Fix the bug in <file>:<line>"
- "/espalier-fix <bug description>"
- "Bug: NPE at src/payment.ts:42"
Do NOT use for:
- Features ("add X") → use `/espalier feat: …`
- Refactors with no behaviour change → use `/espalier refactor: …`
- Fixes that obviously cross >5 files, multiple layers, or require schema changes → use `/espalier fix: …` directly (full pipeline)
## Pipeline Overview (7 stages (0–7, no Stage 2), vs 10 for /espalier)
| Stage | Name | Skipped from /espalier? |
|-------|------|-------------------------|
| 0 | Auto-link Discovery | NEW (fix-only) |
| 1 | Bug Requirements | Slimmer than feat reqs |
| 3 | Coding | Same |
| 4 | Code Review | Same |
| 5 | Contract Phase (folded) / Test Writing (serial) | Same |
| 6 | Contract Delta Review (folded) / Test Review (serial) | Same |
| 7 | Push | Same + back-link write |
Skipped from full pipeline:
- **Stage 2** (standalone reqs review — merged into Stage 4 code review)
- **Stage 8** (CI verify — fix lane defers to repo CI hook)
- **Stage 9** (deploy verify — fix lane assumes same deploy as next normal release)
- **Stage 10** (user confirm — bug reporter confirms via the regression test, not a separate gate)
## Flags
| Flag | Effect |
|------|--------|
| `--slug <name>` | Override auto-derived slug (see Slug Derivation below). Literal — no date prefix added. Must match `^[a-z0-9][a-z0-9-]{0,90}$`; prefer `YYYY-MM-DD-<name>` to keep chronological sort. |
| `--caused-by <slug>` | Skip blame, explicit causal link (e.g. `--caused-by feat/bulk-export-endpoint`). |
| `--build-index` | Run `espalier/hooks/rebuild-commit-index.sh`, then continue normally. |
| `--rebuild-index` | Delete `espalier/.commit-index.tsv`, then run rebuild (forces fresh state). |
| `--no-index` | Bypass reverse-lookup cache for this invocation only (debug). |
| `--no-grill` | Skip the Stage 1 diagnosis grill for this invocation. |
| `--simple` | The human-review lane: diagnose → spec → approval → fix → review → regression gate, then STOP with the fix uncommitted for a human to commit by hand. Records live in `espalier/.simple/{slug}/` (gitignored) and Approve deletes them; Stage 0 auto-link runs read-only (no index write, no back-link), no pre-flight, no security auditor, no commit, no push, no PR. Procedure: `espalier/skills/espalier/stages/simple.md` (shared with the full lane). |
Env vars:
- `ESPALIER_CACHE_THRESHOLD_MS=<ms>` — override the auto-build slow-scan threshold (default 1000ms; 0 = never warn). Legacy `HARNESS_CACHE_THRESHOLD_MS` also honored.
### Flag Handling (parsed at invocation entry)
Parse flags from the user's invocation string. Strip them out before deriving the slug from remaining text. Set the corresponding shell variables for Stage 0 / later stages to consume:
```bash
# Pseudo-shell of what the orchestrator must do before Stage 0:
SLUG_OVERRIDE=""
CAUSED_BY_OVERRIDE=""
NO_INDEX="no"
DO_BUILD_INDEX="no"
DO_REBUILD_INDEX="no"
GRILL_DISABLED="no"
SIMPLE_MODE="no"
# Walk tokens, extract flags
# (Orchestrator parses argv; below is the variable contract — not literal bash)
case "$flag" in
--slug) SLUG_OVERRIDE="$next_arg" ;;
--caused-by) CAUSED_BY_OVERRIDE="$next_arg" ;;
--no-index) NO_INDEX="yes" ;;
--no-grill) GRILL_DISABLED="yes" ;;
--simple) SIMPLE_MODE="yes" ;;
--build-index) DO_BUILD_INDEX="yes" ;;
--rebuild-index) DO_REBUILD_INDEX="yes" ;;
esac
# Pre-Stage-0 actions
if [ "$DO_REBUILD_INDEX" = "yes" ]; then
rm -f espalier/.commit-index.tsv
bash espalier/hooks/rebuild-commit-index.sh
elif [ "$DO_BUILD_INDEX" = "yes" ]; then
bash espalier/hooks/rebuild-commit-index.sh
fi
# Stage 0 then reads $NO_INDEX, $SLUG_OVERRIDE, $CAUSED_BY_OVERRIDE.
# Source helpers once:
. espalier/hooks/lookup-helpers.sh
```
The remaining (flag-stripped) text becomes the bug description fed to Slug Derivation step 2+.
## Slug & Path
- Slug derivation: see Slug Derivation section below. Summary: sanitize bug input → kebab-case ASCII `{kebab}` (max 80 chars), then date-prefix → `{slug}` = `{YYYY-MM-DD}-{kebab}`; `--slug <name>` overrides literally; collision prompts user.
- Path = `espalier/changes/fix/{slug}/` (e.g. `espalier/changes/fix/2026-06-02-npe-in-cart/`) — under `--simple`, `espalier/.simple/{slug}/` everywhere this file says `espalier/changes/fix/{slug}/` (the path rule of `stages/simple.md`).
- All files inherit from `espalier/changes/_template/`.
## Slug Derivation
Steps 2–10 produce `{kebab}` (the deterministic identity tail). Step 10.5
date-prefixes it into the final `{slug}`. All steps are deterministic except
step 1 (override) and step 11 (collision prompt).
### Step 1: Override check
If user passed `--slug <name>`:
- The override is **literal** — taken as the full `{slug}` verbatim, no date
prefix is added (the user owns the whole name). To keep chronological sort,
prefer passing `--slug YYYY-MM-DD-<name>`.
- Validate: must match `^[a-z0-9][a-z0-9-]{0,90}$` (≤ 91 chars, kebab, starts
non-hyphen). The wider cap leaves room for a `YYYY-MM-DD-` prefix.
- If valid, skip to step 11 (collision check).
- If invalid, error and exit with message showing the regex.
### Step 2: Strip type prefix
`fix: foo bar` → `foo bar`
`feat: ignored` → error (wrong skill — espalier-fix should only see fix-shape input)
### Step 3: Lowercase
`NPE In Cart` → `npe in cart`
### Step 4: Transliterate Unicode → ASCII
Use Python `unidecode` library:
```python
from unidecode import unidecode
ascii_text = unidecode(input_text)
```
If unidecode unavailable, fall back to:
```python
ascii_text = input_text.encode('ascii', 'ignore').decode('ascii')
```
(Strip fallback loses CJK/RTL meaning but never crashes.)
Examples:
- `修复支付错误` → unidecode: `Xiu Fu Zhi Fu Cuo Wu` → continues to step 5
- `café crash` → unidecode: `cafe crash`
- With ASCII-strip fallback: `修复支付错误` → `` (continues to step 8 → timestamp fallback)
### Step 5: Replace non-[a-z0-9] runs with single hyphen
`npe in cart` → `npe-in-cart`
`bug at src/payment.ts:42` → `bug-at-src-payment-ts-42`
`v2.3.1 broken` → `v2-3-1-broken`
### Step 6: Trim leading/trailing hyphens
`-rf this is joke-` → `rf-this-is-joke`
### Step 7: Truncate to 80 chars at word boundary
- If ≤ 80, keep as-is.
- If > 80, cut at last hyphen ≤ 80. If no hyphen in first 80 chars, hard-cut at 80.
### Step 8: Empty-result fallback
If empty after sanitization (e.g., all-symbol input or ASCII-strip-emptied CJK), use
`{kebab}` = `fix-{HHMMSS}` (UTC time, e.g., `fix-143022`). Step 10.5 prepends the
date, giving a final slug like `2026-06-02-fix-143022` (no doubled date).
### Step 9: Reserved-name prefix
If slug ∈ {con, aux, nul, prn, com1..9, lpt1..9} (Windows reserved):
prefix with `fix-`
### Step 10: Leading-hyphen guard
If starts with hyphen (post-sanitization edge case): prefix with `x-`
### Step 10.5: Date prefix
Prepend the UTC creation date so change folders sort chronologically:
```bash
DATE="$(date -u +%Y-%m-%d)" # ISO date — lexical sort == chronological sort
SLUG="${DATE}-${kebab}" # e.g. 2026-06-02-npe-in-cart
```
`{slug}` = `{YYYY-MM-DD}-{kebab}`. The ISO date MUST be a *prefix* (a trailing
date does not sort). Reverse-lookup and the commit index derive their slug from
the folder basename, so the dated slug flows through unchanged.
### Step 11: Collision detection + prompt
Match by `{kebab}` **tail**, not exact `{slug}` — re-deriving on a later day
yields a new date prefix, so an exact match would miss an in-progress fix from a
prior day. Glob existing dirs and compare the part after the `YYYY-MM-DD-`:
```bash
shopt -s nullglob
matches=(espalier/changes/fix/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-"${kebab}")
# --simple: the simple folder instead — a simple run and a normal fix never
# adopt each other (stages/simple.md); a FILED skeleton match is one line, not an adoption
[ "$SIMPLE_MODE" = yes ] && matches=(espalier/.simple/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-"${kebab}")
```
For each match read its `pipeline-state.md` Status (and tombstones at
`<match>/TOMBSTONE.md`):
| Existing state | Action |
|----------------|--------|
| No tail match | Use `{slug}` (today's date + kebab). Done. |
| Match exists, Status: IN_PROGRESS | Resume that fix. Announce "Resuming fix/{matched-slug} from Stage {N}". |
| Match exists, terminal Status (COMPLETE / ABORTED / ABORTED_LATE / ESCALATED / ESCALATED_LATE) | **Prompt user** (below) — a same-name fix on a new day is usually a *new* dated folder, but confirm intent. |
| Match exists, Status: PARTIAL_FIX | **Prompt user** (below) |
| Match exists, Status: FILED | Offer to adopt/start it — the skeleton was filed by a partial fix; adopting = set `- Status: IN_PROGRESS` and begin at Stage 1 with its inherited frontmatter (a `charted_from:` skeleton also gets the digest fold — see the espalier skill's FILED-skeleton scan). |
| Only `TOMBSTONE.md` exists (legacy migration) | Follow tombstone pointer; ask user "fix/{matched-slug} was migrated to feat/{target}. New fix at fix/{slug}, or work on feat/{target} instead?" |
Collision prompt (use `AskUserQuestion`):
```
Slug collision detected.
Existing: espalier/changes/fix/{slug}/ — Status: {EXISTING_STATUS}
{If PARTIAL_FIX: Root cause feat: {root_cause_feat}}
{If COMPLETE: Closed on {date}}
Options:
1. New fix with suffix — use fix/{slug}-2 (or next available -N)
2. {Only if Status=PARTIAL_FIX or IN_PROGRESS:} Resume / extend the existing fix
3. {Only if Status=COMPLETE/ABORTED/etc:} Re-open the existing fix
(mark Status: REOPENED, restart from Stage 1, append "Reopened at" row to pipeline-state.md)
4. Custom slug — re-prompt for --slug value
5. Abort
```
**Cross-branch slug collisions (merge-time).** The glob above sees only THIS
checkout's branch: two branches can mint the same dated slug independently
and collide only when the second PR merges — git surfaces it as add/add
conflicts under `espalier/changes/`. The resolution recipe lives in
`espalier/skills/espalier-prune/SKILL.md` → "Slug collisions across branches" (rename one dir to
the next free `-N` suffix, run `espalier/hooks/rebuild-commit-index.sh`, and
rewrite that slug in every `## Follow-up Fixes` table — all in one commit).
### Step 12: Final validation
- Confirm the dated slug matches `^[0-9]{4}-[0-9]{2}-[0-9]{2}-[a-z0-9][a-z0-9-]{0,79}$`
(a `--slug` literal override that omits the date is instead allowed by the
step-1 regex `^[a-z0-9][a-z0-9-]{0,90}$`).
- Confirm `espalier/changes/fix/{slug}/` is now creatable (does not exist OR was user-confirmed for reuse).
## Before Starting
### Install discovery (first step of every invocation)
Same rule as `/espalier` (its "Install discovery" section): `espalier/` is a
real directory or a gitignored symlink into
`<parent>/espalier-main/<basename>/espalier` (outside mode, v0.30). When the
symlink is missing, re-create it from the sibling root or stop:
```bash
if [ ! -e espalier ]; then
R="$(git rev-parse --show-toplevel)"
# The local git config remembers a non-default root (--outside=<dir> /
# --outside-name); the default sibling is the fallback.
M="$(git config --local --get espalier.outside-root 2>/dev/null)"
[ -n "$M" ] && [ -f "$M/.espalier-origin" ] || M="$(dirname "$R")/espalier-main/$(basename "$R")"
if [ -f "$M/.espalier-origin" ] && [ "$(head -1 "$M/.espalier-origin")" = "$R" ] && [ -d "$M/espalier" ]; then
[ -L espalier ] && rm -f espalier # a dangling link
ln -s "$(python3 -c 'import os,sys; print(os.path.relpath(sys.argv[1], sys.argv[2]))' "$M/espalier" "$R")" espalier
bash espalier/hooks/espalier-outside.sh discover "$R" # rewrites the .git/info/exclude block + the remembered root
echo "relinked the outside install at $M"
else
echo "no espalier install — run /espalier-init first"
# STOP HERE. Nothing below can run without the tree.
fi
fi
```
0. **Simple mode** (`SIMPLE_MODE=yes`): read
`espalier/skills/espalier/stages/simple.md` NOW, run its pre-checks
(unattended → refuse; dirty tree outside `espalier/` → refuse; dirty
`espalier/` → one line), and keep it resident for the run. It overrides
this file where it says so: the folder is `espalier/.simple/{slug}/`, the
Stage 0 pre-flight does not run, Stage 0 auto-link runs read-only, the
approval gate asks one question, the coder never runs git, Stage 4 is
the reviewer alone, and Stage 7 is its Final Gate (no split, no
back-link, no PR). Everything it does not mention runs as written below.
1. Read `espalier/pipeline.md` for stage definitions (Stages 3-7 unchanged from /espalier).
2. Check session resumption:
```bash
find espalier/changes/fix -mindepth 2 -maxdepth 2 -name pipeline-state.md
# --simple: espalier/.simple/*/pipeline-state.md with `- Mode: simple` instead
```
Resume is status-driven, not stage-driven: Resume any change whose
`- Status:` is `IN_PROGRESS`, at whatever stage its `Current Stage:`
records — including a crash mid-Stage-7. Statuses `COMPLETE`, `ABORTED`,
`ABORTED_LATE`, `ESCALATED`, `ESCALATED_LATE` are terminal — never resumed.
`PARTIAL_FIX` keeps its existing prompt ('Resume / extend' offer — see the
collision table, step 11). `FILED` skeletons are not resumed here; they are
adopted by the full lane's FILED-skeleton scan.
3. If a matching `IN_PROGRESS` slug found, RESUME from its recorded stage —
append `| {N} | RESUMED | {ts} | fresh session |` to Stage History first
(the row that closes the gap; `espalier-stats.sh` books the time before
it as human wait).
4. Otherwise, derive slug (above) and create new `espalier/changes/fix/{slug}/`
from `espalier/changes/_template/`. On creation, write `- Current Stage: 0`
and `- Status: IN_PROGRESS` to the Status block — this is what the collision
check (step 11) and Session Resumption read.
## Stage State Protocol (MANDATORY — every stage)
The fix lane uses the SAME per-stage state discipline as `/espalier` (its Stage
Execution Protocol). At the START of each stage below, before doing the stage's
work: write `- Current Stage: {N}` to this fix's pipeline-state.md and append a
Stage History row (timestamps via `date -u +%Y-%m-%dT%H:%M:%SZ` — full seconds,
so the stats duration report can measure spans; bookkeeping steps with no agent
in flight may batch into one bash invocation). This is not optional bookkeeping — the **Stage 7 push gate
blocks unless `Current Stage:` ≥ 7**, so a lane that never updates the stage
number cannot push its own clean work. `Status:` stays `IN_PROGRESS` from
creation until a terminal state (COMPLETE / ABORTED / ABORTED_LATE / ESCALATED /
PARTIAL_FIX) is written at the end. Stage numbers in this lane: 0, 1, 3, 4, 5,
6, 7 (2/8/9/10 are skipped — see the overview table; the gate only requires ≥ 7).
## Stage 0 Pre-Flight (drift + conventions + doctor)
**Simple mode: this section does not run** — go straight to Stage 0
Auto-Link Discovery (`stages/simple.md`). Otherwise:
Run this BEFORE Stage 0 Auto-Link Discovery. Source the drift helpers:
```bash
. espalier/hooks/drift-helpers.sh
```
Gather all three signals BEFORE prompting:
1. **STALE** — `stale_files()` lists flagged files; `tier_counts()` buckets them
into fresh / aging / stale / critical / expired. Beside it, information
only: `contract_drift_lines` summed over `espalier/rules/*.md` — when the
total N is above 0 the pre-flight line gains ` · drift=N` (the rules
Writing Contract; never a prompt on its own).
2. **CONV** — `conv_fold` (in `drift-helpers.sh`) folds the legacy
`espalier/.conventions.tsv` AND any `espalier/conventions/*.tsv` per-key
files into `key<TAB>diverges_count<TAB>status` lines; every key with status
`diverges` and `diverges_count` >= 3 is a promotion candidate. Do not parse
the files yourself.
3. **DOCTOR** — `doctor_due()`. Skip if `/espalier-doctor` is not installed.
If all three are empty/false → no prompt, continue to Stage 0 Auto-Link
Discovery. If only fresh (<14d) stale docs and no conv/doctor signal →
treat as empty.
**Critical/expired stale row present** (`tier_counts` shows critical or
expired > 0) → issue ONE blocking `AskUserQuestion` NOW, default
**"Handle now"** — the drift sidecar is per-clone, so a critical/expired row
here is YOUR OWN flag (the prune escape-hatch case):
```
Pre-flight found:
- {N} stale doc(s): {tier breakdown}
- {M} convention(s) over the promotion threshold
- doctor scan due ({cadence})
Options:
1. Handle now — run /espalier-prune + review conventions, then resume
2. Proceed — continue the pipeline with current docs
3. Abort
```
**Only non-critical signals** → do NOT prompt here (this wait was the
cost): print ONE line (`pre-flight: {N} stale, {M} promotion candidate(s),
doctor {due|not due} — deferred to the approval gate`), append the same
summary to `espalier/.drift-report.md` with a
`deferred-to-approval-gate ({ts})` marker line, and continue to Stage 0
Auto-Link Discovery. The Requirements Approval Gate carries the
maintenance question (its step 3b) — still before any code is written. The
weekly gardener rota remains the default owner of non-critical maintenance
either way; an interrupted run's signals re-surface at the next
invocation's pre-flight (the sidecar is never cleared by deferral).
**Unattended runs (never prompt here):** when `interactivity_mode` (in
`drift-helpers.sh`) returns `unattended`, do NOT issue the pre-flight
question. Write the three-signal summary to `espalier/.drift-report.md`,
print ONE line, and continue to THIS LANE's own **Stage 0 Auto-Link
Discovery** below (not Stage 1 — that is the full pipeline's next stage, not
the fix lane's). Never prune, never promote, never run a doctor scan
unattended.
For a `pattern_key` at the promotion threshold (>= 3 deduped `diverges`
observations per `conv_fold`), handle it per the `espalier` skill's Convention
Promotion section — the same four options (promote / reject / exception /
wait), the same branch lane (deciding on your feature branch is fine, as its
own isolated `docs:` commit — CODEOWNERS routes the rules PR to the owner at
merge), and the same fetch race guard run before the prompt.
## Stage 0: Auto-Link Discovery (NEW)
Stage 0 turns the bug input into a set of blamed commit SHAs (`SHAS` array),
then resolves each to the change that introduced it.
**Simple mode runs this stage READ-ONLY** (`stages/simple.md` → Fix lane
Stage 0): blame, the lookup chain, and the linked-context read as written,
`caused_by:` into the simple folder's `requirements.md` only — but no
`_cache_append` (the `espalier/.commit-index.tsv` self-heal in Layers 1/2 is
skipped; the cache is read, never written) and nothing written into the
causing change's folder, here or at Stage 7.
### 0.1 Parse user input for a bug anchor
Priority order (try each until one succeeds):
| Priority | Source | Example | Extracts |
|----------|--------|---------|----------|
| 1 | `--caused-by <slug>` flag | `/espalier-fix --caused-by feat/bulk-export NPE...` | slug directly, skip blame |
| 2 | `file:line` pattern in bug text | `src/payment.ts:42` | file, line |
| 3 | Stack trace block | `at handler (src/auth.ts:88:14)` | list of file:line frames |
| 4 | Bare file path | `bug in src/payment.ts` | file only |
| 5 | Symbol name | `bug in processPayment function` | symbol → grep matches → file:line |
| 6 | No anchor at all | "checkout is broken" | prompt user |
### 0.1a Resolve anchors to blamed SHAs (`SHAS` array)
The `SHAS` array (index 0 = primary, consumed by 0.2) is built as follows. If
`--caused-by` was given, skip blame entirely: `SHAS=()` and use the flag slug.
```bash
SHAS=() # blamed commit SHAs, primary first
_blame_line() { # file, line -> append the commit that last touched that line
local file="$1" line="$2"
[ -f "$file" ] || return 0
local sha
sha=$(git blame -L "${line},${line}" --porcelain -- "$file" 2>/dev/null | awk 'NR==1{print $1}')
# skip an uncommitted line (all-zero SHA) — nothing to link
case "$sha" in ""|0000000*) return 0 ;; esac
SHAS+=("$sha")
}
# Priority 2 — file:line
_blame_line "$FILE" "$LINE"
# Priority 3 — stack trace: blame each frame in order (primary = top frame)
# FRAMES is an array of "file:line" parsed from the trace block.
for frame in "${FRAMES[@]}"; do
_blame_line "${frame%%:*}" "${frame##*:}"
done
# Priority 4 — bare file (no line): blame the file's most recent commit
if [ -n "$FILE" ] && [ -z "$LINE" ]; then
sha=$(git log -1 --format=%H -- "$FILE" 2>/dev/null)
[ -n "$sha" ] && SHAS+=("$sha")
fi
# Priority 5 — symbol: grep the repo; blame EACH match (not just the first — a
# first-match-only guess silently mislinks). Cap at the Stage-0 fan-out of 5.
if [ -n "$SYMBOL" ]; then
while IFS=: read -r mfile mline _; do
[ -n "$mfile" ] && _blame_line "$mfile" "$mline"
[ "${#SHAS[@]}" -ge 5 ] && break
done < <(grep -rnI --exclude-dir=.git -e "$SYMBOL" . 2>/dev/null | head -5)
fi
```
De-duplicate `SHAS` preserving order (primary wins) before 0.2 consumes it. If
`SHAS` is empty after all anchors AND no `--caused-by`, this is the priority-6
"no anchor" case — prompt the user (or proceed with an empty `caused_by` list on
a headless run; a fix with no causal link is valid, just unlinked).
### 0.2 Tiered reverse-lookup chain
Per-SHA lookup runs through Layers 0-3. `espalier/.merge-hook-decision`
(written at `/espalier-init` time) governs Layer 3.
> Prerequisite: source helpers once before this block runs (also done by Flag Handling section):
> `. espalier/hooks/lookup-helpers.sh`
Resolve `ask-later` UPFRONT so the inner loop never hits a prompt. The bash
below only DETECTS the decision. If it reads `ask-later` (or the file
is absent) AND `interactivity_mode` (from `drift-helpers.sh`) is NOT
`unattended`, YOU (the orchestrator) ask via `AskUserQuestion` — the same
choices the init-time question offers (options: `installed` /
`fuzzy-allowed` / `skip-only` / `not-needed`; keeping `ask-later` stays
available via Other) — then write the answer to
`espalier/.merge-hook-decision` yourself and re-run this resolution block. On
an unattended run, keep the `ask-later` behavior (dispatch as `skip-only`, so
entries link as `unknown_squash`) and log one line that the decision was
deferred. (The legacy stderr prompt helper stays in `lookup-helpers.sh` for
unattended/non-Claude use — it is no longer called from this flow.)
```bash
DECISION=$(cat espalier/.merge-hook-decision 2>/dev/null || echo "ask-later")
# ask-later on an unattended run: dispatch conservatively as skip-only.
# Interactive runs never reach here with ask-later — the orchestrator resolved
# it via AskUserQuestion and rewrote the file before re-running this block.
if [ "$DECISION" = "ask-later" ] || [ -z "$DECISION" ]; then
echo "merge decision still ask-later (unattended) — linking conservatively; entries mark unknown_squash" >&2
DECISION="skip-only"
fi
# Build entries in stack-trace order. Index 0 = primary, rest = call_path. Cap=5.
TOTAL_FRAMES=${#SHAS[@]}
CAP=5
if [ "$TOTAL_FRAMES" -gt "$CAP" ]; then
SHAS=("${SHAS[@]:0:$CAP}")
OVERFLOW_NOTE="$((TOTAL_FRAMES - CAP)) additional frames not linked (cap reached)"
fi
for IDX in "${!SHAS[@]}"; do
SHA="${SHAS[$IDX]}"
ROLE=$([ "$IDX" = "0" ] && echo "primary" || echo "call_path")
# Layer 0: cache hit (fast path)
if [ "$NO_INDEX" != "yes" ] && [ -f "espalier/.commit-index.tsv" ]; then
CACHE_HIT=$(grep "^$SHA " espalier/.commit-index.tsv 2>/dev/null | head -1)
if [ -n "$CACHE_HIT" ]; then
SLUG=$(echo "$CACHE_HIT" | cut -f2)
KIND=$(echo "$CACHE_HIT" | cut -f3)
LOOKUP=$([ "$KIND" = "squashed_to" ] && echo "squash_hook" || echo "exact")
_push_entry "$SLUG" "$SHA" "$ROLE" "$LOOKUP"
continue
fi
fi
# Layer 1: exact SHA match (scan + self-heal cache)
SCAN_START=$(date +%s%N 2>/dev/null || date +%s)
SLUG=$(grep -lr "$SHA" espalier/changes/*/*/pipeline-state.md 2>/dev/null \
| head -1 | sed 's|espalier/changes/||; s|/pipeline-state.md||')
_maybe_warn_slow_scan "$SCAN_START"
if [ -n "$SLUG" ]; then
_push_entry "$SLUG" "$SHA" "$ROLE" "exact"
_cache_append "$SHA" "$SLUG" "original"
continue
fi
# Layer 2: hook-recorded squash mapping (self-heal cache)
SCAN_START=$(date +%s%N 2>/dev/null || date +%s)
SLUG=$(grep -lr "squashed_to: $SHA" espalier/changes/*/*/pipeline-state.md 2>/dev/null \
| head -1 | sed 's|espalier/changes/||; s|/pipeline-state.md||')
_maybe_warn_slow_scan "$SCAN_START"
if [ -n "$SLUG" ]; then
_push_entry "$SLUG" "$SHA" "$ROLE" "squash_hook"
_cache_append "$SHA" "$SLUG" "squashed_to"
continue
fi
# Layer 3: dispatch based on cached merge-hook decision
case "$DECISION" in
installed)
SLUG=$(_fuzzy_file_overlap_match "$SHA")
[ -n "$SLUG" ] && _push_entry "$SLUG" "$SHA" "$ROLE" "fuzzy_after_hook_miss" \
|| _push_entry "unknown_squash" "$SHA" "$ROLE" "unknown"
;;
fuzzy-allowed)
SLUG=$(_fuzzy_file_overlap_match "$SHA")
[ -n "$SLUG" ] && _push_entry "$SLUG" "$SHA" "$ROLE" "fuzzy" \
|| _push_entry "unknown_squash" "$SHA" "$ROLE" "unknown"
;;
skip-only|never-ask)
_push_entry "unknown_squash" "$SHA" "$ROLE" "skipped"
;;
not-needed)
_push_entry "unknown" "$SHA" "$ROLE" "unknown"
;;
*)
# Defensive: should not reach here — ask-later resolved upfront.
_push_entry "unknown" "$SHA" "$ROLE" "unknown"
;;
esac
done
_dedupe_entries_preserve_primary
[ -n "$OVERFLOW_NOTE" ] && _push_note_entry "$OVERFLOW_NOTE"
```
Helpers (`_push_entry`, `_push_note_entry`, `_dedupe_entries_preserve_primary`,
`_fuzzy_file_overlap_match`, `_cache_append`, `_maybe_warn_slow_scan`) live in
`espalier/hooks/lookup-helpers.sh` and are sourced at Stage 0 entry.
### 0.3 Per-entry frontmatter shape
```yaml
---
type: fix
caused_by:
- slug: feat/auth
sha: abc1234
role: primary
lookup: exact
- slug: feat/log
sha: def5678
role: call_path
lookup: squash_hook
- note: "2 additional frames not linked (cap reached)"
---
```
| Field | Values |
|-------|--------|
| `slug` | `{type}/{slug}` or `unknown_squash` or `unknown` |
| `sha` | git SHA blame returned |
| `role` | `primary` (top stack frame) \| `call_path` |
| `lookup` | `exact` \| `squash_hook` \| `fuzzy` \| `fuzzy_after_hook_miss` \| `unknown` \| `skipped` |
### 0.4 Load linked context for Stage 1
For each `caused_by` entry where slug ∉ {unknown, unknown_squash}:
- Read `espalier/changes/{slug}/requirements.md` (original intent)
- Read `espalier/changes/{slug}/coding-report.md` (what shipped)
- Read `espalier/changes/{slug}/review-record.md` (predicted concerns — especially dismissed P2/P3)
If combined linked context > 8K tokens, summarize each linked change to acceptance-criteria + open P2/P3 findings only. Full files available via Read on demand during Stage 3.
### 0.5 Record Stage 0 outcome
Append to pipeline-state.md Stage History:
```markdown
| 0 | PASSED | {ISO timestamp} | Auto-linked to {N} change(s): {list}. Anchor: {file:line|stack|flag|symbol|skipped}{; cap reached if applicable} |
```
## Stage 1: Bug Requirements (slimmer than feat reqs)
Write `espalier/changes/fix/{slug}/requirements.md`:
```yaml
---
type: fix
caused_by: # populated by Stage 0
- slug: ...
sha: ...
role: ...
lookup: ...
---
# Bug: {one-line summary}
## Symptom
{what user sees}
## Reproduction
{steps to reproduce}
## Root Cause
{the confirmed cause — file:line and why. Populated by the Stage 1 grill
(diagnosis mode); use "unconfirmed — <hypothesis>" only if grilling could not
verify it against the code}
## Files likely touched
- {bulleted paths — best pre-code estimate}
## Layers involved
- {list of layers the fix will touch}
## Expected behaviour
{what should happen instead}
## Acceptance criteria
- [ ] Bug no longer reproduces with steps above
- [ ] Regression test added in tests/{matching path}
- [ ] Original feature (per caused_by) still works
## Out of scope
{anything reporter asked for that isn't this specific bug}
```
Fill `## Files likely touched` and `## Layers involved` from the diagnosis —
they are the Stage 1 predictive escalation gate's inputs (Files predicted /
Layers predicted), so a best pre-code estimate is mandatory, not optional.
**Grill the diagnosis.** Unless the invocation passed `--no-grill`
(`GRILL_DISABLED=yes`), invoke the `espalier-grill` skill in `diagnosis` mode once
the draft above is written. Grill interrogates the root cause and reproduction
(adaptive depth — a well-anchored bug with a clean repro is skipped), verifies the
claimed cause against the code, and writes its findings into the `## Root Cause`
and `## Reproduction` sections. Record its verdict (`GRILLED (light)` /
`GRILLED (full)` / `SKIPPED: <reason>`) for pipeline-state.md.
**Escalation Gate (Stage 1):** see "Escalation Gates" section below.
## Requirements Approval Gate (BLOCKING — before Stage 3 Coding)
MANDATORY. After Stage 1 writes `requirements.md` and the diagnosis grill
resolves the root cause, STOP and get explicit user sign-off — never chain
straight into Stage 3 coding.
**Order:** run the Stage 1 Escalation Gate FIRST (it may migrate the fix to the
feat lane). Only if the fix stays in-lane does this approval gate fire.
1. Present a concise summary: the one-line bug, confirmed root cause (file:line),
reproduction, and acceptance criteria.
2. Ask with `AskUserQuestion`:
```
Bug diagnosed and requirements written. Nothing has been coded yet.
Approve to start Stage 3 (Coding)?
Options:
1. Approve — proceed to the fix.
2. Edit — tell me what to change; I revise requirements.md and re-ask.
3. Abort — stop here; leave requirements.md as a draft (Status: ABORTED).
```
3. In the SAME `AskUserQuestion` call, add a second question collecting the
Stage 7 push authorization (mirror of the full lane's gate): pre-authorize
`{current branch} → {default remote}`, specify another target, or "Ask me
again at Stage 7". Record it as `- Push-Target: {target | ASK}` in
pipeline-state.md. Stage 7 then pushes a pre-authorized target without
re-prompting — every programmatic gate, the pre-push hook, and the
certificate check still apply; `ASK` or a missing line prompts at Stage 7
as before.
3b. If the pre-flight recorded a `deferred-to-approval-gate` summary, add a
THIRD question to the same call (mirror of the full lane's step 3b):
Handle after this change (default) / Pause & handle now (run
/espalier-prune + convention decisions, same mechanics as the Stage 0
prompt, then continue) / Ignore this run.
3d. In the SAME call — when it still has a slot (four questions per call;
with 3b present and no slot left, ask this one right after) — collect
the session-boundary preference, first option default (mirror of the
full lane's step 3d): `Continue here at both` / `Stop after approval`
/ `Stop after the Stage 4 PASS` / `Stop at both`, recorded as
`- Session-Boundary: none | after-2 | after-4 | both`. Everything the
diagnosis grill read into this context stays resident on "continue"; a
fresh session starts from requirements.md and the pack (the v0.25
`Continue in a fresh session` offer, chosen once, here). Skip the
question on an unattended run (`interactivity_mode`).
4. Advance to Stage 3 ONLY on **Approve**. On **Edit**, revise and re-ask. On
**Abort**, write Status: ABORTED and stop.
5. **Stage boundary (read, never asked).** After **Approve** — the
approval row, `- Push-Target:`, `- Session-Boundary:`, and the context
pack on disk — read the preference: `after-2` or `both` → write
`- Current Stage: 3`, print `run /clear, then /espalier-fix with the
same bug text: the slug collision (step 11) offers Resume / extend this
fix at Stage 3` (bare `/espalier-fix` does not resume), and stop. Any
other value or a missing line → continue here.
**Non-interactive exception:** auto-approve ONLY when EXPLICITLY unattended —
`interactivity_mode` (in `drift-helpers.sh`) returns `unattended` (`CI` /
`ESPALIER_UNATTENDED` / `ESPALIER_LOOP` / `ESPALIER_HEADLESS` set). Do NOT use a
bash TTY test: stdin has no TTY inside Claude Code even with the user present, so
a TTY check would auto-approve every interactive fix — defeating the gate. If you
can call `AskUserQuestion`, you ARE interactive and MUST prompt. Only a genuinely
headless run auto-approves (record it in the Stage History).
## Stage 3: Coding
**Context pack (assembled in the SAME turn that presents this lane's
Requirements Approval Gate — paths/facts only, approval-independent; on an
Edit that changes the layer set, re-derive before re-asking; if it is
missing at Stage 3 entry — a resumed old change — write it before the
first coder spawn):** write
`espalier/changes/fix/{slug}/context-pack.md` — the fix-lane version is
small: the requirement path, the layers involved and their spec paths (both
already in requirements.md's `## Layers involved` / `## Files likely
touched`), the four rules files, 1-2 reference files per touched layer, the
discovered build/lint/test commands behind a `- Verify:` line
(`. espalier/hooks/drift-helpers.sh && exit_gate espalier/changes/fix/{slug} {test files}`
— one call, the gate's own commands), and the two helper-filled lines —
`- Grep-only:` (`grep_only_files`) and `- Scoped docs:` (`scoped_docs` on
the files likely touched; `none` when empty). Paths and facts only, never
conclusions — every Stage 3-6 spawn below is pointed at it so no sub-agent
re-derives the same discovery; agents verify against current code (see
`espalier/skills/espalier/stages/3-coding.md` → "Stage 3 Entry: Context
Pack" for the format). Before the
first coder spawn print `req_shape_check "espalier/changes/fix/{slug}"`
(information only — headings outside the contract set).
**Baseline (first entry only):** before spawning the coder, record
`Base-Ref: $(git rev-parse HEAD)` as a line in this fix's pipeline-state.md. Never
overwrite it on a coder re-spawn — it anchors the Stage 4/6 review fingerprint,
the push gate, AND the Stage 5 regression-test verification against pre-fix code.
Spawn sub-agent. Prompt:
```
You are the harness-coder.
Your instructions are espalier/agents/harness-coder.md (auto-loaded as your
system prompt on Claude Code; read it only if it is not already in your
context).
CONTEXT PACK: espalier/changes/fix/{slug}/context-pack.md — read it first;
paths and facts only, verify against current code.
{On a continuation after a handoff add:}
CONTINUATION: espalier/changes/fix/{slug}/coding-log/NN-handoff-{n}.md —
read its ## Handoff first; its Facts are verified (cite them, do not
re-derive), its Remaining is your task list.
{On a re-spawn after a blocked report add, with the CONTINUATION line
naming coding-log/NN-blocked-{n}.md:}
RESOLUTION: {the human's decision — or the unattended default — on the
criterion in the continuation's ## Blocked block, one line}
REQUIREMENT: {paste requirement summary from Stage 1}
CAUSED BY: {caused_by list — read those changes' requirements + coding-report + review-record}
TASK: Fix the bug described above. Stay within the file(s) identified.
TESTS: alongside the fix, write NOW (per espalier/skills/espalier-testing/SKILL.md):
1. A regression test that reproduces the original bug (must FAIL on the
pre-fix code; PASS on the current code — the orchestrator verifies the
FAIL half mechanically against Base-Ref at the exit gate).
2. A test from the original feature's spec (proves the causing feature
still works — read its requirements.md acceptance criteria).
3. For every NEW external-call path the fix introduces, a failure-mode
test per espalier/rules/production-standards.md.
4. The abuse test (tamper → rejected → store unchanged) for every
client-supplied sensitive value you classify under Security-Aware
Coding — the Stage 4 auditor's contract may name more; a contract
phase then writes only the gaps.
List the test files in their own "Test files" subsection of the
coding report. If a meaningful test requires touching files OUTSIDE the
fix's scope (>2 additional files or crossing a layer boundary), append
the Test Scope Signal block per harness-coder.md — do NOT silently
expand scope.
COMMITS: commit each bounded unit at a clean point per your Commit
Discipline — the fix and its regression test together, a preparing
refactor first as its own commit; message per
espalier/rules/development-process.md → Commit Conventions, body cites
fix/{slug}; stage by path, never espalier/. List them under "- Commits:".
When done, write your coding report to:
espalier/changes/fix/{slug}/coding-report.md
```
(With `test-mode: serial`, drop the TESTS lines — tests are written after
the final panel PASS instead; see Stage 5/6. The mode read is the
`test-mode` block of `espalier/skills/espalier/stages/3-coding.md` —
word-key grep with the `speculative-tests` legacy mapping.)
**Stage 3 exit gate (PROGRAMMATIC — one protocol, every coder return):**
after the coder returns (first pass and every re-spawn), in this order —
sentinel first, so a handoff report is archived before anything appends
to it:
0. **handoff sentinel:**
`grep -q '^- HANDOFF: true' espalier/changes/fix/{slug}/coding-report.md`
(mirrors the `TEST_SCOPE_INFLATION` detector below). Present → the coder
handed off at a clean point: `. espalier/hooks/drift-helpers.sh &&
report_archive "espalier/changes/fix/{slug}" "handoff-{n}"` moves the
report to `coding-log/`, append `| 3 | HANDOFF {n} | {ts} | {remaining
item count}; next: {file} |`, run step 1 (the gate — green or red), SKIP
steps 2-4 (no report to verify), and re-spawn a fresh coder with the
SAME prompt plus the `CONTINUATION:` line naming
`coding-log/NN-handoff-{n}.md` (and the failing log when the gate was
red). The panel is spawned only on a report without the sentinel;
0b. **blocked sentinel:**
`grep -q '^- BLOCKED-ON-REQUIREMENT:' espalier/changes/fix/{slug}/coding-report.md`.
Present → the code contradicts an acceptance criterion and no
conservative option satisfies it (harness-coder.md → Territory vs
Contract). Same protocol as step 0 with the label `blocked-{n}`, the
row `| 3 | BLOCKED {n} | {ts} | {criterion} |`, and — BEFORE the
continuation spawn — the criterion resolved by the human, never by
you or the coder: interactive → ONE `AskUserQuestion` carrying the
report's `## Blocked` block (Criterion, Contradiction, Options), the
choices `1. Take the conservative option (default)` (recorded with
`. espalier/hooks/drift-helpers.sh && open_question_append
"espalier/changes/fix/{slug}" "{criterion} → {option} (ratified at
Stage 3 BLOCKED {n})"`; the criterion stands) / `2. Change the
criterion — tell me the new text` (edit the line; this answer is the
approval) / `3. Abort`; unattended → option 1 with `(default —
revisit)`, no question. The continuation prompt carries
`CONTINUATION:` naming `coding-log/NN-blocked-{n}.md` and a
`RESOLUTION:` line. The panel never sees a blocked report;
1. **gate:** `exit_gate "espalier/changes/fix/{slug}"` (drift-helpers.sh —
the `run_build` / `run_lint` / `run_tests` bodies from the installed
`pre-push-gate.sh`: build + lint as two concurrent jobs, then — folded —
the discovered test command scoped to the coding report's listed test
files where the runner supports path filtering, full suite where it
does not; the old Stage 5 "tests pass" gate, moved earlier so the panel
never reviews unexecuted tests). Exit `0` green; `1` red — archive the
report (`report_archive … "exit-gate-fix"`) and return to the coder with
the failing job's log; `2` / `3` (a customised gate missing a `run_*`
function; the greenfield placeholder) mean "helper unavailable" — run
the gate by hand as before: build + lint as two concurrent background
jobs in ONE bash call (per-pid `wait`s, per-job temp-file output) unless
the discovered commands plainly depend on each other, then the scoped
test run — never red;
2. **folded:** the scoped test run is part of step 1;
3. **folded:** run the regression verification below — it RE-RUNS on every
coder return (a fix round can rewrite the regression test) and
re-appends its `- REGRESSION_VERIFIED:` line; readers take the LAST
line. The panel sees the result BEFORE round 1;
4. **scope detectors:** the reactive escalation gate counts **non-test
files only** toward its `>5 files / >2 layers` thresholds (see the
Stage 3 Gate table under Escalation Gates for why), and
`grep -q '^- TEST_SCOPE_INFLATION: true' espalier/changes/fix/{slug}/coding-report.md`
fires the late-escalation prompt (the signal kept its own detector; it
just moved here with the work).
All must exit 0 / not fire before the panel spawns. The coder's
self-reported status is a claim, not the gate. A build/lint/test failure
returns to the coder without a panel round and without counting a P0 round.
`report_archive` runs before EVERY coder spawn after the first (labels:
`stage3`, `handoff-{n}`, `blocked-{n}`, `round{n}-fix`, `exit-gate-fix`,
`contract-phase`), so `coding-report.md` is always the CURRENT spawn's report
and the `REGRESSION_VERIFIED` lines appended below land on it.
**Escalation Gate (Stage 3):** see "Escalation Gates" section below.
## Stage 4: Code Review (fixpoint loop — a two-agent panel, re-review after EVERY fix)
Run Stage 4 as a loop, not a single pass. Every round runs TWO fresh agents on the
CURRENT diff, spawned concurrently — `harness-reviewer` (correctness / conventions /
production readiness, → review-record.md) and `harness-security` (trust boundary —
never trust frontend data, → security-record.md). BOTH records are OVERWRITTEN each
round and end with a `VERDICT:` sentinel line. Before every panel spawn, run the
Stage 3 programmatic gate — `exit_gate "espalier/changes/fix/{slug}"` (exit 2 / 3
= run it by hand as before, never red) — the coder's self-report is a claim,
not the gate; a failure goes back to the coder without spawning the panel and
without counting a P0 round.
1. **Baseline BOTH records** (`espalier/changes/fix/{slug}/review-record.md` and
`.../security-record.md` — exists? size/mtime), then spawn the FRESH panel on
the CURRENT diff in ONE message — TWO agents, every round. Folded: the
diff already contains the tests; the reviewer's prompt adds "REVIEW THE
TESTS TOO, in the same verdict: the `- REGRESSION_VERIFIED:` last line
in coding-report.md (`false` = P0 — the test does not capture the bug);
assertions meaningful, not tautological; original-feature coverage;
failure-mode coverage (missing = P1). Abuse-test coverage waits for the
contract delta review." The security prompt adds: "Test files are in
scope for secrets / live-endpoint / fixture-data leakage only." Pass
each agent the `CONTEXT PACK:` line
(`espalier/changes/fix/{slug}/context-pack.md` — read first; paths and
facts only, verify against current code), the coding-log line ("earlier
spawns' reports are in espalier/changes/fix/{slug}/coding-log/ — open one
only when the current report cites it or a finding needs the history"),
`ROUND: {n}`, AND the
`CAUSAL CONTEXT` line (the `caused_by` slugs + "verify the fix does not
regress these features' acceptance criteria — read their requirements.md")
so the regression check reaches the reviewer at Stage 4, not only at Stage 6.
On a re-review round, also hand each agent the "changed since last review" set
(the fix's files from the latest coding-report.md) with `read
espalier/agents/modes/re-review.md first (your section)` — the panel
re-reviews in
DELTA SCOPE (fix files + prior findings + direct dependents as required
reads; a floor, not a ceiling — expand on any suspicion; security runs
delta mode when its own prior round was clean — the mode file holds each
agent's "Re-review Rounds" section). Both agents still return fresh current-round
sentinels and still own the whole-change verdict: every line of the final
diff got a fresh review in the round it last changed, build/lint re-runs
before every round, and the fingerprint blocks unreviewed edits at push.
2. **Completion check — BOTH files.** Each record must exist, differ from its
baseline, and end with a `VERDICT:` sentinel carrying `round={n}`. A missing,
unchanged, or sentinel-less record means that agent did NOT complete —
re-spawn that agent (once; a second failure → escalate). Never treat a
missing/stale record as a pass.
3. **Gate read (deterministic).** From EACH record:
`V=$(grep '^VERDICT:' <record> | tail -1)`. Parse the verdict WORD and the counts.
- `ESCALATION_REQUIRED` (either agent, either lane, any stage) → do NOT
advance and do NOT re-spawn: snapshot the sentinel, then run the escalation
protocol (fix lane: the late-escalation prompt; full lane: escalate to the
human with the agent's Escalation Reason block). An `ESCALATION_REQUIRED`
with `p0=0` is still an escalation.
- Verdict word `FAIL`, or `p0=` > 0, or `p1=` > 0 → re-spawn `harness-coder`
with the combined findings and loop (counter + `max-code-rounds` cap
unchanged; the re-spawn prompt's first line is `FIX ROUND {n}: read
espalier/agents/modes/fix-round.md first, then for every P0/P1 below
run the Class Sweep — fix every sibling of the defect class, not the
flagged line; one `### Class Sweep` block per finding in
coding-report.md.`): snapshot
both sentinels into pipeline-state.md Stage History
— appending in the same notes cell one bracketed finding line per
FAILING agent (`[{P-sev} {≤80-char summary}]`; this snapshot is the
findings digest's only source — the records are overwritten next
round), archive the current report (`report_archive
"espalier/changes/fix/{slug}" "stage3"` before the first fix round,
`"round{n-1}-fix"` after), re-spawn with the combined findings, then **return to step 1 and re-review
the new diff with the whole panel.** Never advance to Stage 5 on the
coder's fix report alone — a fix is never the last action before the gate;
a clean panel is. Each non-PASS round increments the counter. Check the cap
BEFORE re-spawning: if the counter already equals `max-code-rounds`
(default 3, read from `espalier/.espalier-config` via
`grep '^max-code-rounds:' espalier/.espalier-config | grep -oE '[0-9]+'`;
fall back to 3 if unset), escalate to the human immediately — the coder is
NOT re-spawned and no further panel round runs. Before stopping, set
`- Status: ESCALATED` and add a Stage History row
`| 4 | ESCALATED | {ts} | {reason, round count} |` in pipeline-state.md.
Otherwise re-spawn, increment the counter, and loop. (A security P0/P1
shares this counter.)
- Advance ONLY when EVERY record's last sentinel has verdict word `PASS` or
`PASS_WITH_FIXES` AND `p0=0` AND `p1=0` on the current code.
4. **Both last sentinels PASS/PASS_WITH_FIXES with p0=0 p1=0 on a fresh review
of the current code →** PASS. Snapshot
the sentinels into Stage History, then record the certificate:
`certificate_write "espalier/changes/fix/{slug}"` — `git add -A` (so new
files count), then `Reviewed-Diff: $(git diff <Base-Ref> -- . ':(exclude)espalier/' | git hash-object --stdin)`
in pipeline-state.md, the last existing line overwritten in place
(`<Base-Ref>` = the Stage 3 SHA). The Stage 7 push gate blocks unless this still matches.
Surface the deviations: `deviations_list "espalier/changes/fix/{slug}"`
prints the coding report's `### Deviations` entries (nothing when
none) — print them under the PASS line verbatim and append
`deviations: {n}` to the PASSED row's notes; the human sees every
departure from the approved criteria here, panel-verified, before push.
Then — after the Post-Review drift processing below — the **stage
boundary**: read `- Session-Boundary:` (collected at the approval gate;
no question here). `after-4` or `both` → write `- Current Stage: 5`,
print `run /clear, then /espalier-fix with the same bug text; the slug
collision offers Resume / extend at Stage 5`, and stop. Any other
value, a missing line, or an unattended run → continue.
Special check for fix lane: reviewer MUST verify the fix doesn't regress the
original feature's acceptance criteria (read from `caused_by` change's `requirements.md`).
A bug fix is a prime place to REINTRODUCE a trust-boundary hole — `harness-security`
treats the fix diff as hostile-input surface exactly as it would a feature, and
emits the `## Security-Sensitive Fields` abuse-test contract for Stage 5/6.
### Stage 4 Post-Review: Drift & Convention Index
After Stage 4 PASSES (step 4 above — BOTH sentinels p0=0, certificate written),
parse `review-record.md` for Convention Drift blocks (see `harness-reviewer.md`)
and flag the affected rule files. Run this BEFORE Stage 6 (which overwrites
review-record.md). Do NOT run it on a P0 round.
> Variable in scope: `SLUG` is this fix's slug (no `fix/` prefix).
```bash
. espalier/hooks/drift-helpers.sh && drift_index fix "$SLUG"
```
`drift_index` runs `parse-drift-blocks.py` over the record: each `DRIFT`
block marks its rule file stale and appends `convention_drift: {rule file}`
(+ `(coupled_with: …)`) to pipeline-state.md; a `MALFORMED` block appends
`convention_drift_malformed: {rule file} (reviewer bundled blocks — drift NOT
indexed)` instead. It prints the lines it appended.
On a `MALFORMED` line (Stage 4 has already PASSED when this parse runs) record
it in pipeline-state.md and surface one line to the user; never write a fake P0
into review-record.md (it would contaminate the Stage 6 gate read).
**Convention Observations → the convention index.** The reviewer also emits
lower-bar Convention Observations (see `harness-reviewer.md`) — one per
divergence, with NO aggregation key. The orchestrator assigns the key. For each
Observation in `review-record.md`:
1. Read existing keys: `. espalier/hooks/drift-helpers.sh && conv_fold | cut -f1`
(folds the legacy file AND the per-key files — never parse them yourself).
2. Map the Observation's `description` to an existing `pattern_key`, or mint a
new kebab-case key.
3. Append the row:
```bash
. espalier/hooks/drift-helpers.sh
append_convention "fix/${SLUG}" "$PATTERN_KEY" "$LOCATION"
```
`append_convention` sanitizes every field and de-dupes on
(change_slug, pattern_key, location). Convention state is tracked and
row-append-only — columns `date · change_slug · pattern_key · location · status`.
When a `pattern_key` reaches 3 deduped `diverges` observations (per `conv_fold`)
it is a promotion candidate, surfaced at the next Stage 0 pre-flight.
## Stage 5/6 (folded): the contract phase
Run `espalier/skills/espalier/stages/5-6-contract.md` — read it now — the
"Stage 5/6 (folded): the contract phase" protocol, shared verbatim:
contract detection
(`grep -q '^## Security-Sensitive Fields' espalier/changes/fix/{slug}/security-record.md`
after the final panel PASS, then `contract_extract "espalier/changes/fix/{slug}"`
→ `security-contract.md`, the file the contract spawn and the delta review
read); no contract → both SKIPPED rows
(`| 5 | SKIPPED | {ts} | folded: no contract |`,
`| 6 | SKIPPED | {ts} | folded: reviewed at Stage 4 |`), `Current Stage: 7`,
zero post-panel spawns; non-empty contract → `contract_gaps` (every entry
`covered_by:` a test already in the diff → `| 5 | PASSED | {ts} | folded:
contract covered at Stage 3 |`, no coder spawn; gaps → contract spawn for
the gap entries only → exit-gate re-run) → contract delta review → FAIL routing (test-only fixes loop under
`max-test-rounds`; code-touching fixes route to a FULL Stage 4 panel round
under `max-code-rounds`, cap-before-respawn, no second counter) →
certificate refresh. Fix-lane deltas:
- the contract delta review prompt also carries the `CAUSAL CONTEXT:` line
(the `caused_by` slugs);
- an escalation at the cap here sets `- Status: ESCALATED_LATE` (the fix's
code is already committed at Stage 3 — the late-escalation path), with
the `| 6 | ESCALATED | {ts} | {reason, round count} |` row;
- the `TEST_SCOPE_INFLATION` detector already ran at the Stage 3 exit gate
(its new home) — a `LATE_ESCALATION_GATE:` line means STOP and run the
"Late-Escalation Prompt" (below) via `AskUserQuestion`; the bash only
detects, the prompt is yours.
**`test-mode: serial`:** after the final panel PASS, one test-coder spawn
writes the regression + original-feature + failure-mode tests PLUS the
contracted abuse tests (reading security-record.md's
`## Security-Sensitive Fields` — via security-contract.md when extracted),
writing its report fresh to coding-report.md (the orchestrator archives the
Stage 3 report first — `report_archive … "stage3"` / `"round{n}-fix"`) —
then the serial Stage 6 review below. The signal greps run against
coding-report.md, exactly as pre-v0.22.
### Stage 3 exit gate — regression verification (PROGRAMMATIC — proves the test earns its keep)
**When (folded):** at the Stage 3 exit gate, on EVERY coder return — a fix
round can rewrite the regression test, so the check RE-RUNS each time and
RE-APPENDS its `- REGRESSION_VERIFIED:` line; readers take the LAST line
(`grep '^- REGRESSION_VERIFIED:' coding-report.md | tail -1`, the sentinel
pattern). Never in the same message as a coder spawn (a verification
racing a rewrite certifies the wrong tree). The panel therefore sees the
result BEFORE its first verdict.
**Skip condition:** each verified run also appends
`- REGRESSION_VERIFIED_SCOPE: {hash}` (the helper below); when the current
scope hash equals the last recorded one the helper skips both runs and
re-appends the previous result marked `(cached)` — see **Cache** below.
(With `test-mode: serial`: run it once, after the last test-writing spawn,
before Stage 6 — as pre-v0.23.)
A regression test that passes on BOTH the fixed and the pre-fix code proves
nothing — and a test that merely ERRORS at `Base-Ref` (missing deps in a fresh
worktree, unresolvable import, bad invocation) proves nothing either: "could
not run" is not "captured the bug". Verify in two steps, both SCOPED to only
the new regression test file(s):
1. Run the scoped invocation on the FIXED tree. It must pass — this validates
the command itself (runner found, deps resolve, file loads) before any
pre-fix conclusion is drawn.
2. Run the same scoped invocation at `Base-Ref` in a detached worktree. A
genuine assertion failure there → `true`. A harness error there → `skipped`
(the reviewer verifies the assertions by reading), NEVER `true`.
`REG_RUN` is the project's test runner limited to exactly the regression
test file(s) the coder listed — most runners accept file paths directly;
npm-style runners need `--` (e.g. `npx jest <files>`, `pytest <files>`,
`npm test -- <files>`, `go test ./path/to/pkg/`). One call does both steps
and records the result in coding-report.md; the reviewer reads it at the
round-1 panel:
```bash
. espalier/hooks/drift-helpers.sh \
&& regression_verify "espalier/changes/fix/${SLUG}" "$REG_RUN" {the regression test file(s), from coding-report.md}
```
`regression_verify` (drift-helpers.sh):
- **Handoff guard** — a report carrying the sentinel
(`grep -q '^- HANDOFF: true' "$COD"`) is archived and continued by a
fresh coder (Stage 3 exit gate, step 0): nothing is appended to it and
the helper returns after one line saying so.
- **Step 1, the fixed tree** — runs `REG_RUN` from the repo root. A harness
error (`_reg_harness_error`: cannot find module / ENOENT / ImportError /
SyntaxError / failed to collect / no tests found …) → `skipped —
scoped invocation could not run on the fixed tree`; an assertion failure
→ `false — regression test FAILS on the FIXED code (broken test or
unfixed bug) (P0 at Stage 6)`.
- **Step 2, Base-Ref** — a detached worktree at the recorded `Base-Ref`
with the test files copied in and the installed dependency dirs
(`node_modules`, `.venv`, `venv`, `vendor`) linked, the same `REG_RUN`
run there: pass → `false — test PASSES on pre-fix code; it does not
capture the bug (P0 at Stage 6)`; harness error → `skipped — could not
RUN at Base-Ref (harness error, not an assertion failure)`; a genuine
assertion failure → `true (test fails on pre-fix {Base-Ref}, passes on
fix)`. The worktree is removed afterwards.
- **Cache** — the helper appends `- REGRESSION_VERIFIED_SCOPE: {hash}`
(the test files' contents) after every run; when the current hash equals
the last recorded one (this report, else the newest `coding-log/`
report) it skips both runs and re-appends the previous result marked
`(cached)`.
- No `Base-Ref` → `skipped — no Base-Ref recorded`; no test file named →
`skipped — no regression test file named`. It appends the
`- REGRESSION_VERIFIED:` line and the scope line and prints the former.
A `REGRESSION_VERIFIED: false` is a P0 the round-1 panel reviewer must
catch (folded; the Stage 6 reviewer in serial mode) — the
"regression test" does not reproduce the bug (or fails on the fixed code) and
would not catch a recurrence. `skipped` keeps its existing Stage 6 meaning:
the reviewer verifies the assertions capture the bug by reading them. (One
deliberate bias: a bug whose pre-fix symptom IS a load-time error — e.g. the
fix repairs a syntax error — classifies as `skipped`, not `true`; the check
errs toward human eyes, never toward false certification.)
## Stage 6 (serial mode only): Test Review
Folded mode has no separate Stage 6 review — the contract delta review in
the Stage 5/6 section above IS Stage 6, and non-sensitive changes write
the SKIPPED rows there. The block below runs only under
`test-mode: serial`.
Spawn `harness-reviewer`:
```
You are the harness-reviewer reviewing tests for a fix.
Your instructions are espalier/agents/harness-reviewer.md (auto-loaded as
your system prompt on Claude Code; read it only if it is not already in
your context). Read espalier/agents/modes/stage6-abuse-coverage.md first.
CONTEXT PACK: espalier/changes/fix/{slug}/context-pack.md — read it first;
paths and facts only — your verdict comes from the tests you read.
REVIEW: tests added in coding-report.md at espalier/changes/fix/{slug}/.
CAUSAL CONTEXT: this fix is caused by {paste caused_by entries}. Verify the
tests don't regress those original features (read their acceptance criteria).
ROUND: {n} — put round={n} in your VERDICT sentinel line.
{On round ≥ 2 add:} CHANGED SINCE LAST REVIEW: {the test files the Stage 5
fix re-spawn touched, from the latest coding-report.md}. Read
espalier/agents/modes/re-review.md first and re-review in delta scope.
Check:
- Regression test would have failed on pre-fix code. The orchestrator recorded
`- REGRESSION_VERIFIED: {true|false|skipped}` in coding-report.md from a
Base-Ref worktree run. `false` → P0 (the test does not capture the bug).
`skipped` → verify the assertions capture the bug by reading them. Your job is
that the ASSERTIONS are meaningful, not tautological.
- Original feature's acceptance criteria still pass
- No tests are tautological (asserting the fix's masked behaviour instead of intended)
- Security coverage: every field in security-contract.md (fallback:
security-record.md's `## Security-Sensitive Fields` block) has a passing
abuse test (tamper → rejected → store unchanged).
A missing one is a P0 → back to Stage 5.
- Failure-mode coverage: every NEW external-call path has a dependency-failure
test (per espalier/rules/production-standards.md). A missing one is a P1.
If the fix is correct given its current scope BUT the scope itself is wrong
(symptom-mask, wrong layer, architectural concern), emit verdict
ESCALATION_REQUIRED with the required Escalation Reason block.
Write (OVERWRITE) review to: espalier/changes/fix/{slug}/review-record.md
End the file with your VERDICT sentinel line.
```
After sub-agent returns (sentinel first; legacy `**Verdict:**` kept as fallback):
```bash
REV="espalier/changes/fix/${SLUG}/review-record.md"
if grep -qE '^VERDICT: ESCALATION_REQUIRED|^\*\*Verdict:\*\* ESCALATION_REQUIRED' "$REV"; then
echo "LATE_ESCALATION_GATE: stage=6 (reviewer flagged ESCALATION_REQUIRED)"
fi
```
Same contract as Stage 5: a `LATE_ESCALATION_GATE:` line means STOP and run the
"Stage 5/6 Late-Escalation Prompt" (below) via `AskUserQuestion`, handing it the
reviewer's Escalation Reason block. Detection is bash; the prompt is yours.
**Fixpoint + certificate.** Stage 6 is a loop like Stage 4: freshness-check
review-record.md against its baseline each round, snapshot each round's
sentinel into Stage History.
**Gate read (deterministic — SINGLE record: one reviewer runs here).** From
review-record.md:
`V=$(grep '^VERDICT:' <record> | tail -1)`. Parse the verdict WORD and the counts.
- `ESCALATION_REQUIRED` → do NOT advance
and do NOT re-spawn: snapshot the sentinel, then run the escalation protocol
(the late-escalation prompt). An `ESCALATION_REQUIRED` with `p0=0` is
still an escalation.
- Verdict word `FAIL`, or `p0=` > 0, or `p1=` > 0 → send the tests back to
Stage 5 (re-spawn `harness-coder`) with the combined findings and loop
(counter + `max-test-rounds` cap unchanged), then **re-review** — never exit
on the fix report alone.
- Advance ONLY when the record's last sentinel has verdict word `PASS` or
`PASS_WITH_FIXES` AND `p0=0` AND `p1=0` on the current code.
Check the cap BEFORE re-spawning: if the counter already equals
`max-test-rounds` (default 3), escalate to the human immediately — the coder is
NOT re-spawned and no further panel round runs. Before stopping, set
`- Status: ESCALATED_LATE` (the fix's code is already committed at Stage 3, so
a Stage 6 escalation is the late-escalation path) and add a Stage History row
`| 6 | ESCALATED | {ts} | {reason, round count} |` in pipeline-state.md.
Otherwise re-spawn, increment the counter, and loop. On a clean PASS
(per the gate read above), refresh `Reviewed-Diff` in pipeline-state.md (same
`git add -A` + fingerprint command as Stage 4) so it now covers the added
tests; the push gate compares against this.
## Stage 7: Push (with back-link)
**Simple mode: Stage 7 is REPLACED by the Final Gate of
`espalier/skills/espalier/stages/simple.md`** — a whole-tree `exit_gate`,
`simple_brief`, one Approve / Request Changes / Abort question; nothing
below (sweep, `record_commits`, `backlink_all`, `espalier-pr.sh`) runs, and
a partial fix is stated in the brief rather than filed. Otherwise:
### 7.0 The split — code branch, espalier branch
A fix ships as two pull requests exactly as a feat does; Stages 3–7 are shared.
**Outside mode (v0.30 — `outside-root:` in `espalier/.espalier-config`).** The
procedure below is run UNCHANGED; `espalier-pr.sh` reads the key and changes
what the calls do: `project` / `project-sweep` / `sync` / `close` commit the
named paths into the outside root's local git repo (via
`espalier/hooks/espalier-outside.sh commit`) instead of projecting an espalier
branch; `push` pushes the code branch only; `open` opens the code PR only and
records the espalier side in `## Pull Requests` as
`| espalier | local | — | local: <root> @ <sha> |`; `ci-scan` prints `n/a`.
There is no espalier PR to merge and nothing to retire at Completion — the
project tree never held the records. Say so in the fix summary: ONE PR
link, and the outside root path with its commit.
Do NOT stage `espalier/conventions/` or any other `espalier/` path into a code
commit — the projection picks up everything under `espalier/`, and `git add`
honours `.gitignore` so the per-clone sidecars stay out. (The legacy
`espalier/.conventions.tsv` is read-only to this plugin version — never
written, nothing to stage.)
Commit code the coder left uncommitted under the message its report carries;
the coder's commits are pushed as made, never squashed or rebased. The full
procedure — including the two invariants that keep the checkout on the code
branch and push both refs safely past the gate — is the espalier skill's
`stages/7-10-delivery.md` → "Stage 7: The Split". Four steps, in this order —
each one's output is the next one's input:
1. **Sweep.** Spawn `harness-reviewer` with `WIKI SWEEP:` on the prompt line
(`espalier/agents/modes/wiki-sweep.md`) over this fix's diff, `espalier/wiki/`
and `espalier/rules/`. It edits the files it patches, records its verdicts
in `doc-patches.md`, and stops. Skip the spawn when the diff touches no
source file. This matters more in this lane than anywhere: the fix lane
stops at Stage 7, so it is the ONLY point at which a fix can refresh a doc
it invalidated.
2. **Record** — 7.1 (own commits) and 7.2 (back-links), BEFORE anything is
projected. A record written after the projection sits in this checkout and
reaches no pull request — and this lane has no later stage to carry it.
3. **Project** — 7.2's back-link projections, then 7.3: once for the records
and once per class the sweep patched, so each lands as its own revertable
commit. Each call names the paths it may commit; nothing else under
`espalier/` can reach this fix's PR.
4. **Push and open** — 7.3. `open` records the PR table and projects it too,
then ends with a CI scan of the espalier PR — its diff is `espalier/**`
only, which either misses path-filtered workflows (a deadlock when their
checks are required) or runs the full suite against a diff with no code. It
reports and never edits; see the full-lane procedure.
> Variables in scope for all Stage 7 snippets: `SLUG` (this fix's slug, no
> `fix/` prefix) and `ESP_BRANCH="fix/${SLUG}-espalier"` — set it before 7.1.
> Step 1 is an agent spawn and cannot share a bash call; 7.1, 7.2 and 7.3 can
> share one invocation after it returns, so Stage 7 costs one spawn plus one
> round-trip.
### 7.1 Record own commits
Same as `/espalier` Stage 7 — one row per commit of the change
(`git rev-list --reverse Base-Ref..HEAD`, oldest first; HEAD alone when no
Base-Ref was recorded) in own pipeline-state.md `## Commits` table, each
self-healing the reverse-lookup cache (`_cache_append`) — the fix lane's
blame resolves a line to ONE commit, so every commit must map to this fix:
```bash
. espalier/hooks/drift-helpers.sh && record_commits fix "$SLUG"
```
### 7.2 Bidirectional back-link
Every entry in this fix's `caused_by:` YAML list (in `requirements.md`
frontmatter) gets a `## Follow-up Fixes` row in the causing change's
pipeline-state.md (schema: Fix Slug · Role · Lookup · Reason · Date; the
Reason is this fix's `# Bug:` title). Entries whose `slug` is `unknown` /
`unknown_squash` (no destination to write) and `- note:` overflow rows (no
`slug` key) are skipped; a row already present for (own slug, role) is not
written twice — the same slug can legitimately appear as `primary` and
`call_path` in different fixes:
```bash
. espalier/hooks/drift-helpers.sh && backlink_all "$SLUG"
```
`backlink_all` parses the frontmatter itself and calls `_backlink_one` per
entry; it prints one line per row written (`fix/{slug} -> {causing} ({role})`).
**Those rows land in ANOTHER change's records, so they need projecting too.**
Under the PR split each change's `espalier/` paths ride its own branch, and
this fix's projection is scoped to its own folder — a back-link written into
`espalier/changes/{causing}/pipeline-state.md` would sit in the working tree
and reach no pull request at all. It is the fix that caused the row, so the row
rides the FIX's espalier PR:
```bash
. espalier/hooks/drift-helpers.sh
ESP_BRANCH="fix/${SLUG}-espalier"
# What the espalier branch holds. Before its first projection (7.3) it does not
# exist yet, and it will be cut from Base-Ref — so Base-Ref is what it holds.
REF="$ESP_BRANCH"
git rev-parse --verify --quiet "refs/heads/$REF" >/dev/null \
|| REF=$(grep -E '^(- )?Base-Ref:' "espalier/changes/fix/$SLUG/pipeline-state.md" | tail -1 \
| sed 's/.*Base-Ref:[[:space:]]*//' | tr -d '[:space:]')
ROWS=$(backlink_all "$SLUG")
printf '%s\n' "$ROWS"
for CAUSING in $(printf '%s\n' "$ROWS" | awk '{print $3}' | sort -u); do
P="espalier/changes/$CAUSING/pipeline-state.md"
# Only when that file already exists on the espalier branch. A causing change
# still in flight has never been merged, so projecting it here would add its
# ENTIRE state file to this PR as a new file and collide when its own PR
# lands. Its records ride its own espalier PR; re-run the back-link after it
# merges. The ref MUST be non-empty: with an empty one the test reads `:$P`,
# which is the INDEX — certificate_write's `git add -A` has staged everything
# there, so the guard would always pass.
if [ -n "$REF" ] && git cat-file -e "$REF:$P" 2>/dev/null; then
espalier/hooks/espalier-pr.sh fix "$SLUG" project \
"chore(espalier): back-link from $SLUG to $CAUSING" "$P"
else
echo "back-link to $CAUSING recorded locally only — that change is not yet"
echo "merged, so its records ride ITS espalier PR. Re-run after it lands."
fi
done
```
A causing change merged before this fix's Base-Ref is on that ref; one still
in flight is not — which is exactly the line between "ride this PR" and "ride
its own".
### 7.3 Project, push, open
After 7.1 and 7.2 have written everything Stage 7 records:
```bash
espalier/hooks/espalier-pr.sh fix "$SLUG" project "chore(espalier): $SLUG — pipeline records"
# the files the latest `### Wiki Sweep` block marked PATCH, one class per commit:
espalier/hooks/espalier-pr.sh fix "$SLUG" project-sweep wiki
espalier/hooks/espalier-pr.sh fix "$SLUG" project-sweep rules
espalier/hooks/espalier-pr.sh fix "$SLUG" push
espalier/hooks/espalier-pr.sh fix "$SLUG" open
```
`project-sweep` commits exactly the files the sweep marked PATCH, never the
whole directory, and `project` refuses a wiki or rule file that was deleted or
lost more lines than it gained — restore it, record the removal under
`### Proposed Removals`, and re-run. A Stage 6 → Stage 3 rollback that comes
back through here re-runs all four steps; every call is idempotent and new
commits go onto the open PRs.
## Escalation Gates
Four gates: predictive (Stage 1), reactive (Stage 3), test-scope (Stage 3
exit — folded; Stage 5 — serial), reviewer-flagged (any review round).
### Stage 1 Gate (predictive)
After reqs written, parse for:
| Signal | Threshold | Source |
|--------|-----------|--------|
| Files predicted | > 5 | requirements.md "## Files likely touched" (mandatory Stage 1 section) |
| Layers predicted | > 2 | requirements.md "## Layers involved" (mandatory Stage 1 section) |
| Data model change | any | grep for "schema", "migration", "model change" |
| New external dep | any | grep "depends on", "requires new" |
| Reporter says "needs redesign" | exact phrase | grep |
### Stage 3 Gate (reactive)
After coder returns:
| Signal | Threshold | Source |
|--------|-----------|--------|
| Files modified + created | > 5 (**non-test files only** — the fold moves test files into this diff; counting them would trip the gate on former Stage-5 work) | coding-report.md |
| Layers touched | > 2 (non-test files only, same reason) | coding-report.md |
| Coder reported "scope creep" | any | coding-report.md notes |
| Build fail crossing modules | any | coding-report.md build status |
### Test-Scope Gate (Stage 3 exit — folded; Stage 5 — serial)
If coding-report.md contains:
```
### Test Scope Signal
- TEST_SCOPE_INFLATION: true
```
→ fire late-escalation prompt.
### Reviewer-Flagged Gate (any review round — Stage 4 / contract delta / serial Stage 6)
If review-record.md `**Verdict:** ESCALATION_REQUIRED` → fire late-escalation prompt with reviewer's Escalation Reason context.
### Stage 1/3 Prompt (clean migration possible)
```
This bug fix is exceeding fix-lane scope:
Tripped signals:
- {signal 1}: {actual} (threshold {N})
- ...
Options:
1. Escalate to /espalier (recommended) — rename fix/{slug} → feat/{slug}-fix,
preserve caused_by + add escalated_from, reset Current Stage to 1.
2. Continue as fix (override) — document override reason; accept risk.
3. Abort — leave fix/{slug} as-is, Status: ABORTED.
```
Migration mechanics: `mv espalier/changes/fix/{slug} → espalier/changes/feat/{slug}-fix`;
mutate frontmatter (`type: feat`, `escalated_from: fix/{slug}`); reset Current Stage; hand off via `/espalier --resume`.
### Stage 5/6 Late-Escalation Prompt
```
{Stage 5: Test scope inflation | Stage 6: Reviewer flagged ESCALATION_REQUIRED}
Code committed at Stage 3: {commits since Base-Ref — sha — subject, one per line} ({files})
{Stage 5: Test sub-agent needs {N} additional files in {layers}}
{Stage 6: Reviewer Escalation Reason: {analysis}}
Options:
1. Revert the Stage 3 commits + abort fix
→ git revert --no-edit {Base-Ref}..HEAD (newest first, one revert
commit each); Status: ABORTED_LATE
2. Late-escalate to feat lane (PRESERVE commits)
→ mv fix/{slug} → feat/{slug}-fix; tombstone left at old slot;
the Stage 3 commits stay on the branch; reset Current Stage: 1;
resume via /espalier --resume
3. Ship as partial fix + file root-cause feat
→ Continue to Stage 7; Status: PARTIAL_FIX
→ AFTER Stage 7's push completes, auto-create the
espalier/changes/feat/{slug}-root-cause/ skeleton with
filed_from_partial_fix + inherited caused_by, `- Status: FILED`
→ User invokes /espalier feat: ... later (or the full lane's
FILED-skeleton scan adopts it)
```
If the run is unattended (the prompt cannot fire) or the user declines all
three options and hands the problem to a human, stop the lane: before
stopping, set `- Status: ESCALATED_LATE` and add a Stage History row
`| {stage} | ESCALATED | {ts} | late-escalation unresolved — human takeover |`
in pipeline-state.md.
#### Tombstone in old fix slot (option 2 migration only)
```bash
mkdir -p "espalier/changes/fix/${SLUG}"
cat > "espalier/changes/fix/${SLUG}/TOMBSTONE.md" << EOF
# Tombstone: fix/${SLUG} → feat/${NEW_SLUG}
This fix was escalated late (at Stage ${ESCALATED_STAGE}) and migrated to:
**espalier/changes/feat/${NEW_SLUG}/**
All artifacts live there now. This file is a forwarding pointer only.
- Escalated at: $(date -u +%Y-%m-%dT%H:%M:%SZ)
- Reason: ${ESCALATION_REASON}
EOF
```
#### PARTIAL_FIX state (option 3)
Frontmatter:
```yaml
---
type: fix
partial: true
partial_reason: |
{one-line summary of what's masked vs what root cause is}
root_cause_feat: feat/{slug}-root-cause
caused_by: [...]
---
```
pipeline-state.md Status block:
```markdown
## Status
- Current Stage: 7
- Status: PARTIAL_FIX
- Partial Reason: "{summary}"
- Root Cause Feat: feat/{slug}-root-cause
- Root Cause Status: PENDING (last checked: {date})
```
Auto-skeleton at `espalier/changes/feat/{slug}-root-cause/` inherits `caused_by`
and adds `filed_from_partial_fix: fix/{slug}`. Create the skeleton only after
the partial fix's push has gone through — an in-flight skeleton would become
the gate's most-recent active change and block the push. The skeleton's
pipeline-state.md gets `- Status: FILED` (a non-active status: the push gate
ignores it and neither lane resumes it; the full lane's FILED-skeleton scan or
an explicit `/espalier feat: …` adopts it). When that feat completes its own
Stage 7, it writes back to the partial fix's pipeline-state.md
`## Root Cause Addressed By` table (mechanism in `/espalier` Stage 7).
## Completion
**Simple mode** (`- Mode: simple` in the state file): none of this section
runs — the Final Gate of `stages/simple.md` is the completion (Approve
deletes `espalier/.simple/{slug}/`; nothing is projected, pushed, or
opened).
When Stage 7 passes:
- Update own `pipeline-state.md` Status: COMPLETE (or PARTIAL_FIX if option 3).
- **Map-charted fixes** (requirements.md frontmatter has
`charted_from: maps/{map-slug}` — rare in this lane, same contract as the
full lane): if Stage History recorded `ROUND {n} FAIL` rows, write their
bracketed finding lines to
`espalier/maps/{map-slug}/findings/{YYYY-MM-DD}-fix-{kebab}.md` (skip if
it exists), update the map's Spawned Changes row, and name the map dir
in the bookkeeping projection below.
- **Delivery brief + territory notes** — `. espalier/hooks/drift-helpers.sh
&& delivery_brief fix "{slug}"` assembles `delivery-brief.md` from the
records (requirement, ratified decisions, deviations, verdicts, rounds,
commits — copied, never authored); when the coding report carries
`### Deviations` or the Stage History a `BLOCKED` row, append the entries
to `requirements-notes.md` under `## Settled for next time` (one line
each, verbatim). Both ride the bookkeeping projection below.
- Project the espalier bookkeeping onto the espalier PR — never commit it on
the code branch, whose PR is code only (`push` refuses a code branch
carrying `espalier/` paths):
`espalier/hooks/espalier-pr.sh fix {slug} close 'chore(espalier): close {slug}'`
(+ ` espalier/changes/fix/{slug} espalier/conventions espalier/maps/{map-slug}`
when charted). `close` projects and pushes — the brief and `COMPLETE` reach
the espalier PR here and nowhere else — then retires this checkout's copies
that the pushed branch holds byte-for-byte, so the next `git pull` after the
espalier PR merges is not blocked by identical untracked files. A file it
keeps is named; resolve it before the next pull.
**Outside mode:** the same `close` call commits the bookkeeping into the
outside root's local repo and prints `records are in <root> @ <sha>`; there
is no espalier PR and no local copies to retire. Present the code PR link
and that line instead of two PR links.
- Summarize from `delivery-brief.md`: original cause, fix files, regression
tests added, deviations ratified.
- Report total rounds and any escalation gates tripped (even if user chose to override).
- Present both PR links (`espalier-pr.sh fix {slug} status`) and say both are
left OPEN: merging is a human act — the code PR first, then the espalier PR.
The pipeline never merges or closes a PR, including on an abort or
escalation after Stage 7; closing those is the operator's call.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |