Z audit plan
Contract-level audit of a plan's INTENT, grounding assumptions, approach choices, and initial BFS task layer before execution. Reality-checks references against the codebase, verifies best practices/design, and runs a cross-LLM adversarial review. Emits PLAN_AUDIT_REPORT.md. Low-risk plans receive a skip_recommended verdict and route directly to /z-execute.From its SKILL.md
npx -y skills add zeke13dev/z-harness --skill z-audit-planAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
60.4 KB, as published. Nobody here has run it
You are running z-harness /z-audit-plan — a structured, pre-implementation plan audit pipeline. The audit scope is contract-level: INTENT.md (the frozen intent + not-doing + acceptance checklist), grounding assumptions, approach choices, and the initial BFS task layer. This is NOT a comprehensive SPEC.md/PLAN.md/TASKS.md enumeration — full task-by-task scrutiny is deferred to the per-task reviewer at implementation time. The output is a PLAN_AUDIT_REPORT.md (detailing contract-level findings) under $Z_HARNESS_PLAN_DIR/.
Low-risk plans skip the multi-phase audit and receive a skip_recommended verdict that routes directly to /z-execute. See Phase 0 step 8 for the skip-by-recommendation fast-path.
Slug argument (from $ARGUMENTS):
$ARGUMENTS
If the user provided a slug (e.g. /z-audit-plan mcp-server), treat the first non-flag token from $ARGUMENTS as --slug <slug>. If they typed --slug <slug> explicitly, parse that form. Use it in Phase 0 step 1.
This command is read-only. Never edit active codebase files. Plan adjustments happen later via /z-amend or /z-plan based on the audit report's findings.
Plan Route Check
Run this route check during setup before any audit phase starts, and after the final report only as a contextual next-action gate. /z-audit-plan is not a front-door planning command; it is valid only when plan artifacts exist.
Use only already-known setup signals: has_existing_plan, candidate_files, expected_tasks, docs_stale_or_drifted, and whether SPEC.md, PLAN.md, and TASKS.md are present under $Z_HARNESS_PLAN_DIR.
Deterministic routes:
- If no plan artifacts are found, route to
/z-plan; do not pretend an audit can proceed. - If all plan artifacts exist, stay in
/z-audit-planand audit read-only. - If the completed audit finds accepted plan changes, route contextually to
/z-amend. - If doc drift blocks audit confidence, route contextually to
/z-maintain-docs.
Call planning-router only when deterministic signals conflict and no hard threshold already decides the route. It receives the compact signal payload plus the current route chain and is advisory; malformed or unavailable classifier output falls back to deterministic routing or an AskUser choice.
If routing after a plan is selected, write $BASE/archive/$RUN/route-decision.md after $BASE and $RUN are known. If routing because no plan artifacts exist, use the pre-discovery $NO_PLAN_ARCHIVE_DIR/route-decision.md and $NO_PLAN_RUN initialized in Phase 0. Emit plan_route_decision with from_command, to_command, route_class, reason_codes, signals, confidence, classifier_used, artifact_path, route_chain, and user_choice, then present the AskUser handoff gate: switch, continue only when plan artifacts exist, or abandon. Do not execute the next command automatically.
Loop prevention: carry forward the latest route chain; if it already has two entries, ask the user to choose explicitly. If the recommended target equals the immediate prior from_command, block ping-pong, show both route artifacts, and ask the user to choose. If the user continues here, log the override and do not route again for the same reason_codes in this run.
Phase 0 — Setup
-
Initialize no-plan route archive: Before discovering a plan slug, define a route archive for the "no artifacts found" branch:
NO_PLAN_RUN=$(date -u +%Y%m%dT%H%M%SZ)-audit-plan-no-plan NO_PLAN_ARCHIVE_DIR="$(bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-path.sh" base_dir)/archive/$NO_PLAN_RUN" -
Discover plan slug: If
--slug <slug>was provided by the user, use it directly — skip enumeration. ExportZ_HARNESS_SLUG=<slug>, resolveZ_HARNESS_PLAN_DIRviaresolve_plan_path, and proceed to step 2. The user's explicit slug overrides all directory scanning. Otherwise (no--slugargument), enumerate subdirectories under the canonical plans directory ($(bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-path.sh" base_dir)/plans/) and the legacy directories (z-harness/plans/,z-harness/) that contain plan artifacts (SPEC.md/PLAN.md/TASKS.md). Deduplicate slugs across paths.- If single candidate -> use it.
- If multiple candidates -> heartbeat before slug-select AskUserQuestion (load-bearing — extends TTL before wait; only fires after a successful claim, skip if claim not yet acquired at this point):
Then useif [[ "${CLAIM_RC:-1}" -eq 0 ]]; then HB_RC=0 bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-claim.sh" heartbeat \ --slug "$Z_HARNESS_SLUG" --run-id "$RUN" --session "$Z_HARNESS_SESSION_ID" \ --command /z-audit-plan || HB_RC=$? if [[ $HB_RC -eq 9 ]]; then bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" plan_claim_lost_during_gate \ "$(printf '{"slug":"%s","run_id":"%s","gate":"slug_select"}' "$Z_HARNESS_SLUG" "$RUN")" # Lost-claim gate: abort (default) / continue-uncoordinated. # Interactive -> AskUserQuestion: abort / continue-uncoordinated (clearly labeled: peer may clobber). # Unattended (Z_HARNESS_NO_ASK) -> abort. Release first (we held the claim), no deregister # (nothing registered yet at this point in Phase 0). # NO-REGISTRY RELEASE: capture failure; never claim success silently. RELEASE_RC=0 bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-claim.sh" release \ --slug "$Z_HARNESS_SLUG" --run-id "$RUN" --session "$Z_HARNESS_SESSION_ID" \ --command /z-audit-plan || RELEASE_RC=$? if [[ $RELEASE_RC -ne 0 ]]; then printf 'z-audit-plan: pre-registration claim release failed (exit %s); manual retry required\n' "$RELEASE_RC" >&2 exit "$RELEASE_RC" fi exit 1 fi fiAskUserQuestionto select the slug (or honor--slug <slug>argument if provided). - If zero ->
mkdir -p "$NO_PLAN_ARCHIVE_DIR", write$NO_PLAN_ARCHIVE_DIR/route-decision.mdrecommending/z-plan, emitplan_route_decisionunder$NO_PLAN_RUN, ask the user to switch or abandon, and stop. Do not create an audit report without plan artifacts.
-
Export variables: Export
Z_HARNESS_SLUG=<slug>andZ_HARNESS_PLAN_DIR=$(bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-path.sh" resolve_plan_path "$Z_HARNESS_SLUG"). Define$BASE = $Z_HARNESS_PLAN_DIR. -
Pick run ID:
RUN=$(date -u +%Y%m%dT%H%M%SZ)-<slug>-audit-plan -
Create directories:
mkdir -p $BASE/archive/$RUN/transcripts -
Version stamp + log run start: Capture the z-harness plugin version stamp and log the run start:
VERSION_BLOB="$(bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/version.sh")" START_PAYLOAD="$(python3 -c ' import json, sys v = json.loads(sys.argv[1]); v["slug"] = sys.argv[2] print(json.dumps(v)) ' "$VERSION_BLOB" "$Z_HARNESS_SLUG")" bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" plan_audit_start "$START_PAYLOAD"Session id — export ONCE, persist, restore on resume (invariant 7; do this before the claim acquire).
/z-audit-planhas no coordination wiring today; resolve the session id exactly once here, persist it to the run archive so a crash-resume reuses the SAME id (the claim's self-reentry guard depends on a stable id), and restore it on resume BEFORE acquiring.plan-claim.shnever derives the session id itself — the caller always passes it via--session.# Restore a persisted session id on resume; otherwise mint one and persist it. SID_FILE="$BASE/archive/$RUN/session-id" if [[ -z "${Z_HARNESS_SESSION_ID:-}" && -f "$SID_FILE" ]]; then export Z_HARNESS_SESSION_ID="$(cat "$SID_FILE")" fi if [[ -z "${Z_HARNESS_SESSION_ID:-}" ]]; then export Z_HARNESS_SESSION_ID="$(python3 "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/active-plan-registry.py" session-id)" fi mkdir -p "$BASE/archive/$RUN" printf '%s' "$Z_HARNESS_SESSION_ID" > "$SID_FILE"Claim acquire — CLAIM-FIRST (invariant 2; BEFORE register, BEFORE the Run Brief init, BEFORE any artifact read). The slug-level hard claim-lock is authoritative; the registry read below is advisory/FYI only. Acquiring before
registeravoids a register-succeeded-but-claim-aborted orphan (a registry record with no claim, needing deregister-without-release). The--command /z-audit-planflag is REQUIRED on this and every laterplan-claim.shcall (heartbeat, release) — it rebuilds the holder identity string for--expected-holdercomparisons; omitting it makes those subcommands exit 2 or mis-compare.CLAIM_RC=0 bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-claim.sh" acquire \ --slug "$Z_HARNESS_SLUG" --run-id "$RUN" --session "$Z_HARNESS_SESSION_ID" \ --command /z-audit-plan || CLAIM_RC=$?Branch on
CLAIM_RC(gated; surfaced — never silent). The audit's slug is FIXED to the plan being audited, so contention/takeover offers proceed / abort only — there is NO use-new-slug option (unlike/z-plan):0→ claimed (or self-reentry, orZ_HARNESS_CLAIM_DISABLE=1no-op) → proceed to register.
1(live peer holds the claim) → show the printed holder JSON (session / command / heartbeat-age). Interactive →AskUserQuestion: proceed anyway / abort. Unattended (Z_HARNESS_NO_ASK) → abort (exit 1) UNLESSZ_HARNESS_CLAIM_OVERRIDE=1(then proceed). On abort here: exit WITHOUT register (nothing registered yet) and WITHOUT release (we never acquired the lock).2(stale-takeover succeeded — we now hold the lock) → show the prior holder + idle age. Interactive →AskUserQuestion: proceed / abort (default ABORT — the prior session's partial artifacts may exist). Unattended → abort UNLESSZ_HARNESS_CLAIM_OVERRIDE=1. On abort here, CALLreleaseFIRST (we hold the lock we just took over), then exit WITHOUT register:# NO-REGISTRY RELEASE: capture failure; never claim success silently. RELEASE_RC=0 bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-claim.sh" release \ --slug "$Z_HARNESS_SLUG" --run-id "$RUN" --session "$Z_HARNESS_SESSION_ID" \ --command /z-audit-plan || RELEASE_RC=$? if [[ $RELEASE_RC -ne 0 ]]; then printf 'z-audit-plan: pre-registration claim release failed (exit %s); manual retry required\n' "$RELEASE_RC" >&2 exit "$RELEASE_RC" fi exit 13(corrupt / invalid — we do NOT hold the lock) → loud error. Proceeding does NOT acquire the slug. Interactive →AskUserQuestion: abort (default) / proceed UNCOORDINATED (clearly labeled: you and a peer may clobber each other; manual-cleanup hintrm <claims_dir>/<slug>.lock*then retry). Unattended → abort UNLESSZ_HARNESS_CLAIM_OVERRIDE=1(proceed uncoordinated). Do NOT call release (we never held it).
Teardown contract for the claim gate: on any abort at
CLAIM_RC0/1/3, exit WITHOUT release (we never acquired). At aCLAIM_RC == 2abort, release FIRST (shown above) then exit. A claim-gate abort registered NOTHING and (except exit-2) acquired nothing, so there is no deregister-without-release case. (Z_HARNESS_CLAIM_DISABLE=1skips claiming entirely;Z_HARNESS_CLAIM_OVERRIDE=1is the explicit unattended opt-in to proceed on contention/takeover/corrupt. Both are env-only knobs read inline byplan-claim.sh; see docs/human/config.md.)Active-plan registration — AFTER a successful claim (so a concurrent
/z-plan's awareness read can SEE this active audit). Register lightly with--phase audit. Graduated failure policy (same as/z-plan) — never silent-continue on failure:python3 "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/active-plan-registry.py" register \ --run-id "$RUN" --slug "$Z_HARNESS_SLUG" --command /z-audit-plan --phase audit \ --session "$Z_HARNESS_SESSION_ID" REG_RC=$?REG_RC == 0→ registered; proceed.REG_RC == 3(register FAILED — no record was written) → emit a loudregistry_errorevent, then branch:- Interactive (not
Z_HARNESS_NO_ASK) →AskUserQuestion: proceed without coordination / abort.- proceed → continue; skip heartbeats and deregister later (no record to update). The claim is still held.
- abort → push-notify, release the claim first (we hold it — register failed AFTER a successful acquire), do NOT call deregister (no record exists), then
exit 1:# NO-REGISTRY RELEASE: capture failure; never claim success silently. RELEASE_RC=0 bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-claim.sh" release \ --slug "$Z_HARNESS_SLUG" --run-id "$RUN" --session "$Z_HARNESS_SESSION_ID" \ --command /z-audit-plan || RELEASE_RC=$? if [[ $RELEASE_RC -ne 0 ]]; then printf 'z-audit-plan: no-registry claim release failed (exit %s); manual retry required\n' "$RELEASE_RC" >&2 exit "$RELEASE_RC" fi exit 1
- Unattended (
Z_HARNESS_NO_ASK) → proceed without coordination and log prominently, UNLESSZ_HARNESS_STRICT_OVERLAP=1→ release the claim (as above) and halt (exit 1). No deregister either way (no record).
- Interactive (not
- Any OTHER nonzero → treat as
REG_RC == 3.
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "orchestration" registry_error \ "$(printf '{"op":"register","run_id":"%s","rc":%d}' "$RUN" "$REG_RC")"FINALIZE_STATUS / teardown rule (single source of truth for the entire run): after registration succeeds, every run-ending path delegates atomically to
scripts/z-teardown.shwith the exact--run "$RUN" --slug "$Z_HARNESS_SLUG" --command /z-audit-plan --session "$Z_HARNESS_SESSION_ID" --status complete|abortedidentity. Every call captures its exit code. A nonzero teardown is an operational failure: surface it and exit nonzero; never independently deregister, because the wrapper intentionally retains the registry record and omits terminalrun_endwhen claim release is unconfirmed. A no-registry abort may callplan-claim.sh releasedirectly, but it must capture/report nonzero and fail rather than use|| true. Heartbeat is called at each phase boundary and before every AskUserQuestion gate.Plan-start awareness read (advisory; Invariant 1 — never a hard gate). After a successful claim and register, read the lockless registry and surface concurrent peers. Read-only, deterministic, non-fatal:
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/active-plan-registry.py" list --json 2>/dev/null AWARE_RC=$?Render any record whose
session_id != $Z_HARNESS_SESSION_IDas a one-line advisory ("Other active sessions: <run_id> — <command> on <slug> (heartbeat <age>)"). On a non-zerolistexit, emitregistry_error {op:"awareness_read_failed", rc:$AWARE_RC}and CONTINUE — the awareness read never blocks or gates a subsequent phase:if [[ $AWARE_RC -ne 0 ]]; then bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "orchestration" registry_error \ "$(printf '{"op":"awareness_read_failed","rc":%d}' "$AWARE_RC")" fiRun Brief init (after the claim + register + awareness read). Registry:
/z-audit-plan, profilefull, artifactPLAN_AUDIT_REPORT.md.CURRENT_ARCHIVE_DIR="$BASE/archive/$RUN" RB_SH="${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/run-brief.sh" PLAN_AUDIT_INTENT="Pre-implementation audit of plan ${Z_HARNESS_SLUG}" bash "$RB_SH" init --run "$RUN" --command /z-audit-plan --slug "$Z_HARNESS_SLUG" --profile full --intent "$PLAN_AUDIT_INTENT" export RUN_BRIEF_PROFILE=full export RUN_BRIEF_ARTIFACT="$BASE/PLAN_AUDIT_REPORT.md" export RUN_BRIEF_ARTIFACT_FALLBACKS="" -
Notification policy: see docs/human/config.md (notify.level key).
-
Artifact Scout preflight: Run after plan selection, claim/register, awareness, and Run Brief init, but before docs grounding, pre-reviewer, consultant, or auditor dispatch.
REPO_ROOT="${REPO_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}" ARTIFACT_SCOUT_INVENTORY="$BASE/archive/$RUN/artifact-scout-inventory.json" python3 "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/artifact-scout-inventory.py" \ --command /z-audit-plan --slug "$Z_HARNESS_SLUG" --run-id "$RUN" \ --repo-root "$REPO_ROOT" --plan-dir "$BASE" \ --task "$ARGUMENTS" --output "$ARTIFACT_SCOUT_INVENTORY" ARTIFACT_SCOUT_EVENT_PAYLOAD="$(python3 - "$ARTIFACT_SCOUT_INVENTORY" <<'PYEOF'
import json, sys path = sys.argv[1] data = json.load(open(path, encoding="utf-8")) print(json.dumps({ "command": data.get("command"), "slug": data.get("slug"), "run_id": data.get("run_id"), "artifact_path": path, "source_status": data.get("source_status", {}), "mandatory_candidate_count": len(data.get("mandatory_candidates") or []), "historical_candidate_count": len(data.get("historical_candidates") or []), "active_record_count": len(data.get("active_records") or []), "worktree_count": len(data.get("worktrees") or []), "truncated": bool(data.get("truncated")), }, separators=(",", ":"))) PYEOF )" bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" artifact_scout_inventory_complete "$ARTIFACT_SCOUT_EVENT_PAYLOAD"
The `artifact_scout_inventory_complete` payload MUST include `command`, `slug`, `run_id`, `artifact_path`, `source_status`, `mandatory_candidate_count`, `historical_candidate_count`, `active_record_count`, `worktree_count`, and `truncated` from the inventory JSON.
<!-- RUNTIME-GATE: subagent; non-supporting drivers must surface this artifact-scout
requirement and skip the Agent() call. Skipping means continue without scout routing. -->
Agent( subagent_type="artifact-scout", description="Artifact scout for z-audit-plan <slug>", prompt="current_command: /z-audit-plan task_or_topic: <plan audit request> route_chain_json: <current route chain JSON> repo_root: <abs repo root> inventory_json_path: $BASE/archive/$RUN/artifact-scout-inventory.json
Inline inventory JSON: <contents printed by scripts/artifact-scout-inventory.py>" )
Write the raw response to `$BASE/archive/$RUN/artifact-scout.md`. Emit `artifact_scout_classified`, `artifact_scout_warning`, and `artifact_scout_route` per the contract. Warning-only output never writes `route-decision.md`, never emits `artifact_scout_route`, and never advances `route_chain`; only `ask_user` or route outcomes with `route_chain_effect: "write_route_decision"` may write a route artifact and emit `plan_route_decision`.
8. **Docs Grounding:**
If `docs/llm/INDEX.json` exists in the repo root, dispatch `doc-fetcher` (Haiku) to identify concepts touched by this plan:
<!-- RUNTIME-GATE: subagent; non-supporting drivers must surface this dispatch
requirement and skip if subagent support is unavailable. The audit can
proceed without doc grounding at reduced confidence. -->
Agent( subagent_type="doc-fetcher", description="Doc context for plan audit <slug>", prompt="query: which concepts cover <plan files and symbols>?\nrepo_root: <abs path>\ndepth: summary" )
Use the returned concept slugs to retrieve the appropriate `docs/llm/<concept>.json` files as plan-grounding validation guidelines.
9. **Skip-by-recommendation — low-risk fast-path:**
After completing steps 0–8, evaluate whether the plan qualifies for a skip. A plan is **low-risk** when ALL of the following hold:
- No public API changes (no new exported functions, types, or CLI flags in the acceptance criteria)
- No schema/migration impact (no database table changes, no serialization-format changes)
- No cross-module entanglement (changes confined to a single skill dir or a clearly scoped subsystem)
- `candidate_files <= 5` (total distinct files referenced across acceptance criteria)
- `non_obvious_decisions <= 2` (count of design choices that require non-trivial tradeoff reasoning)
Evaluate each condition from the INTENT snapshot (frozen INTENT + acceptance checklist + task block). If ANY condition fails, the plan is not low-risk — fall through to Phase 1 normally.
If ALL conditions hold, emit a `skip_recommended` verdict block to `$BASE/PLAN_AUDIT_REPORT.md`:
```markdown
# Plan Audit Report — <slug>
- **Date (UTC):** YYYY-MM-DDTHH:MMZ
- **Slug:** <slug>
- **Run ID:** <RUN>
- **Verdict:** skip_recommended
## Skip Rationale
This plan is classified as low-risk: no public API changes, no schema/migration impact, no
cross-module entanglement, candidate_files ≤ 5, non_obvious_decisions ≤ 2. Full multi-phase
contract audit skipped. <One-sentence summary of why this specific plan qualifies.>
## Recommended next step
`/z-execute <slug>`
Then log the skip event:
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" audit_skip_recommended \
"$(printf '{"slug":"%s","reason":"low_risk","candidate_files":%d,"non_obvious_decisions":%d}' \
"$Z_HARNESS_SLUG" "$CANDIDATE_FILES" "$NON_OBVIOUS_DECISIONS")"
Present the skip summary as a prose chat reply (no popup):
Plan audit for <slug>: skip recommended.
Full report: $BASE/PLAN_AUDIT_REPORT.md
This plan is low-risk (no API/schema changes, confined scope, ≤5 files, ≤2 non-obvious
decisions). The multi-phase contract audit was skipped.
Recommended next step: /z-execute <slug>
Then jump to the Normal-end teardown in Phase 9 (the canonical wrapper owns release + deregister) and exit 0. Do NOT run Phases 1–5 for a skip_recommended plan.
Phase 1 — Reality Check (Reference Verification)
Heartbeat at phase boundary (before phase work begins):
HB_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-claim.sh" heartbeat \
--slug "$Z_HARNESS_SLUG" --run-id "$RUN" --session "$Z_HARNESS_SESSION_ID" \
--command /z-audit-plan || HB_RC=$?
if [[ $HB_RC -eq 9 ]]; then
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" plan_claim_lost_during_gate \
"$(printf '{"slug":"%s","run_id":"%s","gate":"phase1_start"}' "$Z_HARNESS_SLUG" "$RUN")"
# Lost-claim gate: warn user prominently. Offer abort (default) / continue-uncoordinated.
# Interactive -> AskUserQuestion: "Another session took over this slug. Abort (default) or continue-uncoordinated (you and the peer may clobber each other)?".
# Unattended (Z_HARNESS_NO_ASK) -> abort unless Z_HARNESS_CLAIM_OVERRIDE=1 (continue-uncoordinated).
# On abort after registration: canonical teardown retains registry state if release is unconfirmed.
TEARDOWN_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/z-teardown.sh" \
--run "$RUN" --slug "$Z_HARNESS_SLUG" --command /z-audit-plan \
--session "$Z_HARNESS_SESSION_ID" --status aborted || TEARDOWN_RC=$?
if [[ $TEARDOWN_RC -ne 0 ]]; then
printf 'z-audit-plan: aborted teardown incomplete (exit %s); registry retained for retry\n' "$TEARDOWN_RC" >&2
exit "$TEARDOWN_RC"
fi
exit 1
fi
Parse the contract artifacts — $BASE/INTENT.md (or $BASE/SPEC.md for legacy plans), grounding assumptions (captured in the handoff or in $BASE/archive/$RUN/ grounding notes), and the acceptance checklist + initial task layer — to identify factual claims made about the active codebase. Do NOT attempt to enumerate every task in TASKS.md; focus the reality-check on the contract-level claims in the acceptance checklist and the grounding assumptions. Scrutinize these references:
- Entities to verify:
- Files & Directories: Ensure paths described as existing or as preconditions actually exist.
- Symbols: Grep for declarations of functions, methods, classes, variables, or types mentioned in the spec.
- Configs: Verify the existence of specific configuration files or specific JSON/YAML/TOML keys referenced in the plan.
- Database Elements: Ensure tables or columns referenced as active database preconditions exist in schema declarations, models, or migration files.
- CLI Flags: Ensure referenced CLI arguments are declared in their respective option-parsing functions.
- Bucket division:
- MUST EXIST NOW: Entities described as present. Run
Read/Grep/Globto verify their existence and declarations exactly. - WILL BE CREATED: Newly proposed files. Verify that their proposed paths do not clash with existing files in the codebase.
- MUST EXIST NOW: Entities described as present. Run
- Drift & Hallucination detection:
- Flag similar-but-different naming (e.g.
user_idvsuid, or double-suffixes). - Flag contract mismatches between proposed specifications and current codebase structures.
- Flag dependency order violations (e.g., plan relies on a database table that is not created in this or any prior completed plan).
- Flag similar-but-different naming (e.g.
Checkpoint: Write results to $BASE/archive/$RUN/phase1-reality.md.
Phase 2 — Best Practices & Design Audit
Heartbeat at phase boundary (before phase work begins):
HB_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-claim.sh" heartbeat \
--slug "$Z_HARNESS_SLUG" --run-id "$RUN" --session "$Z_HARNESS_SESSION_ID" \
--command /z-audit-plan || HB_RC=$?
if [[ $HB_RC -eq 9 ]]; then
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" plan_claim_lost_during_gate \
"$(printf '{"slug":"%s","run_id":"%s","gate":"phase2_start"}' "$Z_HARNESS_SLUG" "$RUN")"
TEARDOWN_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/z-teardown.sh" \
--run "$RUN" --slug "$Z_HARNESS_SLUG" --command /z-audit-plan \
--session "$Z_HARNESS_SESSION_ID" --status aborted || TEARDOWN_RC=$?
if [[ $TEARDOWN_RC -ne 0 ]]; then
printf 'z-audit-plan: aborted teardown incomplete (exit %s); registry retained for retry\n' "$TEARDOWN_RC" >&2
exit "$TEARDOWN_RC"
fi
exit 1
fi
Audit the plan's architectural, design, and styling choices against best engineering practices:
- Standards verification:
- KISS & DRY: Check for unnecessary complexity, premature abstractions, or code duplication planned across tasks.
- SOLID: Ensure clean single-responsibility components and clear interface boundaries.
- Style: Align proposed changes with
STYLE.mdrules (if it exists).
- Defensive Bloat & Over-engineering:
- Check if error handling is overly defensive, or if unnecessary abstractions are introduced where simple code would suffice.
- Performance & Resources:
- Detect potential N+1 database queries, excessive object allocations in loops, locking/deadlock risks, or poor Big-O complexity in algorithms.
- Security & Validation:
- Ensure all input validation boundaries, sanitization strategies, authentication/authorization checks, and data exposure patterns are secure.
Checkpoint: Write results to $BASE/archive/$RUN/phase2-design.md.
Phase 2.5 — Pre-review cycle (opt-in)
Opt-in gate: Only runs if runtime.pre_review is true in config. Check at phase start:
if [ "$(python3 "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/config.py" get runtime.pre_review 2>/dev/null)" != "true" ]; then
echo "Pre-review cycle skipped (runtime.pre_review != true)"
# Jump to Phase 3
return 0
fi
When enabled, spawn 3 pre-reviewers in parallel to do a fast first-pass scan on plan artifacts before the expensive adversarial consultants.
Dispatch all three in a single message via parallel Agent() calls:
Agent(
subagent_type="pre-reviewer",
description="Pre-review 1 — reality check (Flash) for <slug>",
prompt="MODE: plan-audit
slug: <slug>
run_id: <RUN>
Kernel path: <KERNEL_PATH>
INTENT.md: $BASE/INTENT.md (or $BASE/SPEC.md for legacy plans)
TASKS.md (initial layer only): $BASE/TASKS.md
phase1_reality: $BASE/archive/$RUN/phase1-reality.md
phase2_design: $BASE/archive/$RUN/phase2-design.md
Focus: REALITY CHECK — reference errors in the contract artifacts (INTENT.md, grounding assumptions, acceptance checklist, initial task layer). Files that don't exist, symbols that are wrong, config paths that are hallucinated, naming drift, dependency order violations. Compare contract-level claims against the actual codebase. Do NOT enumerate every TASKS.md task — focus on the acceptance criteria and grounding premises. Be fast and cheap — surface only clear blockers and majors."
)
Agent(
subagent_type="pre-reviewer",
description="Pre-review 2 — design & style audit (Flash) for <slug>",
prompt="MODE: plan-audit
slug: <slug>
run_id: <RUN>
Kernel path: <KERNEL_PATH>
INTENT.md: $BASE/INTENT.md (or $BASE/SPEC.md for legacy plans)
TASKS.md (initial layer only): $BASE/TASKS.md
phase1_reality: $BASE/archive/$RUN/phase1-reality.md
phase2_design: $BASE/archive/$RUN/phase2-design.md
Focus: DESIGN & STYLE — DRY/KISS/SOLID violations, premature abstractions, over-engineering, STYLE.md drift, defensive bloat, security concerns in the contract artifacts (INTENT + grounding + approach + initial task layer). Do NOT check reality references (that's pre-review 1's job). Be fast and cheap — surface only clear blockers and majors."
)
Agent(
subagent_type="pre-reviewer",
description="Pre-review 3 — logic & completeness (Flash) for <slug>",
prompt="MODE: plan-audit
slug: <slug>
run_id: <RUN>
Kernel path: <KERNEL_PATH>
INTENT.md: $BASE/INTENT.md (or $BASE/SPEC.md for legacy plans)
TASKS.md (initial layer only): $BASE/TASKS.md
phase1_reality: $BASE/archive/$RUN/phase1-reality.md
phase2_design: $BASE/archive/$RUN/phase2-design.md
Focus: LOGIC & COMPLETENESS — logic gaps in the contract (INTENT + grounding + acceptance checklist + initial task layer), missing edge cases in acceptance criteria, dependency problems, unstated assumptions that should be made explicit. Do NOT attempt full enumeration of TASKS.md. Do NOT check reality references or design style (those are pre-review 1/2's jobs). Be fast and cheap — surface only clear blockers and majors."
)
Collecting pre-review findings: After all three return, read their outputs. Write a consolidated pre-review summary to $BASE/archive/$RUN/pre-review.md:
# Pre-review summary — <slug>
Run: <RUN>
## Pre-review 1 — reality check
<verbatim findings from pre-reviewer 1, or "CLEAN">
## Pre-review 2 — design & style
<verbatim findings from pre-reviewer 2, or "CLEAN">
## Pre-review 3 — logic & completeness
<verbatim findings from pre-reviewer 3, or "CLEAN">
Feeding into Phase 3: The consolidated $BASE/archive/$RUN/pre-review.md path is added as a context item in the Phase 3 adversarial consultant prompts. Each consultant's prompt gains a section:
Pre-review findings (3 × DeepSeek V4 Flash fast scan):
<contents of $BASE/archive/$RUN/pre-review.md>
These are cheap pre-screener findings — validate them critically before accepting. The real adversarial review is your own analysis.
Phase 3 — Adversarial Cross-LLM Review
Heartbeat at phase boundary (before phase work begins):
HB_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-claim.sh" heartbeat \
--slug "$Z_HARNESS_SLUG" --run-id "$RUN" --session "$Z_HARNESS_SESSION_ID" \
--command /z-audit-plan || HB_RC=$?
if [[ $HB_RC -eq 9 ]]; then
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" plan_claim_lost_during_gate \
"$(printf '{"slug":"%s","run_id":"%s","gate":"phase3_start"}' "$Z_HARNESS_SLUG" "$RUN")"
TEARDOWN_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/z-teardown.sh" \
--run "$RUN" --slug "$Z_HARNESS_SLUG" --command /z-audit-plan \
--session "$Z_HARNESS_SESSION_ID" --status aborted || TEARDOWN_RC=$?
if [[ $TEARDOWN_RC -ne 0 ]]; then
printf 'z-audit-plan: aborted teardown incomplete (exit %s); registry retained for retry\n' "$TEARDOWN_RC" >&2
exit "$TEARDOWN_RC"
fi
exit 1
fi
Spawn two consultants in parallel to review the plan's contract artifacts (INTENT.md, grounding assumptions, acceptance checklist, and initial task layer) and Phase 1/2 audit notes with a highly critical, adversarial mindset. Scope is contract-level — do NOT attempt a full task-by-task enumeration of TASKS.md:
<!-- RUNTIME-GATE: subagent; non-supporting drivers must surface this dispatch
requirement to the user and skip both consultant Agent() calls. Phase 3
cannot complete without subagent support; document the gap and proceed
to Phase 4 without adversarial review input. -->
Agent(
subagent_type="consultant-primary",
description="Adversarial plan audit review (Gemini) for <slug>",
prompt="MODE: plan-audit-review\n\nINTENT:\n<INTENT.md frozen snapshot>\n\nAcceptance checklist:\n<acceptance criteria from INTENT>\n\nInitial task layer:\n<first BFS layer from TASKS.md if present>\n\nReality Check Notes:\n<phase1-reality.md>\n\nDesign Audit Notes:\n<phase2-design.md>\n\nAct as a highly critical, adversarial 'Senior Nitpicker'. Audit at contract level: INTENT + grounding assumptions + approach choices + initial task layer. Do NOT enumerate every task in TASKS.md. Find logic flaws, race conditions, edge cases, missing tests in acceptance criteria, security concerns, style drift, or over-engineering in the plan. Report findings with severity (BLOCKER / MAJOR / MINOR), location, and recommendations."
)
Agent(
subagent_type="consultant-secondary",
description="Adversarial plan audit review (Codex) for <slug>",
prompt="MODE: plan-audit-review\n\n<same prompt>"
)
Both consultants return structured findings. Transcripts are archived under $BASE/archive/$RUN/transcripts/.
Phase 4 — Merge and Synthesize Findings
Heartbeat at phase boundary (before phase work begins):
HB_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-claim.sh" heartbeat \
--slug "$Z_HARNESS_SLUG" --run-id "$RUN" --session "$Z_HARNESS_SESSION_ID" \
--command /z-audit-plan || HB_RC=$?
if [[ $HB_RC -eq 9 ]]; then
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" plan_claim_lost_during_gate \
"$(printf '{"slug":"%s","run_id":"%s","gate":"phase4_start"}' "$Z_HARNESS_SLUG" "$RUN")"
TEARDOWN_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/z-teardown.sh" \
--run "$RUN" --slug "$Z_HARNESS_SLUG" --command /z-audit-plan \
--session "$Z_HARNESS_SESSION_ID" --status aborted || TEARDOWN_RC=$?
if [[ $TEARDOWN_RC -ne 0 ]]; then
printf 'z-audit-plan: aborted teardown incomplete (exit %s); registry retained for retry\n' "$TEARDOWN_RC" >&2
exit "$TEARDOWN_RC"
fi
exit 1
fi
-
Aggregation: Merge findings from Reality Check, Design Audit, and both adversarial consultant reviews.
-
One-Reason-This-Might-Be-Wrong Gate: For every finding, write a brief statement detailing "one reason this finding might be wrong, irrelevant, or pedantic". If the pushback is valid:
- Drop the finding from the final report.
- Or demote its severity.
-
Class tagging (every surviving finding): After the gate, assign a canonical
Classto every surviving finding using the enum fromz-review-all.md(line 716):implementation_drift | spec_gap | completed_task_contradiction | premise_failure | observation. For audit-plan findings, only two values apply:spec_gap— factual or mechanical corrections: wrong symbol, wrong path, wrong table or config value, malformed criterion, missing test, naming drift. The plan states something incorrect about the world.premise_failure— viability or design approach concerns: won't scale or work as written, materially better path exists, wrong library chosen, foundational premise is flawed. The plan may be factually consistent but its approach is questionable.
The discriminator is Class/disposition, NOT severity. A BLOCKER finding can be either
spec_gap(a hard factual error) orpremise_failure(a fatal design concern). A MINOR finding can likewise be either. Never usecorrectionorapproachas Class values — those are human glosses only, not enum members. Never invent new Class values. -
Write final report: Write the unified plan-audit report to
$BASE/PLAN_AUDIT_REPORT.md(and save a copy in$BASE/archive/$RUN/PLAN_AUDIT_REPORT.md):# Plan Audit Report — <slug> - **Date (UTC):** YYYY-MM-DDTHH:MMZ - **Slug:** <slug> - **Run ID:** <RUN> ## Summary - <Actionable high-level takeaways> ## reality-check Reality Check findings <Stale references, naming drift, clashing paths> ## design-check Design & Style findings <SOLID/DRY violations, style drift, over-engineering, performance, security> ## adversarial Adversarial Consult findings <Logic gaps, race conditions, unhandled edge cases, missing tests in acceptance> ## Consensus vs Disagreement - consensus: <findings flagged by multiple layers> - outlier: <findings worth manual scrutiny> ## Actionable Recommendations <Categorized recommendations with recommended actions>Each individual finding entry in the report must include a
**Class:**field immediately after**Severity:**. Example per-finding format:- **Severity:** MAJOR - **Class:** spec_gap - **Location:** <file or section> - **Finding:** <description> - **Recommendation:** <action>The
**Class:**value must bespec_gaporpremise_failure(the two values that apply to audit-plan findings). The field is required on every surviving finding — no finding may appear in the report without it.
Phase 5 — Gate & Action
Heartbeat before Phase 5 audit gate (load-bearing — extends TTL before any interactive wait):
HB_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-claim.sh" heartbeat \
--slug "$Z_HARNESS_SLUG" --run-id "$RUN" --session "$Z_HARNESS_SESSION_ID" \
--command /z-audit-plan || HB_RC=$?
if [[ $HB_RC -eq 9 ]]; then
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" plan_claim_lost_during_gate \
"$(printf '{"slug":"%s","run_id":"%s","gate":"audit_gate"}' "$Z_HARNESS_SLUG" "$RUN")"
# Lost-claim gate: Interactive -> AskUserQuestion abort (default) / continue-uncoordinated.
# Unattended (Z_HARNESS_NO_ASK) -> abort through canonical teardown.
TEARDOWN_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/z-teardown.sh" \
--run "$RUN" --slug "$Z_HARNESS_SLUG" --command /z-audit-plan \
--session "$Z_HARNESS_SESSION_ID" --status aborted || TEARDOWN_RC=$?
if [[ $TEARDOWN_RC -ne 0 ]]; then
printf 'z-audit-plan: aborted teardown incomplete (exit %s); registry retained for retry\n' "$TEARDOWN_RC" >&2
exit "$TEARDOWN_RC"
fi
exit 1
fi
-
Gate decision — run before any user interaction:
# Capture exit code separately — do NOT silence stderr RESOLVED="$(python3 scripts/config.py resolve-question workflow.audit_to_amend)" RESOLVE_EXIT=$? if [[ $RESOLVE_EXIT -ne 0 ]]; then # Exit codes: 2=bad invocation, 3=unknown question_id, 4=I/O error. # In all error cases, fall through to force_ask — never silently skip. echo "resolve-question failed (exit $RESOLVE_EXIT); falling back to force_ask" >&2 GATE_DECISION="force_ask" RESOLVED='{"result":"ask","source":"error","default":""}' else GATE_DECISION="$(python3 scripts/amend-gate-decision.py "$RESOLVED")" fi # Retain individual fields for force_ask popup and Phase 9 elevation RESULT="$(echo "$RESOLVED" | jq -r .result)" DEFAULT="$(echo "$RESOLVED" | jq -r .default)" SOURCE="$(echo "$RESOLVED" | jq -r .source)"Branch on
$GATE_DECISION:halt— stop immediately, no amend, no popup:if [[ "$GATE_DECISION" == "halt" ]]; then bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" audit_halt \ "$(printf '{"reason":"no_ask_blocked","question_id":"workflow.audit_to_amend","rule_id":"no_ask_halt"}')" echo "halt: no_ask_blocked on workflow.audit_to_amend" >&2 fiStop here when
$GATE_DECISIONishalt. Jump to Run Brief — halt finalize below (substitute<reason>), thenexit 0— do not fall through to the auto_split or force_ask branches, step 2, or Phase 9.auto_split— auto-amendspec_gapfindings; renderpremise_failurefindings as prose brief:2a. Extract findings by Class from
$BASE/PLAN_AUDIT_REPORT.md.# Guard: PLAN_AUDIT_REPORT.md must exist and be parseable before extraction. if [[ ! -f "$BASE/PLAN_AUDIT_REPORT.md" ]]; then echo "z-audit-plan Phase 5: PLAN_AUDIT_REPORT.md not found at $BASE/PLAN_AUDIT_REPORT.md — cannot extract findings." >&2 bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" audit_artifact_missing \ "$(printf '{"artifact":"PLAN_AUDIT_REPORT.md","base":"%s"}' "$BASE")" || true TEARDOWN_RC=0 bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/z-teardown.sh" \ --run "$RUN" --slug "$Z_HARNESS_SLUG" --command /z-audit-plan \ --session "$Z_HARNESS_SESSION_ID" --status aborted || TEARDOWN_RC=$? if [[ $TEARDOWN_RC -ne 0 ]]; then printf 'z-audit-plan: missing-report teardown incomplete (exit %s); registry retained for retry\n' "$TEARDOWN_RC" >&2 exit "$TEARDOWN_RC" fi exit 1 fiParse each finding block (delimited by
- **Severity:**entries). For every block that has**Class:** spec_gap, collect the finding title/description into the corrections list. For every block that has**Class:** premise_failure, collect it into the approach_concerns list. Skip any spec_gap finding whose associated task (identified by a**Task:**or**Location:**field referencing a task ID likeT001) appears as a completed[x]entry in$BASE/TASKS.md— completed-task guard for symmetry with review-all.2b. Detect target plan mode:
if [[ -f "$BASE/INTENT.md" ]] && [[ ! -f "$BASE/SPEC.md" ]]; then TARGET_MODE="intent" else TARGET_MODE="legacy" fi2c. Auto-amend
spec_gapfindings via/z-amend:For an INTENT-mode target — batch ALL spec_gap corrections into a single amendment description and invoke
/z-amendONCE (one contract re-freeze). Build the combined amendment text as a bullet list of all corrections and call:/z-amend "<combined amendment text listing all spec_gap corrections>"For a legacy-mode target — invoke
/z-amendonce per spec_gap finding:/z-amend "<correction title: description>"In both modes: skip any spec_gap finding whose task is already
[x]complete in TASKS.md (guard from step 2a) — this is the same completed-task guard, so/z-amend's own Phase 4 gate always finds an emptyTouched-but-completed taskslist here and auto-proceeds without asking. Track the count of amendments actually invoked asN_AUTO_AMENDED.2d. Render
premise_failurefindings as prose brief. Build the JSON input foramendment-brief.pyfrom the two lists. The corrections list uses each spec_gap finding's title/description/location as{"title": ..., "why": ..., "target": ...}. The approach_concerns list uses each premise_failure finding as{"concern": ..., "affected"?: ..., "suggestion"?: ...}(omitaffectedwhen no task/file target is identified). Track count asN_APPROACH_SURFACED.# Build JSON for amendment-brief.py — concrete extraction from PLAN_AUDIT_REPORT.md _EXTRACT_PY="$(mktemp /tmp/audit_extract_XXXXXX.py)" cat > "$_EXTRACT_PY" <<'PY'
import json, re, sys from pathlib import Path
report_path = sys.argv[1] tasks_path = sys.argv[2]
corrections = [] approach_concerns = []
report_text = Path(report_path).read_text(encoding="utf-8")
Read completed task IDs from TASKS.md (lines with [x] and a task ID like T001)
completed_tasks = set() if Path(tasks_path).exists(): tasks_text = Path(tasks_path).read_text(encoding="utf-8") for m in re.finditer(r'[x].*?\b(T\d+)\b', tasks_text, re.IGNORECASE): completed_tasks.add(m.group(1).upper())
Split the report into finding blocks. Each block starts with a "- Severity:" line.
block_re = re.compile(r'(?=^- **Severity:**)', re.MULTILINE) blocks = block_re.split(report_text)
for block in blocks: if not block.strip(): continue
class_match = re.search(r'\*\*Class:\*\*\s*(\S+)', block)
if not class_match:
continue
finding_class = class_match.group(1).strip().rstrip('.')
# Extract task/location reference to check completed-task guard
task_ref_match = re.search(r'\*\*(?:Task|Location):\*\*\s*.*?\b(T\d+)\b', block, re.IGNORECASE)
task_ref = task_ref_match.group(1).upper() if task_ref_match else None
if finding_class == "spec_gap":
# Skip if the referenced task is already completed
if task_ref and task_ref in completed_tasks:
continue
finding_match = re.search(r'\*\*Finding:\*\*\s*(.+?)(?=\n- \*\*|\Z)', block, re.DOTALL)
title = finding_match.group(1).strip().replace('\n', ' ') if finding_match else block.strip().splitlines()[0][:120]
recommendation_match = re.search(r'\*\*Recommendation:\*\*\s*(.+?)(?=\n- \*\*|\Z)', block, re.DOTALL)
why = recommendation_match.group(1).strip().replace('\n', ' ') if recommendation_match else ""
location_match = re.search(r'\*\*Location:\*\*\s*(.+?)(?=\n)', block)
target = location_match.group(1).strip() if location_match else (task_ref or "")
corrections.append({"title": title, "why": why, "target": target})
elif finding_class == "premise_failure":
finding_match = re.search(r'\*\*Finding:\*\*\s*(.+?)(?=\n- \*\*|\Z)', block, re.DOTALL)
concern = finding_match.group(1).strip().replace('\n', ' ') if finding_match else block.strip().splitlines()[0][:200]
location_match = re.search(r'\*\*Location:\*\*\s*(.+?)(?=\n)', block)
affected = location_match.group(1).strip() if location_match else (task_ref or None)
recommendation_match = re.search(r'\*\*Recommendation:\*\*\s*(.+?)(?=\n- \*\*|\Z)', block, re.DOTALL)
suggestion = recommendation_match.group(1).strip().replace('\n', ' ') if recommendation_match else None
entry = {"concern": concern}
if affected:
entry["affected"] = affected
if suggestion:
entry["suggestion"] = suggestion
approach_concerns.append(entry)
print(json.dumps({"corrections": corrections, "approach_concerns": approach_concerns})) PY BRIEF_JSON="$(python3 "$_EXTRACT_PY" "$BASE/PLAN_AUDIT_REPORT.md" "$BASE/TASKS.md")" rm -f "$_EXTRACT_PY" BRIEF_OUTPUT="$(printf '%s' "$BRIEF_JSON" | python3 "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/amendment-brief.py")"
Present `$BRIEF_OUTPUT` as a conversational reply — **no `AskUserQuestion` popup**. If
`approach_concerns` is empty, the brief has no "Worth your eyes" section; present the
"Patched automatically" list and a forward recommendation to proceed to `/z-execute`.
If `approach_concerns` is non-empty, invite the user to reply conversationally (rework / proceed
/ re-plan).
2e. **Telemetry:**
```bash
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" audit_auto_split \
"$(printf '{"corrections_auto_amended":%d,"approach_concerns_surfaced":%d,"target_mode":"%s"}' \
"$N_AUTO_AMENDED" "$N_APPROACH_SURFACED" "$TARGET_MODE")"
Set AUDIT_GATE_CHOICE="auto_split" for the run-brief outcome line.
force_ask — prose alignment summary (no popup):
When $GATE_DECISION is force_ask, emit a prose alignment summary instead of an AskUserQuestion popup. This aligns with the user's askuser-modality preference: judgment-call checkpoints use prose, not popups.
Print the following alignment summary directly as chat output:
Plan audit complete for slug: <$Z_HARNESS_SLUG>
Full report: $BASE/PLAN_AUDIT_REPORT.md
Summary:
- <$N_FINDINGS> total findings (<$N_BLOCKERS> blockers, <$N_MAJORS> majors)
- <$N_AUTO_AMENDED> spec_gap findings auto-amended via /z-amend
- <$N_APPROACH_SURFACED> premise_failure concerns surfaced above
<If N_BLOCKERS > 0: "BLOCKERS found — review the report before proceeding to implementation.
Consider running /z-amend to address them, then re-audit.">
<If N_BLOCKERS == 0 and N_MAJORS > 0: "No blockers. Review the MAJOR findings above
and decide whether to amend before proceeding.">
<If N_BLOCKERS == 0 and N_MAJORS == 0: "Clean audit — no blockers or majors.
Proceed to /z-execute when ready.">
Recommended next step: /z-execute <$Z_HARNESS_SLUG>
(or /z-amend <$Z_HARNESS_SLUG> to address any findings first)
Set AUDIT_GATE_CHOICE="force_ask_prose" for the run-brief outcome line.
-
Run Brief finalize (before
plan_audit_end). Set outcome/next from audit counts and the resolved gate choice. Chat render replaces ad-hoc notify/present prose.
<!-- include: _fragments/run-brief-finalize.md -->CURRENT_ARCHIVE_DIR="$BASE/archive/$RUN" export RUN_BRIEF_PROFILE=full export RUN_BRIEF_ARTIFACT="$BASE/PLAN_AUDIT_REPORT.md" export RUN_BRIEF_ARTIFACT_FALLBACKS="" RB_SH="${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/run-brief.sh" RB_PY="${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/render-run-brief.py" case "${AUDIT_GATE_CHOICE:-auto_split}" in auto_split|force_ask_prose) _RB_NEXT_CMD="/z-execute"; _RB_NEXT_LABEL="Proceed to /z-execute" ;; *amend*) _RB_NEXT_CMD="/z-amend"; _RB_NEXT_LABEL="Amend plan via /z-amend" ;; *re-plan*|*replan*) _RB_NEXT_CMD="/z-plan"; _RB_NEXT_LABEL="Re-plan via /z-plan" ;; *) _RB_NEXT_CMD="/z-execute"; _RB_NEXT_LABEL="Proceed to /z-execute" ;; esac bash "$RB_SH" set-section --run "$RUN" --section outcome \ --value "Plan audit: ${N_FINDINGS} findings (${N_BLOCKERS} blockers, ${N_MAJORS} majors); gate: ${AUDIT_GATE_CHOICE:-auto_split}" bash "$RB_SH" set-section --run "$RUN" --section next --json /dev/stdin <<JSON {"label": "${_RB_NEXT_LABEL}", "command": "${_RB_NEXT_CMD}"} JSON # Pre-seed approach when PLAN_AUDIT_REPORT.md is prose-only (no extractable list bullets) if [[ -f "$RUN_BRIEF_ARTIFACT" ]]; then _RB_APPROACH_N="$(python3 -c ' import importlib.util, sys spec = importlib.util.spec_from_file_location("rrb", sys.argv[1]) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) print(len(mod.extract_approach_bullets(sys.argv[2]))) ' "$RB_PY" "$RUN_BRIEF_ARTIFACT")" if [[ "$_RB_APPROACH_N" -gt 0 ]]; then bash "$RB_SH" set-section --run "$RUN" --section approach --file "$RUN_BRIEF_ARTIFACT" || true else _RB_SEED="$CURRENT_ARCHIVE_DIR/run-brief-approach-seed.md" printf '%s\n' \ "- Reality-check references against the codebase" \ "- Design and style audit against best practices" \ "- Adversarial cross-LLM review of plan artifacts" \ > "$_RB_SEED" bash "$RB_SH" set-section --run "$RUN" --section approach --file "$_RB_SEED" || true fi fi bash "$RB_SH" set-section --run "$RUN" --section status --value "complete"- Log run end:
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" plan_audit_end \ "$(printf '{"status":"complete","findings":%d,"blockers":%d,"majors":%d}' "$N_FINDINGS" "$N_BLOCKERS" "$N_MAJORS")"
Run Brief — halt finalize
Before exit on any halt after run-brief.sh init when PLAN_AUDIT_REPORT.md is missing or the run aborts early. Substitute <reason> in the outcome line. Fragment auto-downgrades to lite when the report file is absent.
CURRENT_ARCHIVE_DIR="$BASE/archive/$RUN"
export RUN_BRIEF_PROFILE=full
export RUN_BRIEF_ARTIFACT="$BASE/PLAN_AUDIT_REPORT.md"
export RUN_BRIEF_ARTIFACT_FALLBACKS=""
RB_SH="${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/run-brief.sh"
bash "$RB_SH" set-section --run "$RUN" --section outcome --value "Halted: <reason>"
bash "$RB_SH" set-section --run "$RUN" --section next --json /dev/stdin <<'JSON'
{"label": "Review plan audit status and retry", "command": null}
JSON
<!-- include: _fragments/run-brief-finalize.md -->
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" plan_audit_end \
"$(printf '{"status":"halted","findings":%d,"blockers":%d,"majors":%d}' "${N_FINDINGS:-0}" "${N_BLOCKERS:-0}" "${N_MAJORS:-0}")"
# Halt-finalize teardown: the wrapper alone owns release-before-deregister.
TEARDOWN_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/z-teardown.sh" \
--run "$RUN" --slug "$Z_HARNESS_SLUG" --command /z-audit-plan \
--session "$Z_HARNESS_SESSION_ID" --status aborted || TEARDOWN_RC=$?
if [[ $TEARDOWN_RC -ne 0 ]]; then
printf 'z-audit-plan: halted teardown incomplete (exit %s); registry retained for retry\n' "$TEARDOWN_RC" >&2
exit "$TEARDOWN_RC"
fi
exit 0
Phase 9 — Elevation Proposer
After the user gate in Phase 5 resolves, run the preference elevation check:
PROPOSE_OUT="$(python3 "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/propose-prefs.py" --check z-audit-plan 2>/dev/null)"
If $PROPOSE_OUT is non-empty, parse it as JSON and surface a one-shot preference proposal:
import json
proposal = json.loads(PROPOSE_OUT)
qid = proposal["question_id"]
val = proposal["proposed_value"]
n = len(proposal["evidence"])
scope_rec = proposal["scope_recommendation"]
Emit proposal_surfaced:
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" proposal_surfaced \
"$(python3 -c '
import json, sys
print(json.dumps({"question_id": sys.argv[1], "proposed_value": sys.argv[2], "n_evidence": int(sys.argv[3]), "scope_recommendation": sys.argv[4]}))
' "$qid" "$val" "$n" "$scope_rec")"
Heartbeat before Phase 9 AskUserQuestion (load-bearing — extends TTL before wait):
HB_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/plan-claim.sh" heartbeat \
--slug "$Z_HARNESS_SLUG" --run-id "$RUN" --session "$Z_HARNESS_SESSION_ID" \
--command /z-audit-plan || HB_RC=$?
if [[ $HB_RC -eq 9 ]]; then
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" plan_claim_lost_during_gate \
"$(printf '{"slug":"%s","run_id":"%s","gate":"phase9_elevation"}' "$Z_HARNESS_SLUG" "$RUN")"
# Lost-claim gate at Phase 9 elevation: skip elevation and abort through canonical teardown.
TEARDOWN_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/z-teardown.sh" \
--run "$RUN" --slug "$Z_HARNESS_SLUG" --command /z-audit-plan \
--session "$Z_HARNESS_SESSION_ID" --status aborted || TEARDOWN_RC=$?
if [[ $TEARDOWN_RC -ne 0 ]]; then
printf 'z-audit-plan: aborted teardown incomplete (exit %s); registry retained for retry\n' "$TEARDOWN_RC" >&2
exit "$TEARDOWN_RC"
fi
exit 0
fi
<!-- RUNTIME-GATE: ask_user; category=mechanical_proceed; non-supporting drivers must surface the preference
elevation proposal question via their native channel and accept a reply.
Silent omission is forbidden. -->
Present a single AskUserQuestion:
"You've done
<cmd_a> → z-amendN times — add<val>as your preference for<qid>?"Options:
- config — write to project config (or global if
scope_recommendation=global)- memory:very_strong — store as a very-strong routing-preference memory entry
- memory:strong — store as a strong routing-preference memory entry
- no — suppress this prompt for 30 days
Branch on the user's choice:
config branch:
SCOPE_FLAG="--scope=project"
[ "$scope_rec" = "global" ] && SCOPE_FLAG="--scope=global"
python3 "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/config.py" set workflow.audit_to_amend amend $SCOPE_FLAG
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" proposal_accepted \
"$(printf '{"question_id":"%s","via":"config","scope":"%s"}' "$qid" "$scope_rec")"
memory:very_strong or memory:strong branch:
Dispatch /z-suggest-memory with --kind routing-preference:
/z-suggest-memory --kind routing-preference \
--question-id <qid> \
--value <val> \
--strength <very_strong|strong> \
--scope <scope_recommendation>
Then emit:
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" proposal_accepted \
"$(printf '{"question_id":"%s","via":"memory","strength":"%s","scope":"%s"}' "$qid" "$strength" "$scope_rec")"
no branch:
Write suppression entry with 30-day expiry:
import json, os, time
from pathlib import Path
suppress_path = Path(".z-harness") / ".propose-suppress"
suppress_path.parent.mkdir(parents=True, exist_ok=True)
data = {}
if suppress_path.exists():
try:
data = json.loads(suppress_path.read_text())
except (json.JSONDecodeError, OSError):
data = {}
expiry = time.time() + 30 * 86400
data[qid] = str(expiry)
suppress_path.write_text(json.dumps(data))
Then emit:
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/log-event.sh" "$RUN" proposal_rejected \
"$(printf '{"question_id":"%s","suppressed_until_epoch":"%s"}' "$qid" "$expiry")"
If $PROPOSE_OUT is empty, skip this phase entirely — no question is asked.
Normal-end teardown (after Phase 9 or when Phase 9 is skipped — canonical wrapper is the only release/deregister owner):
TEARDOWN_RC=0
bash "${ANTIGRAVITY_PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/z-teardown.sh" \
--run "$RUN" --slug "$Z_HARNESS_SLUG" --command /z-audit-plan \
--session "$Z_HARNESS_SESSION_ID" --status complete || TEARDOWN_RC=$?
if [[ $TEARDOWN_RC -ne 0 ]]; then
printf 'z-audit-plan: completion teardown incomplete (exit %s); registry retained for retry\n' "$TEARDOWN_RC" >&2
exit "$TEARDOWN_RC"
fi
Operating Principles
- Rigorous Verification: Validate all facts before starting the implementation.
- Push Back on Reviews: Apply the "one reason it might be wrong" check to keep reports high-signal.
- Strictly Read-Only: Never modify the codebase during the audit.
- Format Consistency: No emojis, professional headers, clean Markdown structures.
Runtime contract conformance
| Feature | Used | Gates |
|---|---|---|
subagent | yes | Phase 0 doc-fetcher Agent(); Phase 3 consultant-primary and consultant-secondary Agent() calls |
ask_user | yes | Phase 0 multiple-candidates slug selection; Phase 0 claim contention/takeover gate (proceed / abort) and register-failure gate (proceed without coordination / abort); Phases 1–5 lost-claim gate (abort default / continue-uncoordinated) on heartbeat exit 9; Phase 5 post-audit checkpoint no longer uses AskUserQuestion — both auto_split and force_ask paths emit prose alignment summaries (PLAN_AUDIT_REPORT.md path + recommendation); Phase 9 preference elevation proposal |
skill_invoke | no | — |
Driver support requirements: see frontmatter driver_features_required.
Non-supporting drivers must surface and skip any gated block — silent
omission is forbidden. Each gated call site is annotated with a
<!-- RUNTIME-GATE: ... --> comment immediately before the call.