@deftai/directive-content 0.99.0 → 0.101.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,7 +29,7 @@
29
29
  ],
30
30
  "path": "skills/deft-directive-build/SKILL.md",
31
31
  "version": "0.1",
32
- "body": "# Deft Directive Build\n\nImplements a project from its scope xBRIEFs following Deft Directive standards.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, \u2249=SHOULD NOT, \u2297=MUST NOT, ?=MAY.\n\n## When to Use\n\n- After `deft-directive-setup` completes and generates `PROJECT-DEFINITION.xbrief.json`\n- User says \"build this\", \"implement the spec\", or \"start building\"\n- Resuming a partially-built project that has story xBRIEFs in `xbrief/active/`\n\n## Ordered-plan / cohort exhaustion (#2402)\n\n## Multi-scope turn/cache budget (epic #3009)\n\nMulti-scope greenfield (app-bank pins, N story scopes) multiplies agent turns when ceremony, promote, check, and render are re-run per scope. Apply the following after offline seed.\n\n### Offline seed vs implement phase (#3010)\n\n! Distinguish **offline seed** (operator or harness already ran `directive init` / deposit, pin-copied scopes into `xbrief/proposed/`, and recorded session ritual) from the **agent implement phase**.\n\n! When seed + session ritual are already complete for the engagement:\n- \u2297 Run `directive init` again\n- \u2297 Run full cold `session:start` unless hooks deny writes and recovery is required\n- \u2297 Run `directive migrate` or re-copy scopes already present\n- ! Prefer recovery via `session:ready` (or re-arm) when PreToolUse denies \u2014 not full re-init\n- ! Documented consumer/harness contract: seed is done once; implement agents only activate+implement\n\n### Batch promote; one active implement (#3011)\n\n! For a multi-scope pin, batch-stage scopes with `task scope:promote -- --batch` (all `proposed/`) or `task scope:promote -- --batch <path>\u2026`.\n! Implement path remains **one** `scope:activate` + implement at a time \u2014 no multi-active write fence.\n! When pin order is known, do **not** re-list the entire lifecycle tree every scope; walk the known ordered list.\n\u2297 Activate all scopes at once or drop the one-active-scope / story-ready stack.\n\n### Quality check once at end of multi-scope batch (#3012)\n\n! On an approved multi-scope batch (operator-approved multi-story branch, swarm cohort, or pin walk): run full `task check` (merge chokepoint) **once at the end of the batch** (or after the last scope), not after every scope.\n! Exception: if the last full check **failed**, fix loops MAY re-run check until green.\n! Pre-PR / merge-ready gates remain end-of-unit \u2014 this does not weaken them.\n! Iteration lane (affected tests / `verify:forward-coverage` / `coverage:hotspots`) still applies **per scope** during implementation (#1704).\n\u2297 Spam full `directive check` / `task check` after every scope when the batch is still mid-flight and the last merge-chokepoint check was green.\n\n### One-shot project:render (#3013)\n\n! Greenfield init seeds a minimal render-ready `PROJECT-DEFINITION`. Treat `task project:render` as a **refresh of items from lifecycle folders**, not multi-turn identity research.\n\u2297 Invent project identity across many turns when seed already stamped the skeleton.\n\n\n! When processing an approved multi-story cohort or an active ordered-plan sequence, stop after the final approved entry. Do not promote or dispatch adjacent stories from queue intuition. Continuation language advances only within the approved order; skill-chaining is non-authorizing.\n\n## Step 0 -- Implementation Preflight (#810)\n\n- ! Before starting any new implementation story or switching from one story to another, MUST run `git status --short --branch`.\n- ! If the working tree is dirty, MUST stop and summarize the current branch, modified/untracked files, and whether the changes appear related to the target story. Ask the operator to choose one path: commit existing work, stash existing work, include existing work in the current story, or stop.\n- \u2297 Begin a new story while unrelated dirty work is present without explicit operator approval.\n- ! Resolve exactly one target story xBRIEF path by default. One story is the default implementation unit for this skill; if the user asks for a phase/epic, decompose or ask which story to start.\n- ! Batching multiple stories in one branch/PR requires explicit operator approval and a short rationale recorded in the handoff.\n- ! **Swarm-cohort dispatch carve-out**: when this skill is invoked as part of a swarm cohort allocated by `skills/deft-directive-swarm/SKILL.md`, the approved Phase 5 allocation plan satisfies the \"explicit operator approval and short rationale recorded in the handoff\" requirement above -- the dispatched xBRIEF paths and allocation rationale ARE the consent token. Process each assigned story sequentially under the checkpoint-commit + `task scope:complete` discipline below. Do NOT re-prompt the parent for batching approval mid-cohort -- the all-or-nothing dispatch envelope rule (`AGENTS.md` `## Multi-agent orchestration discipline (#954)`) forbids mid-scope user-approval gates.\n- ! **Structured consent-token recognition (#1378)**: the canonical recognition path for the carve-out above is the structured `## Allocation context` section of the dispatch envelope (the frozen schema in `templates/agent-prompt-preamble.md`, Story A of #1378). When that section reports `dispatch_kind: swarm-cohort` with a non-null `allocation_plan_id` AND a non-null `batching_rationale`, the consent token is satisfied mechanically -- read `cohort_vbriefs` as the authoritative file boundary and process each entry sequentially under the checkpoint-commit + `task scope:complete` discipline below, without re-prompting the parent for batching approval mid-cohort. When the `## Allocation context` section is ABSENT (pre-#1378 dispatches, solo-interactive sessions), fall back to the #1371 prose carve-out immediately above -- the prose carve-out remains the recognition path of record for un-elevated envelopes.\n- ! **Within a cohort, between stories**: the working tree MUST be clean after each story's checkpoint commit + `task scope:complete`. If `git status --short` shows uncommitted state between stories (e.g. a missed `task scope:complete` move, an unstaged file from the prior story), checkpoint-commit it and proceed -- do NOT pause to ask the operator. The dirty-tree \"ask the operator\" branch above applies only at the FIRST story-start of a fresh branch, where uncommitted operator work might legitimately exist.\n- ! If the target story is in `xbrief/proposed/`, run `task scope:promote -- <path>` first (or `task scope:promote -- --batch` for a multi-scope pin \u2014 #3011); if it is in `xbrief/pending/`, run `task scope:activate -- <path>`. After activation, update the path to the active-file location before preflight.\n- ! **Effort estimate gate (#1581):** before `task scope:activate` / `task vbrief:activate`, scan `plan.items` (including nested `items` / `subItems`) for `effort`. Time anchors: `S` <2h, `M` half-day (2-4h), `L` 1-2 days, `XL` needs breakdown. The activate path fails closed while any item still has `effort: \"XL\"` \u2014 break XL work into S/M/L items (or re-estimate) first. Omitted `effort` remains valid (field is optional). Plan-item effort is **post-planning** authority (confirms/corrects intake estimates); it is **not** session-start ritual input \u2014 ceremony depth (#3214) uses two-stage rapid\u2192escalate, not a required plan-item read at cold start. Headless: no operator confirm. Depth: `vbrief/vbrief.md` \u00a7 Effort estimate.\n- \u2297 Activate a scope that still carries plan items with `effort: \"XL\"` \u2014 XL means \"not ready to start\" until broken down (#1581).\n- \u2297 Require plan-item `effort` to choose session-start ritual depth \u2014 estimates do not exist until after planning (#1581 / #3214).\n- ! Before any code-writing tool call -- the first scaffold edit, the first `task` invocation that mutates files, or any `start_agent` dispatch that will implement scope -- MUST run `task xbrief:preflight -- <active-story-path>` (the structural intent gate; wraps `scripts/preflight_implementation.py` so the same invocation works whether deft is the project root or installed as a `deft/` subdirectory).\n\nThe gate exits 0 only when the candidate xBRIEF lives in `xbrief/active/` AND `plan.status == \"running\"`. Any other state (pending/, proposed/, completed/, active/-with-non-running-status, malformed JSON, missing keys) exits 1 with an actionable redirect to `task xbrief:activate <path>`.\n\n- ! A non-zero exit MUST halt the skill. Surface the helper's stderr message verbatim to the user; do NOT proceed to USER.md Gate, File Reading, or any later phase.\n- ! Use canonical lifecycle tasks to satisfy this gate: `task scope:promote -- <path>` for proposed stories, `task scope:activate -- <path>` for pending stories, and the helper's idempotent companion `task xbrief:activate <path>` only when following the preflight redirect directly. Manual lifecycle moves bypass the activation contract -- use the task.\n- \u2297 Infer implementation intent from lifecycle vocabulary (\"do the full PR process\", \"start the work\", \"poller agents\"), branching language, or workflow shape. Workflow-shape vocabulary is NOT authorization to spawn an implementation agent (#810 surfacing event).\n- \u2297 Skip this preflight because the user said \"yes\", \"go\", or \"proceed\" -- affirmative continuation phrases are NOT implementation authorization unless the prior turn explicitly proposed implementation. When intent is ambiguous, ask one targeted question before invoking the gate.\n\n## Platform Detection\n\n! Before resolving any config paths, detect the host OS from your environment context:\n\n| Platform | USER.md default path |\n|--------------------|-------------------------------------------------------------------|\n| Windows | `%APPDATA%\\deft\\USER.md` (e.g. `C:\\Users\\{user}\\AppData\\Roaming\\deft\\USER.md`) |\n| Unix (macOS/Linux) | `~/.config/deft/USER.md` |\n\n- ! If `$DEFT_USER_PATH` is set, it takes precedence on any platform\n\n## Pre-Cutover Detection Guard\n\n! Before proceeding with any build step, detect whether the project uses the pre-v0.20 document model **or was generated by a strategy that emitted non-conformant v0.20 output shape** (the root cause of most \"build fails immediately after spec\" complaints in #1166). Redirect or block with the precise remediation.\n\n### Detection Criteria\n\nA project is **pre-cutover** if ANY of the following are true. This prose mirrors the executable helper in `scripts/_precutover.py`; when in doubt, the helper is canonical.\n\n1. `SPECIFICATION.md` exists and is neither a deprecation redirect nor a current generated spec export. A current generated spec export contains `<!-- Purpose: rendered specification -->` and `<!-- Source of truth: xbrief/specification.xbrief.json -->`, and `xbrief/specification.xbrief.json` plus all five lifecycle folders exist.\n2. `PROJECT.md` exists and contains neither the legacy `<!-- deft:deprecated-redirect -->` sentinel NOR the current `Purpose: deprecation redirect` canonical-banner marker (real content, not a deprecation redirect)\n3. `xbrief/specification.xbrief.json` exists but the lifecycle folders (`xbrief/proposed/`, `xbrief/pending/`, `xbrief/active/`, `xbrief/completed/`, `xbrief/cancelled/`) do NOT exist\n4. Strategy output shape violations (run `task verify-strategy-output` -- the canonical gate -- or the direct form `python .deft/core/scripts/validate_strategy_output.py --project-root <path>` after `deft` install):\n - Any scope xBRIEF under `xbrief/proposed/` (or other lifecycle dirs) lacks the required `YYYY-MM-DD-` date prefix in its filename (e.g. bare `scaffold.xbrief.json`).\n - `xbrief/PROJECT-DEFINITION.xbrief.json` is missing.\n - `xbrief/specification.xbrief.json` exists as a legacy dual-write in a user-generated project. This is tolerated only for the framework source tree or a complete post-cutover full-spec consumer where all lifecycle folders exist and `SPECIFICATION.md` is rendered from `xbrief/specification.xbrief.json`.\n\n### Action on Detection\n\n! If pre-cutover or strategy-nonconformant state is detected, **stop immediately** and display an actionable message that cites the exact validator:\n\n> \"This project was generated with pre-v0.20 or non-conformant strategy output. Run the deterministic validator and follow its remediation: `task verify-strategy-output` (works in source and after `deft` package install) or `python .deft/core/scripts/validate_strategy_output.py --project-root .`. For document-model migration, follow UPGRADING.md \u00a7 Frozen pre-v0.20 document-model migration (#2068): pin v0.59.0, then run `task migrate:vbrief` from that payload. Otherwise `task project:render` / strategy re-run as indicated.\"\n\n! Include specific details about what was detected (the validator output is authoritative):\n\n- Legacy specification.xbrief.json or missing lifecycle folders: \"Follow the frozen v0.59.0 migrator path (#2068) or run `task migrate:preflight` for current-release guidance\"\n- Non-date-prefixed xBRIEFs: \"Re-run the emitting strategy after the v0.20 migrations (#1166 s1+s2+...) or manually rename files to `YYYY-MM-DD-<slug>.xbrief.json` and `task scope:promote`\"\n- Missing `PROJECT-DEFINITION.xbrief.json`: \"Run `task project:render` to generate the project definition\"\n- `SPECIFICATION.md` / `PROJECT.md` without sentinel: the classic pre-cutover messages\n- Scope xBRIEF in wrong folder: \"Status is '{status}' but file is in {folder}/ -- run `task scope:activate <file>` to fix\"\n\n! After the validator reports clean, re-run this guard before continuing.\n\n\u2297 Proceed with build when pre-cutover or strategy-nonconformant artifacts are detected -- always redirect to the frozen migration path first (or run the validator) and surface the exact remediation.\n\u2297 Silently ignore these artifacts or guess at fixes -- the validator (wired into `task check` and this guard) is the deterministic gate.\n\n## USER.md Gate\n\n! Before proceeding, verify USER.md exists at the platform-appropriate path\n(resolved via Platform Detection above, or `$DEFT_USER_PATH` if set).\n\n- ! If USER.md is not found: inform the user and redirect to `deft-directive-setup`\n Phase 1 before continuing -- do not proceed without user preferences\n- ! Once USER.md exists, continue with the Cost Phase Gate below\n\n## Cost Phase Gate (#739)\n\n! Before proceeding to File Reading, verify the project has gone through the\npre-build cost & budget transparency phase from `skills/deft-directive-cost/SKILL.md`.\nThis closes the adoption-blocker surfaced by issue #739 (refs #151 umbrella) where\nusers finished the spec flow and stopped at build because deft offered no cost\nsignal.\n\n### Detection\n\n- ! Check for `COST-ESTIMATE.md` in the project root.\n- ! Check that the file contains a recorded decision (the **Decision recorded**\n block populated with one of: `build`, `rescope`, `no-build`, `skip`).\n- ! For `skip`, `rescope`, or `no-build` decisions: the **Reason** field MUST be\n populated (one or two sentences in plain language). A skip with no reason\n recorded is treated the same as no decision.\n\n### Action\n\n- ! If `COST-ESTIMATE.md` is missing OR the **Decision recorded** block is\n unpopulated OR a `skip`/`rescope`/`no-build` decision has no reason recorded:\n stop immediately and redirect the user:\n\n > \"This project has not gone through the pre-build cost & budget transparency\n > phase. Run `skills/deft-directive-cost/SKILL.md` to produce a plain-English\n > `COST-ESTIMATE.md`, then re-run the build skill once the user has chosen\n > build / rescope / no-build / skip(+reason).\"\n\n- ! On a `build` or `skip` decision: continue with File Reading below.\n- ! On a `rescope` decision: stop and redirect the user back to spec edits\n (chain to `skills/deft-directive-refinement/SKILL.md` to pull spec scope\n back, or the interview), then re-run `skills/deft-directive-cost/SKILL.md`\n before re-attempting build.\n- ! On a `no-build` decision: stop and exit; do NOT proceed to File Reading.\n The user has explicitly stopped the project at the cost phase.\n- \u2297 Proceed to File Reading or any subsequent phase when `COST-ESTIMATE.md` is\n missing, when the decision is unpopulated, or when a skip / rescope / no-build\n decision has no reason recorded.\n- \u2297 Treat a `rescope` or `no-build` decision as if it were a `build` -- the\n build skill MUST honor the recorded decision.\n\n## File Reading\n\n- ! Read in order, lazy load:\n 1. `./xbrief/active/` -- scope xBRIEFs for work items to build (required)\n 2. `./xbrief/PROJECT-DEFINITION.xbrief.json` -- project identity, tech stack, architecture\n 3. `./.planning/codebase/MAP.md` -- generated codebase orientation projection, if present (advisory)\n 4. USER.md at the platform-appropriate path (see Platform Detection) -- Personal section is highest precedence; Defaults are fallback\n 5. `deft/main.md` -- framework guidelines\n 6. `deft/coding/coding.md` -- coding standards\n 7. `deft/coding/testing.md` -- testing requirements\n 8. `deft/coding/toolchain.md` -- toolchain validation rules\n 9. `deft/languages/{language}.md` -- only for languages this project uses\n- ~ If the MAP is absent or may be stale and the current scope needs broad codebase orientation, run `task codebase:map` and `task verify:codebase-map-fresh` when those commands resolve. Treat absence/staleness as advisory unless the task edits `plan.architecture.codeStructure`, a configured provider artifact, or the generated MAP itself.\n- ! Treat `plan.architecture.codeStructure` and selected provider artifacts as authoritative. The MAP is a generated projection.\n- \u2297 Read all language/interface/tool files upfront\n- \u2297 Hand-edit `.planning/codebase/MAP.md` or block unrelated implementation solely because the MAP is stale or absent\n\n## Rule Precedence\n\n```\nUSER.md Personal <- HIGHEST (name, custom rules -- always wins)\nPROJECT-DEFINITION.xbrief.json <- Project-specific (tech stack, architecture, config)\nUSER.md Defaults <- Fallback defaults (used when PROJECT-DEFINITION doesn't specify)\n{language}.md <- Language standards\ncoding.md <- General coding\nmain.md <- Framework defaults\nScope xBRIEFs <- LOWEST\n```\n\n- ! USER.md Personal section always wins over any other file\n- ! For project-scoped settings, PROJECT-DEFINITION.xbrief.json overrides USER.md Defaults\n\n## Change Lifecycle Gate\n\n! Before any implementation that touches 3+ files, verify that a `/deft:change <name>` proposal exists and has been confirmed by the user:\n\n- ! Check `history/changes/` for an active `proposal.xbrief.json` matching this work\n- ! If no proposal exists: propose `/deft:change <name>` and present the change name for explicit confirmation (e.g. \"Confirm? yes/no\")\n- ! The user must reply with an affirmative (`yes`, `confirmed`, `approve`) \u2014 a general 'proceed', 'do it', or 'go ahead' does NOT satisfy this gate\n- ? For solo projects: this gate is RECOMMENDED but not mandatory for changes fully covered by `task check`; it remains mandatory for cross-cutting, architectural, or high-risk changes\n- \u2297 Skip this gate because the user has already said \"proceed\" or \"go ahead\"\n\n## Build Process\n\nAll xBRIEFs (including those read from `xbrief/active/` and any new xBRIEFs this skill emits) MUST use `\"xBRIEFInfo\": { \"version\": \"0.6\" }`. The validator rejects any other version (see [`../../conventions/references.md`](../../conventions/references.md)).\n\n### Step 1: Understand the Scope\n\n- ! Read story xBRIEFs from `xbrief/active/` and `PROJECT-DEFINITION.xbrief.json`\n- ! Identify phases, dependencies, starting point from scope xBRIEF acceptance criteria\n- ~ Use `.planning/codebase/MAP.md`, when present, to orient broad codebase scanning. If the MAP conflicts with current code or canonical metadata, surface the drift and trust `plan.architecture.codeStructure` / provider artifacts plus the working tree over generated prose.\n- ! When scanning the existing codebase during scope understanding, MUST surface any contradicting patterns (two error-handling shapes, two state-management approaches, two naming conventions, etc.) before implementation begins -- apply `coding/hygiene.md` `## Surface Conflicts: Pick One, Explain, Flag the Other (#1005)` and choose ONE pattern (more recent OR more tested), explain the choice in the scope summary, and flag the other for cleanup\n- \u2297 Begin implementation against an averaged blend of two contradicting patterns -- \"average code that satisfies both rules is the worst code\" (#1005)\n- ! Present brief summary to user:\n\n> \"Here's what I see: {N} story xBRIEFs in active/. I'll start with {name}. Ready?\"\n\n### Step 2: Verify Toolchain\n\n- ! Before any implementation, verify all tools required by this project are installed and functional \u2014 see `deft/coding/toolchain.md` for full rules\n- ! At minimum: confirm task runner (`task --version`), language compiler/runtime, and platform SDK (if applicable) are available\n- ! If any required tool is missing, stop and report \u2014 do not proceed to Step 3\n- \u2297 Assume tools are available because the spec references them\n\n### Gate throughput \u2014 iteration fast lane vs merge chokepoint (#1704)\n\n> **Invariant:** every change MUST pass the full gate at least once before merge. Iteration MAY use a cheaper proxy; the merge chokepoint MUST NOT be skipped.\n\n- ! **Iteration lane (agents + humans):** during implementation commits, use affected/static gates \u2014 targeted tests on changed paths (`vitest run --coverage <paths>` or project equivalent), static `verify:*` gates relevant to touched files, and `task coverage:hotspots` / `task verify:forward-coverage` \u2014 NOT full `task check` on every commit.\n- ! **Merge chokepoint:** run full `task check` (or `task check:merge` in the framework source repo) once before push/PR and again when CI merge gate runs. Pre-PR skill exit and review-cycle fix batches still require a green full gate.\n- ! **Escape-rate safety (#1703 Tier-1):** before tightening fast-lane defaults fleet-wide, consult `#1703` measurement \u2014 `task eval:health` (Tier 0) and Tier-1 session telemetry (`helped/crud-metrics.jsonl` via instrumented CRUD / workflow metrics). Do NOT invent a separate fast-lane escape-rate surface (#1704 LockedDecisions).\n- ~ **In-engine incrementality (#1713):** content-hash task cache and runner-delegated affected selection are sibling work \u2014 not required for this policy face.\n- \u2297 Run full `task check` on every iteration commit when a cheaper proxy suffices \u2014 reserve the full gate for PR/merge (#1704).\n- \u2297 Skip the merge chokepoint because the iteration lane passed \u2014 the fast lane is convenience only.\n\n**Cost model (swarm-heavy path):** moves from roughly `O(commits \u00d7 full-gate)` toward `O(merges \u00d7 full-gate) + O(iterations \u00d7 cheap-proxy)` when workers iterate with affected/static gates and run full `task check` only at PR/merge.\n\n### Dual stop \u2014 multi-iteration implement and pre-PR loops (#2442)\n\nMulti-iteration implement-fix and pre-PR polish loops MUST carry **both** a success stop and a failure/budget stop (`main.md` `## Dual Stop Rule (#2442)`). Single-turn edits and one-shot probes are exempt.\n\n**Defaults for this skill (override only with an explicit operator envelope or xBRIEF field):**\n\n| Loop class | Success stop | Default failure stop |\n|------------|--------------|----------------------|\n| Implement / quality fix (tests, lint, typecheck, coverage, AC) | Affected/static gates green for the change; AC met | **max 5** fix iterations **or** **3** consecutive identical outcomes (same failing command + same primary error class) with no material code/config change |\n| Pre-PR polish (`deft-directive-pre-pr` Read-Write-Lint-Diff) | Full pass with zero further edits | **max 3** polish passes **or** **2** consecutive no-diff / same-diff outcomes |\n| Full `task check` re-run after a red merge chokepoint | `task check` green | Counts toward the implement/quality fix envelope above (do not open a separate unbounded check-retry loop) |\n\n**On failure stop:**\n\n- ! Halt the loop. Surface an **operator-visible halt report** with: (1) iterations attempted and which stop fired (max-iter / no-progress / budget), (2) commands and primary failure fingerprints tried, (3) what is still red or missing, (4) the human decision needed (unblock dependency, rescope AC, waive with audit, abandon).\n- ! Prefer a structured `BLOCKED:` terminal (preamble \u00a711 / #2843) when exiting a drive-to:merge-ready or parent-dispatched unit early because the envelope is exhausted.\n- \u2297 Continue \"one more fix\" after the envelope is exhausted.\n- \u2297 Reset the counter by opening a new commit, rewording the same change, or swapping workers while the same failure class remains.\n\n**Enforcement note:** skill defaults are behavioral. Durable delivery/acceptance circuit-breaker: **#3143** `packages/core/src/delivery-attempt/` (`evaluatePreDispatch`, `.deft/delivery-attempts/`). Docs: `docs/delivery-attempt.md`. Route delivery/acceptance automatic retries through that gate; do not invent a parallel ledger in this skill.\n\n## Step 3: Build Phase by Phase\n\nFor each phase:\n\n1. ! **Scaffold** \u2014 file structure, dependencies, config\n2. ! **Test first** \u2014 write tests before implementation (TDD)\n3. ! **Implement** \u2014 make tests pass, following deft coding standards\n4. ! **Verify (iteration lane)** \u2014 run affected/static gates per `#1704` fast lane above; fix failures before checkpoint commits\n5. ! **Origin sync** \u2014 when this phase materially changed an origin-linked scope xBRIEF (`plan.references` includes `x-xbrief/github-issue`), run `task issue:sync-from-xbrief -- <path>` (or `--dry-run` to preview) so the linked GitHub issue receives a sync comment; if skipped, document why in the PR or session notes (#2540)\n6. ! **Checkpoint** \u2014 tell user what's done, what's next\n\n- \u2297 Move to next phase until current phase passes all checks\n\n### Step 4: Quality Gates\n\nAfter EVERY phase (iteration lane \u2014 #1704):\n\n```bash\nvitest run --coverage <changed-paths> # or project test runner on touched modules\ntask coverage:hotspots # branch headroom before merge\ntask verify:forward-coverage # new-source coverage (#1310)\n```\n\nBefore PR / phase handoff (merge chokepoint):\n\n```bash\ntask check # Full gate \u2014 format, lint, typecheck, tests, coverage, verify:*\ntask test:coverage # >=85% or PROJECT-DEFINITION.xbrief.json override\n```\n\n- ! Phase checkpoint commits MAY use the iteration lane; phase is NOT done for PR handoff until full `task check` passes at the merge chokepoint\n- \u2297 Skip quality gates or claim they passed without running\n- \u2297 Treat iteration-lane green as merge-ready without full `task check`\n- ! **Multi-scope batch (#3012):** when implementing an approved multi-scope pin/cohort, reserve full `task check` for end-of-batch (or after last scope) unless the last full check failed \u2014 then re-run on the fix loop. Do not run full check after every intermediate scope.\n- \u2297 Re-run full install/session ceremony after offline seed when ritual is already complete (#3010) \u2014 use `session:ready` for recovery only.\n\n\n## Operator-log hygiene (lazy-load, #1940)\n\nWhen the story touches **operator-facing** services (dashboards, multi-process\nworkers, WARN/ERROR operators triage):\n\n- ~ SHOULD load `patterns/operator-log-hygiene.md` and apply the copy-paste\n checklist in `docs/operator-log-hygiene-checklist.md` to story AC or probe\n locked decisions before claiming logging done\n- \u2297 MUST NOT treat this as Product Insights (#2603) or LLM-call telemetry\n (#481) \u2014 those are different lanes\n- \u2297 MUST NOT assume core `deft check` enforces a log schema by default \u2014\n consumer-owned shape; optional pack stub under\n `docs/operator-log-hygiene-consumer-pack-stub.md`\n\nDiscovery keywords: operator log, operator-facing logs, observability checklist\n\u2014 also indexed in `REFERENCES.md`.\n\n## Goal-gate determinism (lazy-load, #852)\n\nWhen authoring or tightening story acceptance criteria, quality gates, or skill\nsteps during build:\n\n- ~ SHOULD load `patterns/goal-gate-determinism.md` \u2014 goals, AC, gates, exit,\n scope, stop, and preserve are rigid; pure execution path is flexible guidance\n- \u2297 MUST NOT treat \"all process steps done\" as verification \u2014 outcomes and\n gates own \"done\" (see also `verification/verification.md` and Fail Loud #1006)\n\nDiscovery keywords: goal-gate-determinism, rigid goals flexible path \u2014 also\nindexed in `REFERENCES.md`.\n\n## Coding Standards (Summary)\n\nRead full files when you need detail:\n\n- ! TDD: write tests first \u2014 implementation incomplete without passing tests\n- ! Coverage: \u226585% lines, functions, branches, statements\n- ~ Files: <300 lines ideal, <500 recommended, ! <1000 max\n- ~ Naming: hyphens for filenames unless language idiom dictates otherwise\n- ! Contracts first: define interfaces/types before implementation\n- ! Secrets: in `secrets/` dir with `.example` templates; \u2297 secrets in code\n- ! Commits: Conventional Commits format; ! use iteration fast lane before checkpoint commits; ! run full `task check` at PR/merge chokepoint only (#1704)\n\nSee `deft/coding/coding.md` and `deft/coding/testing.md` for full rules.\n\n## Pre-Commit File Review\n\n! Before every commit, re-read ALL modified files and explicitly check for:\n\n1. ! **Encoding errors** -- em-dashes corrupted to replacement characters, BOM artifacts, mojibake from round-trip read/write\n2. ! **Unintended duplication** -- accidental double entries in CHANGELOG.md, scope xBRIEF files, or structured data files\n3. ! **Structural issues** -- malformed CHANGELOG entries, broken table rows, mismatched index entries, invalid JSON/YAML\n4. ! **Semantic accuracy** -- verify that counts, claims, and summaries in CHANGELOG entries and ROADMAP changelog lines match the actual data in the commit (e.g. \"triaged 4 issues\" must match the number actually triaged, issue numbers cited must match the issues actually added)\n5. ! **Semantic contradictions** -- when adding a `!` or `\u2297` rule that prohibits a specific command, pattern, or behavior, search the same file for any `~`, `\u2248\u0338`, or prose that recommends or permits the same command/pattern -- resolve all contradictions in the same commit before pushing\n6. ! **Strength duplicates** -- when strengthening a rule (e.g. upgrading `~` to `!`), grep for the term in the full file and verify no weaker-strength duplicate remains\n7. ! **Forward test coverage** -- for each new source file in this PR (`scripts/`, `src/`, `cmd/`, `*.py`, `*.go`), verify a corresponding test file exists in the same PR; running existing tests is not sufficient for new code\n\n\u2297 Commit without re-reading all modified files first.\n\n## Commit Strategy\n\n- ! Default to one story per branch/PR. Batching multiple stories in one branch requires explicit operator approval and a short rationale.\n- ! Create a checkpoint commit after each completed story before beginning another story.\n- ! Use iteration fast lane before checkpoint commits; run full `task check` at PR/merge chokepoint (#1704)\n- \u2297 Claim checks passed without running them\n\n```\nfeat(phase-1): scaffold project structure\nfeat(phase-1): implement core data models with tests\nfeat(phase-2): add REST API endpoints with integration tests\n```\n\n## Error Recovery\n\n- ! Tests fail \u2192 fix them; \u2297 skip or weaken assertions\n- ! Coverage drops \u2192 write more tests; \u2297 exclude files\n- ! Lint/type errors \u2192 fix them; \u2249 add ignore comments without documented reason\n- ! Scope xBRIEF ambiguous -> ask user; \u2297 guess\n- ! Scope needs changes -> propose, get approval, update the scope xBRIEF first\n- ! Multi-iteration fix loops obey dual-stop defaults above (#2442); on envelope exhaustion halt with an operator-visible report -- do not thrash\n\n\n## Probe-then-fill remote claims (#3120)\n\n! Before filling any **remote** handoff field (PR URL, PR number, commit/HEAD SHA, CI green/success, review score) or claiming `status: pass` / ship/gate done, MUST **probe then fill**:\n\n1. Run same-turn `git` + forge probes (examples: `git rev-parse HEAD`, `gh api repos/<owner>/<repo>/pulls/<N>`, `task pr:watch -- <N> --one-shot`, checks API).\n2. Copy IDs / URLs / SHAs / scores **only** from that probe JSON/text into the evidence block.\n3. Set `proof_status: bound` and attach short raw probe snippets (`command` + `snippet`) for each remote claim.\n\n! Handoff evidence axes: **work** (local) / **ship** (pushed branch or PR) / **gate** (CI/review on HEAD). `proof_status` is `bound` | `unbound` | `n/a-no-remote-claim`.\n! **Legal partial:** local work `done` + ship `not_started` / `blocked` **without** PR/SHA/CI/review fields and `proof_status: n/a-no-remote-claim` (or `status: partial`) is valid \u2014 do not invent ship state.\n! **Fail ranking:** **invented-done** (false/unbound remote artifacts under pass) is **stricter** than **empty-done**. Unbound remote claims \u2192 invalid evidence (fail), not pass-with-notes.\n! Machine check: `validateHandoffEvidence` in `packages/core/src/handoff-evidence/` (see `templates/agent-prompt-preamble.md` \u00a711).\n\u2297 Fill PR / SHA / CI / review fields from recollection, narration, or prior-turn memory.\n\u2297 Claim `status: pass` with remote fields when `proof_status` is not `bound` or probes are missing (#3120).\n\n## Completion\n\n- ! When all phases pass and `task check` is green, complete each implemented story via `task scope:complete -- <active-story-path>` before final PR handoff.\n\n> \"The project is built and all quality checks pass. Describe any new features you'd like to add \u2014 I'll follow the deft standards we've set up.\"\n\n\n## Significant decision log (#1396)\n\n! When this scope makes a **significant** choice (architecture, product behavior, security, public/private boundary, data model, runtime topology, hard-to-reverse process), record it with `task decision:write` (or `--body-file` for multi-line fields) so later agents load rationale without inventing it.\n\n~ Prefer attaching with `--scope <active-xbrief>` when the decision is bound to this story; use standalone `xbrief/decisions/` for cross-cutting / multi-scope process choices.\n\n~ Before claiming a process/architecture path was 'already decided', run `task decision:list -- --query <topic>` (or `--issue N`).\n\n\u2297 Require a decision record for every trivial scope or routine fix.\n\u2297 Merge lessons (#1513) into decision records, or replace ADRs under `docs/decisions/ADR-*.md`.\n\nDocs: `docs/decision-log.md` \u00b7 `xbrief/decisions/README.md`.\n\n## Anti-Patterns\n\n- \u2297 Skip tests or write them after implementation\n- \u2297 Ignore `task check` failures\n- \u2297 Implement things not in scope xBRIEF without asking\n- \u2297 Read every deft file upfront\n- \u2297 Move to next phase before current passes checks\n- \u2297 Make commits without running iteration-lane validation; \u2297 skip full `task check` at PR/merge chokepoint (#1704)\n- \u2297 Proceed without USER.md -- always run the USER.md Gate first\n- \u2297 Re-run `directive init`, cold `session:start`, migrate, or re-copy pin scopes after offline seed when ritual is already complete (#3010)\n- \u2297 Run full `task check` after every intermediate scope of an approved multi-scope batch when the last merge-chokepoint check was green (#3012)\n- \u2297 Promote scopes one-by-one for a known multi-scope pin when `scope:promote --batch` would stage them in one turn (#3011)\n\n- \u2297 Spawn an implementation agent or invoke a code-writing tool against a xBRIEF that has not passed `task xbrief:preflight` (which wraps `scripts/preflight_implementation.py`) -- always run the Step 0 Implementation Preflight (#810) first; satisfy via `task xbrief:activate <path>`\n- \u2297 Proceed without `COST-ESTIMATE.md` and a recorded build / rescope / no-build / skip(+reason) decision -- always run the Cost Phase Gate (#739) first\n- \u2297 Proceed with implementation when the build or test toolchain is unavailable -- always run the Toolchain Gate (Step 2) first\n- \u2297 Proceed to next task or phase without tests passing -- testing is a hard gate, not a cleanup step\n- \u2297 Skip the Change Lifecycle Gate because the user said \"proceed\" -- broad approval does not satisfy the confirmation gate\n- \u2297 Commit or push directly to the default branch -- always create a feature branch first. Exception: user explicitly instructs a direct commit, or `PROJECT-DEFINITION.xbrief.json` narratives contain `Allow direct commits to master: true`\n- \u2297 Add a prohibition (`!` or `\u2297`) without scanning the same file for conflicting softer-strength rules (`~`, `\u2249`) that reference the same term\n- \u2297 Invent remote PR/SHA/CI/review claims in handoff evidence without same-turn probe binding \u2014 invented-done (#3120)\n- \u2297 Fill remote ship/gate fields from memory when only local work completed; legal partial omits PR fields (#3120)\n- \u2297 Run multi-iteration implement / pre-PR loops without a failure stop (max iterations and/or no-progress) or without an operator-visible halt report when the envelope is exhausted (#2442)\n- \u2297 Silently continue after dual-stop failure halt \u2014 escalate; do not thrash (#2442)\n",
32
+ "body": "# Deft Directive Build\n\nImplements a project from its scope xBRIEFs following Deft Directive standards.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, \u2249=SHOULD NOT, \u2297=MUST NOT, ?=MAY.\n\n## When to Use\n\n- After `deft-directive-setup` completes and generates `PROJECT-DEFINITION.xbrief.json`\n- User says \"build this\", \"implement the spec\", or \"start building\"\n- Resuming a partially-built project that has story xBRIEFs in `xbrief/active/`\n\n## Ordered-plan / cohort exhaustion (#2402)\n\n## Multi-scope turn/cache budget (epic #3009)\n\nMulti-scope greenfield (app-bank pins, N story scopes) multiplies agent turns when ceremony, promote, check, and render are re-run per scope. Apply the following after offline seed.\n\n### Offline seed vs implement phase (#3010)\n\n! Distinguish **offline seed** (operator or harness already ran `directive init` / deposit, pin-copied scopes into `xbrief/proposed/`, and recorded session ritual) from the **agent implement phase**.\n\n! When seed + session ritual are already complete for the engagement:\n- \u2297 Run `directive init` again\n- \u2297 Run full cold `session:start` unless hooks deny writes and recovery is required\n- \u2297 Run `directive migrate` or re-copy scopes already present\n- ! Prefer recovery via `session:ready` (or re-arm) when PreToolUse denies \u2014 not full re-init\n- ! Documented consumer/harness contract: seed is done once; implement agents only activate+implement\n\n### Batch promote; one active implement (#3011)\n\n! For a multi-scope pin, batch-stage scopes with `task scope:promote -- --batch` (all `proposed/`) or `task scope:promote -- --batch <path>\u2026`.\n! Implement path remains **one** `scope:activate` + implement at a time \u2014 no multi-active write fence.\n! When pin order is known, do **not** re-list the entire lifecycle tree every scope; walk the known ordered list.\n\u2297 Activate all scopes at once or drop the one-active-scope / story-ready stack.\n\n### Quality check once at end of multi-scope batch (#3012)\n\n! On an approved multi-scope batch (operator-approved multi-story branch, swarm cohort, or pin walk): run full `task check` (merge chokepoint) **once at the end of the batch** (or after the last scope), not after every scope.\n! Exception: if the last full check **failed**, fix loops MAY re-run check until green.\n! Pre-PR / merge-ready gates remain end-of-unit \u2014 this does not weaken them.\n! Iteration lane (affected tests / `verify:forward-coverage` / `coverage:hotspots`) still applies **per scope** during implementation (#1704).\n\u2297 Spam full `directive check` / `task check` after every scope when the batch is still mid-flight and the last merge-chokepoint check was green.\n\n### One-shot project:render (#3013)\n\n! Greenfield init seeds a minimal render-ready `PROJECT-DEFINITION`. Treat `task project:render` as a **refresh of items from lifecycle folders**, not multi-turn identity research.\n\u2297 Invent project identity across many turns when seed already stamped the skeleton.\n\n\n! When processing an approved multi-story cohort or an active ordered-plan sequence, stop after the final approved entry. Do not promote or dispatch adjacent stories from queue intuition. Continuation language advances only within the approved order; skill-chaining is non-authorizing.\n\n## Step 0 -- Implementation Preflight (#810)\n\n- ! Before starting any new implementation story or switching from one story to another, MUST run `git status --short --branch`.\n- ! If the working tree is dirty, MUST stop and summarize the current branch, modified/untracked files, and whether the changes appear related to the target story. Ask the operator to choose one path: commit existing work, stash existing work, include existing work in the current story, or stop.\n- \u2297 Begin a new story while unrelated dirty work is present without explicit operator approval.\n- ! Resolve exactly one target story xBRIEF path by default. One story is the default implementation unit for this skill; if the user asks for a phase/epic, decompose or ask which story to start.\n- ! Batching multiple stories in one branch/PR requires explicit operator approval and a short rationale recorded in the handoff.\n- ! **Swarm-cohort dispatch carve-out**: when this skill is invoked as part of a swarm cohort allocated by `skills/deft-directive-swarm/SKILL.md`, the approved Phase 5 allocation plan satisfies the \"explicit operator approval and short rationale recorded in the handoff\" requirement above -- the dispatched xBRIEF paths and allocation rationale ARE the consent token. Process each assigned story sequentially under the checkpoint-commit + `task scope:complete` discipline below. Do NOT re-prompt the parent for batching approval mid-cohort -- the all-or-nothing dispatch envelope rule (`AGENTS.md` `## Multi-agent orchestration discipline (#954)`) forbids mid-scope user-approval gates.\n- ! **Structured consent-token recognition (#1378)**: the canonical recognition path for the carve-out above is the structured `## Allocation context` section of the dispatch envelope (the frozen schema in `templates/agent-prompt-preamble.md`, Story A of #1378). When that section reports `dispatch_kind: swarm-cohort` with a non-null `allocation_plan_id` AND a non-null `batching_rationale`, the consent token is satisfied mechanically -- read `cohort_vbriefs` as the authoritative file boundary and process each entry sequentially under the checkpoint-commit + `task scope:complete` discipline below, without re-prompting the parent for batching approval mid-cohort. When the `## Allocation context` section is ABSENT (pre-#1378 dispatches, solo-interactive sessions), fall back to the #1371 prose carve-out immediately above -- the prose carve-out remains the recognition path of record for un-elevated envelopes.\n- ! **Within a cohort, between stories**: the working tree MUST be clean after each story's checkpoint commit + `task scope:complete`. If `git status --short` shows uncommitted state between stories (e.g. a missed `task scope:complete` move, an unstaged file from the prior story), checkpoint-commit it and proceed -- do NOT pause to ask the operator. The dirty-tree \"ask the operator\" branch above applies only at the FIRST story-start of a fresh branch, where uncommitted operator work might legitimately exist.\n- ! If the target story is in `xbrief/proposed/`, run `task scope:promote -- <path>` first (or `task scope:promote -- --batch` for a multi-scope pin \u2014 #3011); if it is in `xbrief/pending/`, run `task scope:activate -- <path>`. After activation, update the path to the active-file location before preflight.\n- ! **Effort estimate gate (#1581):** before `task scope:activate` / `task vbrief:activate`, scan `plan.items` (including nested `items` / `subItems`) for `effort`. Time anchors: `S` <2h, `M` half-day (2-4h), `L` 1-2 days, `XL` needs breakdown. The activate path fails closed while any item still has `effort: \"XL\"` \u2014 break XL work into S/M/L items (or re-estimate) first. Omitted `effort` remains valid (field is optional). Plan-item effort is **post-planning** authority (confirms/corrects intake estimates); it is **not** session-start ritual input \u2014 ceremony depth (#3214) uses two-stage rapid\u2192escalate, not a required plan-item read at cold start. Headless: no operator confirm. Depth: `vbrief/vbrief.md` \u00a7 Effort estimate.\n- \u2297 Activate a scope that still carries plan items with `effort: \"XL\"` \u2014 XL means \"not ready to start\" until broken down (#1581).\n- \u2297 Require plan-item `effort` to choose session-start ritual depth \u2014 estimates do not exist until after planning (#1581 / #3214).\n- ! Before any code-writing tool call -- the first scaffold edit, the first `task` invocation that mutates files, or any `start_agent` dispatch that will implement scope -- MUST run `task xbrief:preflight -- <active-story-path>` (the structural intent gate; wraps `scripts/preflight_implementation.py` so the same invocation works whether deft is the project root or installed as a `deft/` subdirectory).\n\nThe gate exits 0 only when the candidate xBRIEF lives in `xbrief/active/` AND `plan.status == \"running\"`. Any other state (pending/, proposed/, completed/, active/-with-non-running-status, malformed JSON, missing keys) exits 1 with an actionable redirect to `task xbrief:activate <path>`.\n\n- ! A non-zero exit MUST halt the skill. Surface the helper's stderr message verbatim to the user; do NOT proceed to USER.md Gate, File Reading, or any later phase.\n- ! Use canonical lifecycle tasks to satisfy this gate: `task scope:promote -- <path>` for proposed stories, `task scope:activate -- <path>` for pending stories, and the helper's idempotent companion `task xbrief:activate <path>` only when following the preflight redirect directly. Manual lifecycle moves bypass the activation contract -- use the task.\n- \u2297 Infer implementation intent from lifecycle vocabulary (\"do the full PR process\", \"start the work\", \"poller agents\"), branching language, or workflow shape. Workflow-shape vocabulary is NOT authorization to spawn an implementation agent (#810 surfacing event).\n- \u2297 Skip this preflight because the user said \"yes\", \"go\", or \"proceed\" -- affirmative continuation phrases are NOT implementation authorization unless the prior turn explicitly proposed implementation. When intent is ambiguous, ask one targeted question before invoking the gate.\n\n## Platform Detection\n\n! Before resolving any config paths, detect the host OS from your environment context:\n\n| Platform | USER.md default path |\n|--------------------|-------------------------------------------------------------------|\n| Windows | `%APPDATA%\\deft\\USER.md` (e.g. `C:\\Users\\{user}\\AppData\\Roaming\\deft\\USER.md`) |\n| Unix (macOS/Linux) | `~/.config/deft/USER.md` |\n\n- ! If `$DEFT_USER_PATH` is set, it takes precedence on any platform\n\n## Pre-Cutover Detection Guard\n\n! Before proceeding with any build step, detect whether the project uses the pre-v0.20 document model **or was generated by a strategy that emitted non-conformant v0.20 output shape** (the root cause of most \"build fails immediately after spec\" complaints in #1166). Redirect or block with the precise remediation.\n\n### Detection Criteria\n\nA project is **pre-cutover** if ANY of the following are true. This prose mirrors the executable helper in `scripts/_precutover.py`; when in doubt, the helper is canonical.\n\n1. `SPECIFICATION.md` exists and is neither a deprecation redirect nor a current generated spec export. A current generated spec export contains `<!-- Purpose: rendered specification -->` and `<!-- Source of truth: xbrief/specification.xbrief.json -->`, and `xbrief/specification.xbrief.json` plus all five lifecycle folders exist.\n2. `PROJECT.md` exists and contains neither the legacy `<!-- deft:deprecated-redirect -->` sentinel NOR the current `Purpose: deprecation redirect` canonical-banner marker (real content, not a deprecation redirect)\n3. `xbrief/specification.xbrief.json` exists but the lifecycle folders (`xbrief/proposed/`, `xbrief/pending/`, `xbrief/active/`, `xbrief/completed/`, `xbrief/cancelled/`) do NOT exist\n4. Strategy output shape violations (run `task verify-strategy-output` -- the canonical gate -- or the direct form `python .deft/core/scripts/validate_strategy_output.py --project-root <path>` after `deft` install):\n - Any scope xBRIEF under `xbrief/proposed/` (or other lifecycle dirs) lacks the required `YYYY-MM-DD-` date prefix in its filename (e.g. bare `scaffold.xbrief.json`).\n - `xbrief/PROJECT-DEFINITION.xbrief.json` is missing.\n - `xbrief/specification.xbrief.json` exists as a legacy dual-write in a user-generated project. This is tolerated only for the framework source tree or a complete post-cutover full-spec consumer where all lifecycle folders exist and `SPECIFICATION.md` is rendered from `xbrief/specification.xbrief.json`.\n\n### Action on Detection\n\n! If pre-cutover or strategy-nonconformant state is detected, **stop immediately** and display an actionable message that cites the exact validator:\n\n> \"This project was generated with pre-v0.20 or non-conformant strategy output. Run the deterministic validator and follow its remediation: `task verify-strategy-output` (works in source and after `deft` package install) or `python .deft/core/scripts/validate_strategy_output.py --project-root .`. For document-model migration, follow UPGRADING.md \u00a7 Frozen pre-v0.20 document-model migration (#2068): pin v0.59.0, then run `task migrate:vbrief` from that payload. Otherwise `task project:render` / strategy re-run as indicated.\"\n\n! Include specific details about what was detected (the validator output is authoritative):\n\n- Legacy specification.xbrief.json or missing lifecycle folders: \"Follow the frozen v0.59.0 migrator path (#2068) or run `task migrate:preflight` for current-release guidance\"\n- Non-date-prefixed xBRIEFs: \"Re-run the emitting strategy after the v0.20 migrations (#1166 s1+s2+...) or manually rename files to `YYYY-MM-DD-<slug>.xbrief.json` and `task scope:promote`\"\n- Missing `PROJECT-DEFINITION.xbrief.json`: \"Run `task project:render` to generate the project definition\"\n- `SPECIFICATION.md` / `PROJECT.md` without sentinel: the classic pre-cutover messages\n- Scope xBRIEF in wrong folder: \"Status is '{status}' but file is in {folder}/ -- run `task scope:activate <file>` to fix\"\n\n! After the validator reports clean, re-run this guard before continuing.\n\n\u2297 Proceed with build when pre-cutover or strategy-nonconformant artifacts are detected -- always redirect to the frozen migration path first (or run the validator) and surface the exact remediation.\n\u2297 Silently ignore these artifacts or guess at fixes -- the validator (wired into `task check` and this guard) is the deterministic gate.\n\n## USER.md Gate\n\n! Before proceeding, verify USER.md exists at the platform-appropriate path\n(resolved via Platform Detection above, or `$DEFT_USER_PATH` if set).\n\n- ! If USER.md is not found: inform the user and redirect to `deft-directive-setup`\n Phase 1 before continuing -- do not proceed without user preferences\n- ! Once USER.md exists, continue with the Cost Phase Gate below\n\n## Cost Phase Gate (#739)\n\n! Before proceeding to File Reading, verify the project has gone through the\npre-build cost & budget transparency phase from `skills/deft-directive-cost/SKILL.md`.\nThis closes the adoption-blocker surfaced by issue #739 (refs #151 umbrella) where\nusers finished the spec flow and stopped at build because deft offered no cost\nsignal.\n\n### Detection\n\n- ! Check for `COST-ESTIMATE.md` in the project root.\n- ! Check that the file contains a recorded decision (the **Decision recorded**\n block populated with one of: `build`, `rescope`, `no-build`, `skip`).\n- ! For `skip`, `rescope`, or `no-build` decisions: the **Reason** field MUST be\n populated (one or two sentences in plain language). A skip with no reason\n recorded is treated the same as no decision.\n\n### Action\n\n- ! If `COST-ESTIMATE.md` is missing OR the **Decision recorded** block is\n unpopulated OR a `skip`/`rescope`/`no-build` decision has no reason recorded:\n stop immediately and redirect the user:\n\n > \"This project has not gone through the pre-build cost & budget transparency\n > phase. Run `skills/deft-directive-cost/SKILL.md` to produce a plain-English\n > `COST-ESTIMATE.md`, then re-run the build skill once the user has chosen\n > build / rescope / no-build / skip(+reason).\"\n\n- ! On a `build` or `skip` decision: continue with File Reading below.\n- ! On a `rescope` decision: stop and redirect the user back to spec edits\n (chain to `skills/deft-directive-refinement/SKILL.md` to pull spec scope\n back, or the interview), then re-run `skills/deft-directive-cost/SKILL.md`\n before re-attempting build.\n- ! On a `no-build` decision: stop and exit; do NOT proceed to File Reading.\n The user has explicitly stopped the project at the cost phase.\n- \u2297 Proceed to File Reading or any subsequent phase when `COST-ESTIMATE.md` is\n missing, when the decision is unpopulated, or when a skip / rescope / no-build\n decision has no reason recorded.\n- \u2297 Treat a `rescope` or `no-build` decision as if it were a `build` -- the\n build skill MUST honor the recorded decision.\n\n## File Reading\n\n- ! Read in order, lazy load:\n 1. `./xbrief/active/` -- scope xBRIEFs for work items to build (required)\n 2. `./xbrief/PROJECT-DEFINITION.xbrief.json` -- project identity, tech stack, architecture\n 3. `./.planning/codebase/MAP.md` -- generated codebase orientation projection, if present (advisory)\n 4. USER.md at the platform-appropriate path (see Platform Detection) -- Personal section is highest precedence; Defaults are fallback\n 5. `deft/main.md` -- framework guidelines\n 6. `deft/coding/coding.md` -- coding standards\n 7. `deft/coding/testing.md` -- testing requirements\n 8. `deft/coding/toolchain.md` -- toolchain validation rules\n 9. `deft/languages/{language}.md` -- only for languages this project uses\n- ~ If the MAP is absent or may be stale and the current scope needs broad codebase orientation, run `task codebase:map` and `task verify:codebase-map-fresh` when those commands resolve. Treat absence/staleness as advisory unless the task edits `plan.architecture.codeStructure`, a configured provider artifact, or the generated MAP itself.\n- ! Treat `plan.architecture.codeStructure` and selected provider artifacts as authoritative. The MAP is a generated projection.\n- \u2297 Read all language/interface/tool files upfront\n- \u2297 Hand-edit `.planning/codebase/MAP.md` or block unrelated implementation solely because the MAP is stale or absent\n\n## Rule Precedence\n\n```\nUSER.md Personal <- HIGHEST (name, custom rules -- always wins)\nPROJECT-DEFINITION.xbrief.json <- Project-specific (tech stack, architecture, config)\nUSER.md Defaults <- Fallback defaults (used when PROJECT-DEFINITION doesn't specify)\n{language}.md <- Language standards\ncoding.md <- General coding\nmain.md <- Framework defaults\nScope xBRIEFs <- LOWEST\n```\n\n- ! USER.md Personal section always wins over any other file\n- ! For project-scoped settings, PROJECT-DEFINITION.xbrief.json overrides USER.md Defaults\n\n## Change Lifecycle Gate\n\n! Before any implementation that touches 3+ files, verify that a `/deft:change <name>` proposal exists and has been confirmed by the user:\n\n- ! Check `history/changes/` for an active `proposal.xbrief.json` matching this work\n- ! If no proposal exists: propose `/deft:change <name>` and present the change name for explicit confirmation (e.g. \"Confirm? yes/no\")\n- ! The user must reply with an affirmative (`yes`, `confirmed`, `approve`) \u2014 a general 'proceed', 'do it', or 'go ahead' does NOT satisfy this gate\n- ? For solo projects: this gate is RECOMMENDED but not mandatory for changes fully covered by `task check`; it remains mandatory for cross-cutting, architectural, or high-risk changes\n- \u2297 Skip this gate because the user has already said \"proceed\" or \"go ahead\"\n\n## Build Process\n\nAll xBRIEFs (including those read from `xbrief/active/` and any new xBRIEFs this skill emits) MUST use `\"xBRIEFInfo\": { \"version\": \"0.6\" }`. The validator rejects any other version (see [`../../conventions/references.md`](../../conventions/references.md)).\n\n### Step 1: Understand the Scope\n\n- ! Read story xBRIEFs from `xbrief/active/` and `PROJECT-DEFINITION.xbrief.json`\n- ! Identify phases, dependencies, starting point from scope xBRIEF acceptance criteria\n- ~ Use `.planning/codebase/MAP.md`, when present, to orient broad codebase scanning. If the MAP conflicts with current code or canonical metadata, surface the drift and trust `plan.architecture.codeStructure` / provider artifacts plus the working tree over generated prose.\n- ! When scanning the existing codebase during scope understanding, MUST surface any contradicting patterns (two error-handling shapes, two state-management approaches, two naming conventions, etc.) before implementation begins -- apply `coding/hygiene.md` `## Surface Conflicts: Pick One, Explain, Flag the Other (#1005)` and choose ONE pattern (more recent OR more tested), explain the choice in the scope summary, and flag the other for cleanup\n- \u2297 Begin implementation against an averaged blend of two contradicting patterns -- \"average code that satisfies both rules is the worst code\" (#1005)\n- ! Present brief summary to user:\n\n> \"Here's what I see: {N} story xBRIEFs in active/. I'll start with {name}. Ready?\"\n\n### Step 2: Verify Toolchain\n\n- ! Before any implementation, verify all tools required by this project are installed and functional \u2014 see `deft/coding/toolchain.md` for full rules\n- ! At minimum: confirm task runner (`task --version`), language compiler/runtime, and platform SDK (if applicable) are available\n- ! If any required tool is missing, stop and report \u2014 do not proceed to Step 3\n- \u2297 Assume tools are available because the spec references them\n\n### Gate throughput \u2014 iteration fast lane vs merge chokepoint (#1704)\n\n> **Invariant:** every change MUST pass the full gate at least once before merge. Iteration MAY use a cheaper proxy; the merge chokepoint MUST NOT be skipped.\n\n- ! **Iteration lane (agents + humans):** during implementation commits, use affected/static gates \u2014 targeted tests on changed paths (`vitest run --coverage <paths>` or project equivalent), static `verify:*` gates relevant to touched files, and `task coverage:hotspots` / `task verify:forward-coverage` \u2014 NOT full `task check` on every commit.\n- ! **Merge chokepoint:** run full `task check` (or `task check:merge` in the framework source repo) once before push/PR and again when CI merge gate runs. Pre-PR skill exit and review-cycle fix batches still require a green full gate.\n- ! **Escape-rate safety (#1703 Tier-1):** before tightening fast-lane defaults fleet-wide, consult `#1703` measurement \u2014 `task eval:health` (Tier 0) and Tier-1 session telemetry (`helped/crud-metrics.jsonl` via instrumented CRUD / workflow metrics). Do NOT invent a separate fast-lane escape-rate surface (#1704 LockedDecisions).\n- ~ **In-engine incrementality (#1713):** content-hash task cache and runner-delegated affected selection are sibling work \u2014 not required for this policy face.\n- \u2297 Run full `task check` on every iteration commit when a cheaper proxy suffices \u2014 reserve the full gate for PR/merge (#1704).\n- \u2297 Skip the merge chokepoint because the iteration lane passed \u2014 the fast lane is convenience only.\n\n**Cost model (swarm-heavy path):** moves from roughly `O(commits \u00d7 full-gate)` toward `O(merges \u00d7 full-gate) + O(iterations \u00d7 cheap-proxy)` when workers iterate with affected/static gates and run full `task check` only at PR/merge.\n\n### Dual stop \u2014 multi-iteration implement and pre-PR loops (#2442)\n\nMulti-iteration implement-fix and pre-PR polish loops MUST carry **both** a success stop and a failure/budget stop (`main.md` `## Dual Stop Rule (#2442)`). Single-turn edits and one-shot probes are exempt.\n\n**Defaults for this skill (override only with an explicit operator envelope or xBRIEF field):**\n\n| Loop class | Success stop | Default failure stop |\n|------------|--------------|----------------------|\n| Implement / quality fix (tests, lint, typecheck, coverage, AC) | Affected/static gates green for the change; AC met | **max 5** fix iterations **or** **3** consecutive identical outcomes (same failing command + same primary error class) with no material code/config change |\n| Pre-PR polish (`deft-directive-pre-pr` Read-Write-Lint-Diff) | Full pass with zero further edits | **max 3** polish passes **or** **2** consecutive no-diff / same-diff outcomes |\n| Full `task check` re-run after a red merge chokepoint | `task check` green | Counts toward the implement/quality fix envelope above (do not open a separate unbounded check-retry loop) |\n\n**On failure stop:**\n\n- ! Halt the loop. Surface an **operator-visible halt report** with: (1) iterations attempted and which stop fired (max-iter / no-progress / budget), (2) commands and primary failure fingerprints tried, (3) what is still red or missing, (4) the human decision needed (unblock dependency, rescope AC, waive with audit, abandon).\n- ! Prefer a structured `BLOCKED:` terminal (preamble \u00a711 / #2843) when exiting a drive-to:merge-ready or parent-dispatched unit early because the envelope is exhausted.\n- \u2297 Continue \"one more fix\" after the envelope is exhausted.\n- \u2297 Reset the counter by opening a new commit, rewording the same change, or swapping workers while the same failure class remains.\n\n\n### Budget-aware effort - bank the pass before deepening (#3266)\n\nWhen a hard turn or cost budget is detectable (session:start `effort_budget` / env `DEFT_MAX_TURNS` / `DEFT_MAX_BUDGET` / host descriptor #1461), size effort to the **stated** acceptance bar first. This is the success-side analog of dual-stop (#2442): dual-stop stops thrash on failure; bank-the-pass stops budget exhaustion on over-deepening.\n\n- ! At implement start, read the session effort-budget signal (`task session:start` lines or JSON `effort_budget`, or env). When `posture=hard-capped`, treat the run as budget-constrained.\n- ! **Bank the pass first:** satisfy stated acceptance criteria (xBRIEF items / issue AC / official checker) and produce the passing artifact **before** any self-imposed deeper verification suite that exceeds the stated bar.\n- ! Only with **remaining** budget after the stated pass, extend verification depth. Never deepen past the point where a found defect could not also be fixed within budget (default reserve: enough turns/cost for one fix batch).\n- ! Self-verification scope scales with remaining budget - prefer the official/stated checks under a tight cap.\n- ! When deepening is skipped for budget, MUST say so in the run summary / handoff (`deepening_skipped=true` + reason) - fail-loud (#1006). Use `formatDeepeningSkippedNote` semantics from `packages/core/src/session/effort-budget.ts`.\n- ~ When no hard budget is detected (`posture=unbounded`), normal dual-stop defaults still apply; bank-the-pass is optional discipline, not a license to skip stated AC.\n- \u2297 Exhaust the turn/cost budget on self-imposed gold-plating after the stated bar is already within reach (#3266).\n- \u2297 Silently skip deepening without naming it, or silently gold-plate under a hard cap (#1006 / #3266).\n- \u2297 Treat bank-the-pass as permission to ship without meeting stated AC - stated AC remains the success stop.\n\nCore helper: `packages/core/src/session/effort-budget.ts` (`detectHardEffortBudget`, `recommendVerificationDepth`). Composes #2442, #1581, #3214, #1006.\n**Enforcement note:** skill defaults are behavioral. Durable delivery/acceptance circuit-breaker: **#3143** `packages/core/src/delivery-attempt/` (`evaluatePreDispatch`, `.deft/delivery-attempts/`). Docs: `docs/delivery-attempt.md`. Route delivery/acceptance automatic retries through that gate; do not invent a parallel ledger in this skill.\n\n### AC-pass banking checkpoint - finalize on green (#3285)\n\nSharpens #3266: the **first** moment stated/official acceptance criteria pass is a **banking checkpoint**, not a license to keep spending the turn budget on self-imposed depth.\n\n- ! When stated acceptance criteria first pass (`task verify:ac` / product-first done-gate #3284 / official checker), the **next** action is **FINALIZE**: checkpoint-commit the green state and record the bank (durable under `.deft/ac-pass-banks/`; optional run-summary line when `DEFT_RUN_SUMMARY_PATH` is set).\n- ! **Deepening after the bank requires surplus budget.** Self-imposed extra verification, refactors, or polish are permitted only when remaining budget meets `plan.policy.acPassBanking.surplusThreshold` (default **0.2** = 20% of max turns/cost still remaining) **and** the absolute reserve from #3266. Env override: `DEFT_AC_PASS_SURPLUS_THRESHOLD`.\n- ! Deepening, when allowed, happens **on top of** the committed checkpoint so a failed experiment can revert to banked green.\n- ! **Post-bank discoveries are reported, not chased** when surplus is insufficient: file a note/issue in the deliverable for out-of-scope defects unless they **regress stated AC** (then fix-regression). Finding beyond the bar is a win; thrashing a dying budget into a zero is the failure mode this rule closes.\n- ! When surplus is insufficient, ship the banked state and fail-loud (`deepening_skipped=true` + surplus reason) via `evaluateAcPassBanking` / `formatDeepeningSkippedNote` semantics.\n- ~ When no hard budget is detected, dual-stop still applies; bank-on-first-AC-pass remains good discipline but is not a hard surplus gate.\n- \u2297 Convert a banked official pass into a scored failure by chasing post-bank polish until the turn budget dies (#3285).\n- \u2297 Start post-bank deepening without a finalize checkpoint when a hard budget is active (#3285).\n- \u2297 Chase out-of-scope post-bank findings when surplus is below threshold (#3285).\n\nCore helpers: `packages/core/src/session/ac-pass-banking.ts` (`evaluateAcPassBanking`, `bankAcPass`, `decidePostBankFinding`, `simulateSurplusInsufficientRun`); policy: `packages/core/src/policy/ac-pass-banking.ts` (`plan.policy.acPassBanking`). Composes #3266, #3284, #3282 (optional bank-event JSONL), #1006.\n\n## Step 3: Build Phase by Phase\n\nFor each phase:\n\n1. ! **Scaffold** \u2014 file structure, dependencies, config\n2. ! **Test first** \u2014 write tests before implementation (TDD)\n3. ! **Implement** \u2014 make tests pass, following deft coding standards\n4. ! **Verify (iteration lane)** \u2014 run affected/static gates per `#1704` fast lane above; fix failures before checkpoint commits\n5. ! **Origin sync** \u2014 when this phase materially changed an origin-linked scope xBRIEF (`plan.references` includes `x-xbrief/github-issue`), run `task issue:sync-from-xbrief -- <path>` (or `--dry-run` to preview) so the linked GitHub issue receives a sync comment; if skipped, document why in the PR or session notes (#2540)\n6. ! **Checkpoint** \u2014 tell user what's done, what's next\n\n- \u2297 Move to next phase until current phase passes all checks\n\n### Step 4: Quality Gates\n\nAfter EVERY phase (iteration lane \u2014 #1704):\n\n```bash\nvitest run --coverage <changed-paths> # or project test runner on touched modules\ntask coverage:hotspots # branch headroom before merge\ntask verify:forward-coverage # new-source coverage (#1310)\n```\n\nBefore PR / phase handoff (merge chokepoint):\n\n```bash\ntask check # Full gate \u2014 format, lint, typecheck, tests, coverage, verify:*\ntask test:coverage # >=85% or PROJECT-DEFINITION.xbrief.json override\n```\n\n- ! Phase checkpoint commits MAY use the iteration lane; phase is NOT done for PR handoff until full `task check` passes at the merge chokepoint\n- \u2297 Skip quality gates or claim they passed without running\n- \u2297 Treat iteration-lane green as merge-ready without full `task check`\n- ! **Multi-scope batch (#3012):** when implementing an approved multi-scope pin/cohort, reserve full `task check` for end-of-batch (or after last scope) unless the last full check failed \u2014 then re-run on the fix loop. Do not run full check after every intermediate scope.\n- \u2297 Re-run full install/session ceremony after offline seed when ritual is already complete (#3010) \u2014 use `session:ready` for recovery only.\n\n\n## Product-first done-gate (#3284) / literal AC (#3267)\n\nAt intake, capture the task statement's **exact** acceptance commands as executable AC (`plan.acceptance.commands` + #3267 `literal_acceptance_commands`). Empty is allowed only with `none_stated: true` (ladder: stated \u2192 derived \u2192 project_floor). Before declaring done, run them **verbatim** \u2014 same paths, same flags, same working directory. Self-chosen verification is supplementary, never a substitute. Extends #973. `task check` runs `verify:ac` **first** (fail-fast); hygiene is second and may become advisory under pressure. Rapid ceremony = **AC-only**.\n\n- ! When reading the active scope xBRIEF / issue body at story start, capture stated shell acceptance commands into `plan.acceptance.commands` (issue:ingest stamps this + the #3267 ledger automatically). Do not paraphrase.\n- ! Before claiming phase or story done (and before merge-chokepoint PR handoff), run:\n```\ntask verify:ac -- <active-story-path>\n```\n Exit 0 = pass or none stated with valid marker; exit 1 = a stated command failed; exit 2 = config. (`verify:literal-ac` is the #3267 mechanism alias.)\n- ! Quote the literal invocations and their outputs in the completion note when commands were stated.\n- \u2297 Substitute a self-chosen approximation (`pnpm test` when the statement said `pnpm exec vitest run packages/core/src`) for the stated command.\n- \u2297 Skip this gate because ceremony dial is rapid/minimal \u2014 rapid's positive content is exactly this check (#3284).\n- \u2297 Leave `plan.acceptance.commands` empty without `none_stated: true` \u2014 absence must be an explicit decision.\n\n## Operator-log hygiene (lazy-load, #1940)\n\nWhen the story touches **operator-facing** services (dashboards, multi-process\nworkers, WARN/ERROR operators triage):\n\n- ~ SHOULD load `patterns/operator-log-hygiene.md` and apply the copy-paste\n checklist in `docs/operator-log-hygiene-checklist.md` to story AC or probe\n locked decisions before claiming logging done\n- \u2297 MUST NOT treat this as Product Insights (#2603) or LLM-call telemetry\n (#481) \u2014 those are different lanes\n- \u2297 MUST NOT assume core `deft check` enforces a log schema by default \u2014\n consumer-owned shape; optional pack stub under\n `docs/operator-log-hygiene-consumer-pack-stub.md`\n\nDiscovery keywords: operator log, operator-facing logs, observability checklist\n\u2014 also indexed in `REFERENCES.md`.\n\n## Goal-gate determinism (lazy-load, #852)\n\nWhen authoring or tightening story acceptance criteria, quality gates, or skill\nsteps during build:\n\n- ~ SHOULD load `patterns/goal-gate-determinism.md` \u2014 goals, AC, gates, exit,\n scope, stop, and preserve are rigid; pure execution path is flexible guidance\n- \u2297 MUST NOT treat \"all process steps done\" as verification \u2014 outcomes and\n gates own \"done\" (see also `verification/verification.md` and Fail Loud #1006)\n\nDiscovery keywords: goal-gate-determinism, rigid goals flexible path \u2014 also\nindexed in `REFERENCES.md`.\n\n## Coding Standards (Summary)\n\nRead full files when you need detail:\n\n- ! TDD: write tests first \u2014 implementation incomplete without passing tests\n- ! Coverage: \u226585% lines, functions, branches, statements\n- ~ Files: <300 lines ideal, <500 recommended, ! <1000 max\n- ~ Naming: hyphens for filenames unless language idiom dictates otherwise\n- ! Contracts first: define interfaces/types before implementation\n- ! Secrets: in `secrets/` dir with `.example` templates; \u2297 secrets in code\n- ! Commits: Conventional Commits format; ! use iteration fast lane before checkpoint commits; ! run full `task check` at PR/merge chokepoint only (#1704)\n\nSee `deft/coding/coding.md` and `deft/coding/testing.md` for full rules.\n\n## Pre-Commit File Review\n\n! Before every commit, re-read ALL modified files and explicitly check for:\n\n1. ! **Encoding errors** -- em-dashes corrupted to replacement characters, BOM artifacts, mojibake from round-trip read/write\n2. ! **Unintended duplication** -- accidental double entries in CHANGELOG.md, scope xBRIEF files, or structured data files\n3. ! **Structural issues** -- malformed CHANGELOG entries, broken table rows, mismatched index entries, invalid JSON/YAML\n4. ! **Semantic accuracy** -- verify that counts, claims, and summaries in CHANGELOG entries and ROADMAP changelog lines match the actual data in the commit (e.g. \"triaged 4 issues\" must match the number actually triaged, issue numbers cited must match the issues actually added)\n5. ! **Semantic contradictions** -- when adding a `!` or `\u2297` rule that prohibits a specific command, pattern, or behavior, search the same file for any `~`, `\u2248\u0338`, or prose that recommends or permits the same command/pattern -- resolve all contradictions in the same commit before pushing\n6. ! **Strength duplicates** -- when strengthening a rule (e.g. upgrading `~` to `!`), grep for the term in the full file and verify no weaker-strength duplicate remains\n7. ! **Forward test coverage** -- for each new source file in this PR (`scripts/`, `src/`, `cmd/`, `*.py`, `*.go`), verify a corresponding test file exists in the same PR; running existing tests is not sufficient for new code\n\n\u2297 Commit without re-reading all modified files first.\n\n## Commit Strategy\n\n- ! Default to one story per branch/PR. Batching multiple stories in one branch requires explicit operator approval and a short rationale.\n- ! Create a checkpoint commit after each completed story before beginning another story.\n- ! Use iteration fast lane before checkpoint commits; run full `task check` at PR/merge chokepoint (#1704)\n- \u2297 Claim checks passed without running them\n\n```\nfeat(phase-1): scaffold project structure\nfeat(phase-1): implement core data models with tests\nfeat(phase-2): add REST API endpoints with integration tests\n```\n\n## Error Recovery\n\n- ! Tests fail \u2192 fix them; \u2297 skip or weaken assertions\n- ! Coverage drops \u2192 write more tests; \u2297 exclude files\n- ! Lint/type errors \u2192 fix them; \u2249 add ignore comments without documented reason\n- ! Scope xBRIEF ambiguous -> ask user; \u2297 guess\n- ! Scope needs changes -> propose, get approval, update the scope xBRIEF first\n- ! Multi-iteration fix loops obey dual-stop defaults above (#2442); on envelope exhaustion halt with an operator-visible report -- do not thrash\n\n\n## Probe-then-fill remote claims (#3120)\n\n! Before filling any **remote** handoff field (PR URL, PR number, commit/HEAD SHA, CI green/success, review score) or claiming `status: pass` / ship/gate done, MUST **probe then fill**:\n\n1. Run same-turn `git` + forge probes (examples: `git rev-parse HEAD`, `gh api repos/<owner>/<repo>/pulls/<N>`, `task pr:watch -- <N> --one-shot`, checks API).\n2. Copy IDs / URLs / SHAs / scores **only** from that probe JSON/text into the evidence block.\n3. Set `proof_status: bound` and attach short raw probe snippets (`command` + `snippet`) for each remote claim.\n\n! Handoff evidence axes: **work** (local) / **ship** (pushed branch or PR) / **gate** (CI/review on HEAD). `proof_status` is `bound` | `unbound` | `n/a-no-remote-claim`.\n! **Legal partial:** local work `done` + ship `not_started` / `blocked` **without** PR/SHA/CI/review fields and `proof_status: n/a-no-remote-claim` (or `status: partial`) is valid \u2014 do not invent ship state.\n! **Fail ranking:** **invented-done** (false/unbound remote artifacts under pass) is **stricter** than **empty-done**. Unbound remote claims \u2192 invalid evidence (fail), not pass-with-notes.\n! Machine check: `validateHandoffEvidence` in `packages/core/src/handoff-evidence/` (see `templates/agent-prompt-preamble.md` \u00a711).\n\u2297 Fill PR / SHA / CI / review fields from recollection, narration, or prior-turn memory.\n\u2297 Claim `status: pass` with remote fields when `proof_status` is not `bound` or probes are missing (#3120).\n\n## Completion\n\n- ! When all phases pass and `task check` is green, complete each implemented story via `task scope:complete -- <active-story-path>` before final PR handoff.\n\n> \"The project is built and all quality checks pass. Describe any new features you'd like to add \u2014 I'll follow the deft standards we've set up.\"\n\n\n## Significant decision log (#1396)\n\n! When this scope makes a **significant** choice (architecture, product behavior, security, public/private boundary, data model, runtime topology, hard-to-reverse process), record it with `task decision:write` (or `--body-file` for multi-line fields) so later agents load rationale without inventing it.\n\n~ Prefer attaching with `--scope <active-xbrief>` when the decision is bound to this story; use standalone `xbrief/decisions/` for cross-cutting / multi-scope process choices.\n\n~ Before claiming a process/architecture path was 'already decided', run `task decision:list -- --query <topic>` (or `--issue N`).\n\n\u2297 Require a decision record for every trivial scope or routine fix.\n\u2297 Merge lessons (#1513) into decision records, or replace ADRs under `docs/decisions/ADR-*.md`.\n\nDocs: `docs/decision-log.md` \u00b7 `xbrief/decisions/README.md`.\n\n## Anti-Patterns\n\n- \u2297 Skip tests or write them after implementation\n- \u2297 Ignore `task check` failures\n- \u2297 Implement things not in scope xBRIEF without asking\n- \u2297 Read every deft file upfront\n- \u2297 Move to next phase before current passes checks\n- \u2297 Make commits without running iteration-lane validation; \u2297 skip full `task check` at PR/merge chokepoint (#1704)\n- \u2297 Proceed without USER.md -- always run the USER.md Gate first\n- \u2297 Re-run `directive init`, cold `session:start`, migrate, or re-copy pin scopes after offline seed when ritual is already complete (#3010)\n- \u2297 Run full `task check` after every intermediate scope of an approved multi-scope batch when the last merge-chokepoint check was green (#3012)\n- \u2297 Promote scopes one-by-one for a known multi-scope pin when `scope:promote --batch` would stage them in one turn (#3011)\n\n- \u2297 Spawn an implementation agent or invoke a code-writing tool against a xBRIEF that has not passed `task xbrief:preflight` (which wraps `scripts/preflight_implementation.py`) -- always run the Step 0 Implementation Preflight (#810) first; satisfy via `task xbrief:activate <path>`\n- \u2297 Proceed without `COST-ESTIMATE.md` and a recorded build / rescope / no-build / skip(+reason) decision -- always run the Cost Phase Gate (#739) first\n- \u2297 Proceed with implementation when the build or test toolchain is unavailable -- always run the Toolchain Gate (Step 2) first\n- \u2297 Proceed to next task or phase without tests passing -- testing is a hard gate, not a cleanup step\n- \u2297 Skip the Change Lifecycle Gate because the user said \"proceed\" -- broad approval does not satisfy the confirmation gate\n- \u2297 Commit or push directly to the default branch -- always create a feature branch first. Exception: user explicitly instructs a direct commit, or `PROJECT-DEFINITION.xbrief.json` narratives contain `Allow direct commits to master: true`\n- \u2297 Add a prohibition (`!` or `\u2297`) without scanning the same file for conflicting softer-strength rules (`~`, `\u2249`) that reference the same term\n- \u2297 Invent remote PR/SHA/CI/review claims in handoff evidence without same-turn probe binding \u2014 invented-done (#3120)\n- \u2297 Fill remote ship/gate fields from memory when only local work completed; legal partial omits PR fields (#3120)\n- \u2297 Run multi-iteration implement / pre-PR loops without a failure stop (max iterations and/or no-progress) or without an operator-visible halt report when the envelope is exhausted (#2442)\n- \u2297 Silently continue after dual-stop failure halt \u2014 escalate; do not thrash (#2442)\n- \u2297 Exhaust hard turn/cost budget on self-imposed deepening after the stated acceptance bar is within reach (#3266)\n- \u2297 Silently skip deepening for budget without a fail-loud summary note (#3266 / #1006)\n- \u2297 Chase post-bank out-of-scope findings when surplus budget is insufficient \u2014 report, do not thrash the banked pass (#3285)\n- \u2297 Skip finalize-on-green after first stated AC pass under a hard budget (#3285)\n",
33
33
  "frontmatter_extra": null
34
34
  },
35
35
  {
@@ -174,7 +174,7 @@
174
174
  ],
175
175
  "path": "skills/deft-directive-pre-pr/SKILL.md",
176
176
  "version": "0.1",
177
- "body": "# Deft Directive Pre-PR -- Read, Write, Lint, Diff, Loop\n\nStructured self-review loop agents run before submitting a PR. Catches inconsistencies, missing enforcement markers, incomplete acceptance criteria, scope creep, and unintended changes before they reach the reviewer.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, \u2249=SHOULD NOT, \u2297=MUST NOT, ?=MAY.\n\n**See also**: [deft-directive-review-cycle](../deft-directive-review-cycle/SKILL.md) | [deft-directive-build](../deft-directive-build/SKILL.md) | [RWLDL tool](../../tools/RWLDL.md)\n\n> **Formerly `deft-rwldl`** -- renamed and scoped to PR readiness. For the broader iterative quality improvement loop (micro/macro review), see [tools/RWLDL.md](../../tools/RWLDL.md).\n\n## Branch-Protection Policy Guard\n\n! Before entering Phase 1 (Read), run the skill-level branch-policy guard documented in `scripts/policy.py` / `scripts/preflight_branch.py` (#746 / #747). Halt before any state mutation (the Phase 2 Write phase, the Phase 3 Lint phase that may touch files) when the policy is unresolvable AND no env-var bypass is active:\n\n```\nuv run python scripts/preflight_branch.py --project-root . --quiet || exit 1\n```\n\nor invoke `task verify:branch`. Pre-PR is the last gate before push, so a stale / unresolvable policy here is the highest-leverage place to catch the bug before it reaches the bot reviewer.\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (per-finding decision menus in Phase 4 Diff, the Phase 5 Loop restart-vs-exit gate) MUST follow [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md): the final two numbered options MUST be `Discuss` and `Back`, in that order. The Discuss-pause semantic is documented verbatim there -- implicit resumption is forbidden.\n\n\n## Ordered-plan target gate (#2402)\n\n! Before opening or pushing a PR, when an ordered-plan sequence may be active, verify the work unit matches the current authorized entry:\n\n1. Resolve the current entry kind and id:\n\n```\ntask plan-sequence:current\n```\n\n Use `task plan-sequence:current -- --json` when you need machine-readable `kind` / `id` fields from the current entry.\n\n2. Verify with the **entry kind** (not hardcoded `pr` \u2014 `story` / `issue` entries are common):\n\n```\ntask verify:plan-sequence -- --target-kind <entry-kind> --target <entry-id>\n```\n\n- ! Exit non-zero \u2192 fail closed; do not open an unauthorized PR.\n- ! Exit 0 with \"skipped (no active ordered-plan sequence)\" \u2192 proceed under normal pre-PR rules.\n- \u2297 Hardcode `--target-kind pr` when the current entry is `kind=story` or `kind=issue` \u2014 the verifier matches entry kind exactly (#2662).\n- ! After the PR's review cycle completes successfully, run `task plan-sequence:advance` so \"next\" resolves to the following entry (or exhausted).\n- \u2297 Treat skill-chaining or \"what's next?\" as permission to open a PR outside the current sequence entry.\n\n## Gate throughput \u2014 iteration fast lane vs merge chokepoint (#1704)\n\n> **Invariant:** every change MUST pass the full gate at least once before merge. Pre-PR is the merge chokepoint \u2014 NOT every iteration commit.\n\n- ! **Iteration lane (Phases 2\u20133 loop):** use affected/static gates on changed paths \u2014 `vitest run --coverage <paths>`, relevant `verify:*` on touched files, `task coverage:hotspots` \u2014 instead of full `task check` on every pre-PR iteration.\n- ! **Merge chokepoint (Phase 3 Lint exit + final confirm):** run full `task check` once before push/PR; Phase 3c targeted coverage precedes but does not replace the full gate.\n- ! **Escape-rate safety (#1703 Tier-1):** before recommending fleet-wide fast-lane tightening, cite `#1703` Tier-1 telemetry (`helped/crud-metrics.jsonl`) and `task eval:health` \u2014 do NOT invent a separate escape-rate surface.\n- ~ **In-engine incrementality (#1713):** content-hash cache + runner-delegated affected selection are sibling work (#1713).\n- \u2297 Treat Phase 3c targeted coverage alone as PR-ready without full `task check` at the merge chokepoint.\n\n## When to Use\n\n- ! Before pushing a branch for PR creation\n- ! After completing implementation but before the final merge-chokepoint `task check` (#1704)\n- ~ After addressing bot reviewer findings (run one pre-PR pass before pushing the fix batch)\n- ? During mid-implementation checkpoints on large changes\n\n## Loop Phases\n\nEach iteration proceeds through all phases in order. Do NOT skip phases or reorder them.\n\n### Phase 1 -- Read\n\n! Re-read each changed file end-to-end (`git diff master --name-only` to get the list).\n\n- ! Read every changed file in full -- do not skim or skip sections\n- ! Compare each file against its scope xBRIEF acceptance criteria in `xbrief/active/`\n- ~ If changed files include `xbrief/PROJECT-DEFINITION.xbrief.json`, a configured `codebase-map` provider artifact, or `.planning/codebase/MAP.md`, read the MAP and canonical metadata together. The MAP is orientation; `plan.architecture.codeStructure` and provider artifacts remain authoritative.\n- ! When adding a `!` or `\u2297` rule that prohibits a specific command, pattern, or behavior, search the same file for any `~`, `\u2249`, or prose that recommends or permits the same command/pattern -- resolve all contradictions in the same commit before pushing\n- ! When strengthening a rule (e.g. upgrading `~` to `!`), grep for the term in the full file and verify no weaker-strength duplicate remains\n- ~ Note any inconsistencies, missing RFC2119 markers, stale cross-references, or incomplete sections\n- ~ Check that CHANGELOG.md entries match the actual changes made\n- ! If the change alters **user-visible behavior**, apply [coding/docs.md](../../coding/docs.md) (#447): update the matching user-facing surface (CHANGELOG when user/operator-visible, CLI help / commands.md for new or changed verbs/flags, README/getting-started for install/first-run, skill/strategy triggers when entry points change) in this PR\n- \u2297 Claim documentation was updated without those files in the diff\n- ~ Pure internal refactors with no user-visible behavior change do not require user-facing doc updates\n\n### Phase 2 -- Write\n\n! Fix any issues found in the Read phase.\n\n- ! Fix inconsistencies, add missing RFC2119 enforcement markers (`!`, `~`, `\u2297`)\n- ! Complete any incomplete acceptance criteria or missing content\n- ! Update stale cross-references\n- ~ Improve clarity where intent is ambiguous\n- \u2297 Make changes beyond the scope of the current task -- if you notice unrelated issues, file them as ideas or future work, do not fix them now\n\n### Phase 3 -- Lint\n\n! Run the merge-chokepoint gate and fix any failures (#1704).\n\n- ! Run full `task check` (fmt + lint + typecheck + tests + coverage + verify:*) \u2014 the merge chokepoint, not every pre-PR iteration\n- ! Fix all failures before proceeding to Phase 3b\n- ~ If a lint fix requires changing a file, that counts as a change for the Loop phase\n\n~ **Windows + Grok Build (#1353):** Avoid `|`, `>`, or `2>&1` in `run_terminal_command` strings -- use Python `pathlib`/`subprocess` or plain task commands instead.\n\n### Phase 3c -- Coverage headroom (#2683)\n\n! Before the full `task check` coverage gate, run targeted coverage on changed modules and verify headroom above the project floor.\n\n- ! Run targeted coverage first: `vitest run --coverage <changed-paths>` (or language equivalent) \u2014 not only full `task check`.\n- ! Exercise both sides of new branches (ternary / early-return / catch / default switch / `||` / `??`).\n- ! Treat barely \u2265 floor as insufficient \u2014 aim for \u2265 floor + 0.3\u20130.5pp headroom on the branch metric relative to **your project's** vitest/coverage floor (may differ from 85%).\n- ! Run `task coverage:hotspots` / `deft coverage:hotspots` to locate uncovered branches before opening a PR; complements `deft verify:forward-coverage` (#1310) and `--allow-coverage-debt=#N` (#2573).\n\n### Phase 3b -- Auto-Render Exports\n\n! If `xbrief/specification.xbrief.json` exists, refresh rendered exports before the diff check:\n\n- ! Run `task prd:render` if `PRD.md` already exists in the project root\n- ! Run `task spec:render` if `SPECIFICATION.md` already exists and does not contain `<!-- deft:deprecated-redirect -->`\n- ! If `plan.architecture.codeStructure`, a configured `codebase-map` provider artifact, or `.planning/codebase/MAP.md` changed, run `task codebase:map` and `task verify:codebase-map-fresh` so the generated orientation projection matches its canonical inputs.\n- \u2297 Create export files that don't already exist -- only refresh existing ones\n- \u2297 Hand-edit `.planning/codebase/MAP.md` to satisfy review; update canonical metadata or provider artifacts, then regenerate it\n\n### Phase 4 -- Diff\n\n! Review the full diff against the base branch for unintended changes.\n\n```\ngit --no-pager diff master\n```\n\n- ! Verify no files outside the task scope were modified\n- ! Check for scope creep -- changes that go beyond the spec task acceptance criteria\n- ! Verify no debug code, TODO comments, or temporary scaffolding remains\n- ! Confirm no unintended whitespace-only changes or formatting drift\n- ! **Closing-keyword policy (#3015 class D / #737 Layer 0):** Default PR body uses `Tracking: #N` / `Related: #N` / `Refs #N` only. Use `Closes` / `Fixes` / `Resolves #N` only when the **full issue DoD** is met (not Phase A partial / multi-phase mid-stream).\n- \u2297 Write `Closes #N Phase A`, `only if`, `partial`, or other conditional English around a real closing keyword \u2014 GitHub ignores the condition and auto-closes (#3015 enterprize#29).\n- ! **Run `task pr:check-closing-keywords` before opening the PR (default mode `both` = FP #737 + intent #3015).** Offline: `--body-file` / `--commits-file`. Scans body and commits for closing-keyword tokens in negation / quotation / example / code-block contexts (FP) and for any unallowlisted real close (intent). When full DoD close is intentional, pass `--allow-close <N,M>` (CLI allowlist only \u2014 body trailers are not an authorization path). FP-only: `--mode fp`. Known-safe quoted tokens: `--allow-known-false-positives`. Recurrence stack: #167, #697 / #698, #401 / #700, #735 (class A), #3015 (class D enterprize#29).\n- ~ Verify the diff tells a coherent story -- a reviewer reading it top-to-bottom should understand the change\n- ~ If the PR adds or moves any documentation, verify each new doc is reachable from the AGENTS.md reference chain -- an orphan doc is discovered <10% of the time yet still costs context when found (the reference-chain contract, #644 / #647). Add a pointer or fold it in rather than leaving it stranded.\n- ! **Gate integrity (#3156):** If the branch cleared a red gate, confirm the fix changed the product/process/test under test \u2014 not the gate definition, verifier, reward, required check, coverage floor, policy flag, or eval fixture that was failing. Deliberate gate changes need issue/PR rationale (constitution-tier disposal under #3164). Doctrine: [docs/gate-integrity.md](../../docs/gate-integrity.md). Refine-internal SkillOpt region stays on #2436 \u2014 do not re-implement it here.\n\n### Phase 5 -- Loop\n\n! Decide whether to restart or exit.\n\n- ! If ANY fixes were made in Phase 2 (Write) or Phase 3 (Lint): restart from Phase 1 (Read)\n- ~ Phase 3b auto-renders are intentional output refreshes; they do NOT trigger a loop restart\n- ! If a full Read-Write-Lint-Diff cycle produced zero changes: exit the loop\n- ~ Track iteration count -- if you exceed 3 iterations, pause and assess whether you are oscillating between competing fixes\n\n\n## Probe-then-fill remote claims (#3120)\n\n! Before filling any **remote** handoff field (PR URL, PR number, commit/HEAD SHA, CI green/success, review score) or claiming `status: pass` / ship/gate done, MUST **probe then fill**:\n\n1. Run same-turn `git` + forge probes (examples: `git rev-parse HEAD`, `gh api repos/<owner>/<repo>/pulls/<N>`, `task pr:watch -- <N> --one-shot`, checks API).\n2. Copy IDs / URLs / SHAs / scores **only** from that probe JSON/text into the evidence block.\n3. Set `proof_status: bound` and attach short raw probe snippets (`command` + `snippet`) for each remote claim.\n\n! Handoff evidence axes: **work** (local) / **ship** (pushed branch or PR) / **gate** (CI/review on HEAD). `proof_status` is `bound` | `unbound` | `n/a-no-remote-claim`.\n! **Legal partial:** local work `done` + ship `not_started` / `blocked` **without** PR/SHA/CI/review fields and `proof_status: n/a-no-remote-claim` (or `status: partial`) is valid \u2014 do not invent ship state.\n! **Fail ranking:** **invented-done** (false/unbound remote artifacts under pass) is **stricter** than **empty-done**. Unbound remote claims \u2192 invalid evidence (fail), not pass-with-notes.\n! Machine check: `validateHandoffEvidence` in `packages/core/src/handoff-evidence/` (see `templates/agent-prompt-preamble.md` \u00a711).\n\u2297 Fill PR / SHA / CI / review fields from recollection, narration, or prior-turn memory.\n\u2297 Claim `status: pass` with remote fields when `proof_status` is not `bound` or probes are missing (#3120).\n\n## Exit Condition\n\n! Exit when a complete Read-Write-Lint-Diff cycle produces **zero changes** -- no file edits in Write, no lint fixes in Lint, and no scope issues in Diff.\n\nAfter exiting:\n- ! Run `task check` one final time to confirm clean state\n- ~ The branch is now ready for push and PR creation\n\n\n## Significant decision log (#1396)\n\n! Before push, if this PR encodes a **significant** choice not already recorded, run `task decision:write` (significance filter: architecture, product behavior, security, boundaries, data model, topology, hard-to-reverse process).\n\n~ Check `task decision:list` for related process policy so the PR does not silently reverse a dogfood decision.\n\n\u2297 Invent revisit-free rationale in the PR body as a substitute for a decision record when the choice is significant.\n\u2297 Noise the log with trivial scope completions.\n\nDocs: `docs/decision-log.md`.\n\n## Anti-Patterns\n\n- \u2297 Submit a PR without running this pre-PR loop (Read-Write-Lint-Diff) -- every PR branch should pass at least one full cycle\n- \u2297 Exit the loop after the Lint phase without completing the Diff phase -- Diff catches scope creep and unintended changes that Lint cannot detect\n- \u2297 Skip the Read phase and jump directly to Lint -- Read catches semantic issues (missing content, wrong RFC2119 markers, incomplete acceptance criteria) that linters do not check\n- \u2297 Make out-of-scope fixes during Write -- this introduces scope creep that Diff will flag, forcing another iteration\n- \u2297 Ignore the iteration count -- more than 3 iterations usually indicates oscillating fixes or an unclear spec task\n- \u2297 Add a prohibition (`!` or `\u2297`) without scanning the same file for conflicting softer-strength rules (`~`, `\u2249`) that reference the same term\n- \u2297 Skip `task pr:check-closing-keywords` (#737) before pushing a PR. Intent mode (#3015) also refuses bare/conditional real `Closes #N` without `--allow-close`. The negation-context substring match is the Layer 0 (prevention) gate that prevents the recurring auto-close of umbrella / staying-OPEN issues observed in #697 (closed #642), #401 (closed #642), #700 (closed #233), and #735 (closed #734) -- each incident required manual reopen and downstream cleanup. The lint's three-state exit (0 clean / 1 hits found / 2 config error) MUST be treated as a hard refusal: rewrite the PR body / commit messages until clean, OR pass `--allow-known-false-positives` ONLY for legitimately-quoted occurrences (test fixtures, documentation that discusses the trigger token literally). See `skills/deft-directive-swarm/SKILL.md` Phase 6 Step 1 for the corresponding Layer 3 (recovery) `pr:check-protected-issues` rule (#701)\n- \u2297 Invent remote PR/SHA/CI/review claims in handoff evidence without same-turn probe binding \u2014 invented-done (#3120)\n- \u2297 Fill remote ship/gate fields from memory when only local work completed; legal partial omits PR fields (#3120)\n- \u2297 Clear a failing gate by editing the gate (definition, verifier, reward, required check, coverage floor, policy, eval fixture) instead of the work under test \u2014 gate integrity (#3156); see [docs/gate-integrity.md](../../docs/gate-integrity.md)\n",
177
+ "body": "# Deft Directive Pre-PR -- Read, Write, Lint, Diff, Loop\n\nStructured self-review loop agents run before submitting a PR. Catches inconsistencies, missing enforcement markers, incomplete acceptance criteria, scope creep, and unintended changes before they reach the reviewer.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, \u2249=SHOULD NOT, \u2297=MUST NOT, ?=MAY.\n\n**See also**: [deft-directive-review-cycle](../deft-directive-review-cycle/SKILL.md) | [deft-directive-build](../deft-directive-build/SKILL.md) | [RWLDL tool](../../tools/RWLDL.md)\n\n> **Formerly `deft-rwldl`** -- renamed and scoped to PR readiness. For the broader iterative quality improvement loop (micro/macro review), see [tools/RWLDL.md](../../tools/RWLDL.md).\n\n## Branch-Protection Policy Guard\n\n! Before entering Phase 1 (Read), run the skill-level branch-policy guard documented in `scripts/policy.py` / `scripts/preflight_branch.py` (#746 / #747). Halt before any state mutation (the Phase 2 Write phase, the Phase 3 Lint phase that may touch files) when the policy is unresolvable AND no env-var bypass is active:\n\n```\nuv run python scripts/preflight_branch.py --project-root . --quiet || exit 1\n```\n\nor invoke `task verify:branch`. Pre-PR is the last gate before push, so a stale / unresolvable policy here is the highest-leverage place to catch the bug before it reaches the bot reviewer.\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (per-finding decision menus in Phase 4 Diff, the Phase 5 Loop restart-vs-exit gate) MUST follow [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md): the final two numbered options MUST be `Discuss` and `Back`, in that order. The Discuss-pause semantic is documented verbatim there -- implicit resumption is forbidden.\n\n\n## Ordered-plan target gate (#2402)\n\n! Before opening or pushing a PR, when an ordered-plan sequence may be active, verify the work unit matches the current authorized entry:\n\n1. Resolve the current entry kind and id:\n\n```\ntask plan-sequence:current\n```\n\n Use `task plan-sequence:current -- --json` when you need machine-readable `kind` / `id` fields from the current entry.\n\n2. Verify with the **entry kind** (not hardcoded `pr` \u2014 `story` / `issue` entries are common):\n\n```\ntask verify:plan-sequence -- --target-kind <entry-kind> --target <entry-id>\n```\n\n- ! Exit non-zero \u2192 fail closed; do not open an unauthorized PR.\n- ! Exit 0 with \"skipped (no active ordered-plan sequence)\" \u2192 proceed under normal pre-PR rules.\n- \u2297 Hardcode `--target-kind pr` when the current entry is `kind=story` or `kind=issue` \u2014 the verifier matches entry kind exactly (#2662).\n- ! After the PR's review cycle completes successfully, run `task plan-sequence:advance` so \"next\" resolves to the following entry (or exhausted).\n- \u2297 Treat skill-chaining or \"what's next?\" as permission to open a PR outside the current sequence entry.\n\n## Gate throughput \u2014 iteration fast lane vs merge chokepoint (#1704)\n\n> **Invariant:** every change MUST pass the full gate at least once before merge. Pre-PR is the merge chokepoint \u2014 NOT every iteration commit.\n\n- ! **Iteration lane (Phases 2\u20133 loop):** use affected/static gates on changed paths \u2014 `vitest run --coverage <paths>`, relevant `verify:*` on touched files, `task coverage:hotspots` \u2014 instead of full `task check` on every pre-PR iteration.\n- ! **Merge chokepoint (Phase 3 Lint exit + final confirm):** run full `task check` once before push/PR; Phase 3c targeted coverage precedes but does not replace the full gate.\n- ! **Escape-rate safety (#1703 Tier-1):** before recommending fleet-wide fast-lane tightening, cite `#1703` Tier-1 telemetry (`helped/crud-metrics.jsonl`) and `task eval:health` \u2014 do NOT invent a separate escape-rate surface.\n- ~ **In-engine incrementality (#1713):** content-hash cache + runner-delegated affected selection are sibling work (#1713).\n- \u2297 Treat Phase 3c targeted coverage alone as PR-ready without full `task check` at the merge chokepoint.\n\n## When to Use\n\n- ! Before pushing a branch for PR creation\n- ! After completing implementation but before the final merge-chokepoint `task check` (#1704)\n- ~ After addressing bot reviewer findings (run one pre-PR pass before pushing the fix batch)\n- ? During mid-implementation checkpoints on large changes\n\n## Loop Phases\n\nEach iteration proceeds through all phases in order. Do NOT skip phases or reorder them.\n\n### Phase 1 -- Read\n\n! Re-read each changed file end-to-end (`git diff master --name-only` to get the list).\n\n- ! Read every changed file in full -- do not skim or skip sections\n- ! Compare each file against its scope xBRIEF acceptance criteria in `xbrief/active/`\n- ~ If changed files include `xbrief/PROJECT-DEFINITION.xbrief.json`, a configured `codebase-map` provider artifact, or `.planning/codebase/MAP.md`, read the MAP and canonical metadata together. The MAP is orientation; `plan.architecture.codeStructure` and provider artifacts remain authoritative.\n- ! When adding a `!` or `\u2297` rule that prohibits a specific command, pattern, or behavior, search the same file for any `~`, `\u2249`, or prose that recommends or permits the same command/pattern -- resolve all contradictions in the same commit before pushing\n- ! When strengthening a rule (e.g. upgrading `~` to `!`), grep for the term in the full file and verify no weaker-strength duplicate remains\n- ~ Note any inconsistencies, missing RFC2119 markers, stale cross-references, or incomplete sections\n- ~ Check that CHANGELOG.md entries match the actual changes made\n- ! If the change alters **user-visible behavior**, apply [coding/docs.md](../../coding/docs.md) (#447): update the matching user-facing surface (CHANGELOG when user/operator-visible, CLI help / commands.md for new or changed verbs/flags, README/getting-started for install/first-run, skill/strategy triggers when entry points change) in this PR\n- \u2297 Claim documentation was updated without those files in the diff\n- ~ Pure internal refactors with no user-visible behavior change do not require user-facing doc updates\n\n### Phase 2 -- Write\n\n! Fix any issues found in the Read phase.\n\n- ! Fix inconsistencies, add missing RFC2119 enforcement markers (`!`, `~`, `\u2297`)\n- ! Complete any incomplete acceptance criteria or missing content\n- ! Update stale cross-references\n- ~ Improve clarity where intent is ambiguous\n- \u2297 Make changes beyond the scope of the current task -- if you notice unrelated issues, file them as ideas or future work, do not fix them now\n\n### Phase 3 -- Lint\n\n! Run the merge-chokepoint gate and fix any failures (#1704).\n\n- ! Run full `task check` (fmt + lint + typecheck + tests + coverage + verify:*) \u2014 the merge chokepoint, not every pre-PR iteration\n- ! Fix all failures before proceeding to Phase 3b\n- ~ If a lint fix requires changing a file, that counts as a change for the Loop phase\n\n~ **Windows + Grok Build (#1353):** Avoid `|`, `>`, or `2>&1` in `run_terminal_command` strings -- use Python `pathlib`/`subprocess` or plain task commands instead.\n\n### Phase 3c -- Coverage headroom (#2683)\n\n! Before the full `task check` coverage gate, run targeted coverage on changed modules and verify headroom above the project floor.\n\n- ! Run targeted coverage first: `vitest run --coverage <changed-paths>` (or language equivalent) \u2014 not only full `task check`.\n- ! Exercise both sides of new branches (ternary / early-return / catch / default switch / `||` / `??`).\n- ! Treat barely \u2265 floor as insufficient \u2014 aim for \u2265 floor + 0.3\u20130.5pp headroom on the branch metric relative to **your project's** vitest/coverage floor (may differ from 85%).\n- ! Run `task coverage:hotspots` / `deft coverage:hotspots` to locate uncovered branches before opening a PR; complements `deft verify:forward-coverage` (#1310) and `--allow-coverage-debt=#N` (#2573).\n\n### Phase 3b -- Auto-Render Exports\n\n! If `xbrief/specification.xbrief.json` exists, refresh rendered exports before the diff check:\n\n- ! Run `task prd:render` if `PRD.md` already exists in the project root\n- ! Run `task spec:render` if `SPECIFICATION.md` already exists and does not contain `<!-- deft:deprecated-redirect -->`\n- ! If `plan.architecture.codeStructure`, a configured `codebase-map` provider artifact, or `.planning/codebase/MAP.md` changed, run `task codebase:map` and `task verify:codebase-map-fresh` so the generated orientation projection matches its canonical inputs.\n- \u2297 Create export files that don't already exist -- only refresh existing ones\n- \u2297 Hand-edit `.planning/codebase/MAP.md` to satisfy review; update canonical metadata or provider artifacts, then regenerate it\n\n### Phase 4 -- Diff\n\n! Review the full diff against the base branch for unintended changes.\n\n```\ngit --no-pager diff master\n```\n\n- ! Verify no files outside the task scope were modified\n- ! Check for scope creep -- changes that go beyond the spec task acceptance criteria\n- ! Verify no debug code, TODO comments, or temporary scaffolding remains\n- ! Confirm no unintended whitespace-only changes or formatting drift\n- ! **Closing-keyword policy (#3015 class D / #737 Layer 0):** Default PR body uses `Tracking: #N` / `Related: #N` / `Refs #N` only. Use `Closes` / `Fixes` / `Resolves #N` only when the **full issue DoD** is met (not Phase A partial / multi-phase mid-stream).\n- \u2297 Write `Closes #N Phase A`, `only if`, `partial`, or other conditional English around a real closing keyword \u2014 GitHub ignores the condition and auto-closes (#3015 enterprize#29).\n- ! **Run `task pr:check-closing-keywords` before opening the PR (default mode `both` = FP #737 + intent #3015).** Offline: `--body-file` / `--commits-file`. Scans body and commits for closing-keyword tokens in negation / quotation / example / code-block contexts (FP) and for any unallowlisted real close (intent). When full DoD close is intentional, pass `--allow-close <N,M>` (CLI allowlist only \u2014 body trailers are not an authorization path). FP-only: `--mode fp`. Known-safe quoted tokens: `--allow-known-false-positives`. Recurrence stack: #167, #697 / #698, #401 / #700, #735 (class A), #3015 (class D enterprize#29).\n- ~ Verify the diff tells a coherent story -- a reviewer reading it top-to-bottom should understand the change\n- ~ If the PR adds or moves any documentation, verify each new doc is reachable from the AGENTS.md reference chain -- an orphan doc is discovered <10% of the time yet still costs context when found (the reference-chain contract, #644 / #647). Add a pointer or fold it in rather than leaving it stranded.\n- ! **Gate integrity (#3156):** If the branch cleared a red gate, confirm the fix changed the product/process/test under test \u2014 not the gate definition, verifier, reward, required check, coverage floor, policy flag, or eval fixture that was failing. Deliberate gate changes need issue/PR rationale (constitution-tier disposal under #3164). Doctrine: [docs/gate-integrity.md](../../docs/gate-integrity.md). Refine-internal SkillOpt region stays on #2436 \u2014 do not re-implement it here.\n\n### Phase 5 -- Loop\n\n! Decide whether to restart or exit.\n\n- ! If ANY fixes were made in Phase 2 (Write) or Phase 3 (Lint): restart from Phase 1 (Read)\n- ~ Phase 3b auto-renders are intentional output refreshes; they do NOT trigger a loop restart\n- ! If a full Read-Write-Lint-Diff cycle produced zero changes: exit the loop\n- ~ Track iteration count -- if you exceed 3 iterations, pause and assess whether you are oscillating between competing fixes\n\n\n\n## Budget-aware pre-PR depth (#3266)\n\nWhen session effort-budget is hard-capped (`DEFT_MAX_TURNS` / `DEFT_MAX_BUDGET` / session:start `effort_budget`):\n\n- ! Complete the merge-chokepoint path that proves stated AC (full `task check` once, stated AC evidence) before optional polish that only deepens beyond the bar.\n- ! If remaining budget cannot fund another full Read-Write-Lint-Diff pass **and** a fix for a new finding, stop after the stated-pass chokepoint and record `deepening_skipped=true` with reason (#1006).\n- ! Dual-stop pre-PR defaults (max 3 polish / 2 no-diff) still apply; under a hard cap, prefer fewer polish iterations once AC + check are green.\n- \u2297 Start an unbounded self-imposed verification suite that exceeds stated AC while the hard budget is nearly exhausted (#3266).\n\n## Product-first done-gate (#3284) / literal AC (#3267)\n\n- ! Before Phase 3 Lint exit / push, when the active scope xBRIEF has acceptance commands (`plan.acceptance` or #3267 metadata/narratives), run `task verify:ac -- <active-xbrief>` and fail closed on exit 1. (`verify:literal-ac` is the mechanism alias.)\n- ! Commands must be the exact strings from the task statement \u2014 same flags and cwd. Self-chosen verification is supplementary only.\n- ! Full `task check` already runs `verify:ac` first; still run it explicitly before push when AC is stated so failures are visible without the full hygiene suite.\n- \u2297 Skip AC run on rapid/minimal ceremony dial \u2014 rapid = AC-only; AC never degrades when commands exist (#3284 / #3156).\n\n## Probe-then-fill remote claims (#3120)\n\n! Before filling any **remote** handoff field (PR URL, PR number, commit/HEAD SHA, CI green/success, review score) or claiming `status: pass` / ship/gate done, MUST **probe then fill**:\n\n1. Run same-turn `git` + forge probes (examples: `git rev-parse HEAD`, `gh api repos/<owner>/<repo>/pulls/<N>`, `task pr:watch -- <N> --one-shot`, checks API).\n2. Copy IDs / URLs / SHAs / scores **only** from that probe JSON/text into the evidence block.\n3. Set `proof_status: bound` and attach short raw probe snippets (`command` + `snippet`) for each remote claim.\n\n! Handoff evidence axes: **work** (local) / **ship** (pushed branch or PR) / **gate** (CI/review on HEAD). `proof_status` is `bound` | `unbound` | `n/a-no-remote-claim`.\n! **Legal partial:** local work `done` + ship `not_started` / `blocked` **without** PR/SHA/CI/review fields and `proof_status: n/a-no-remote-claim` (or `status: partial`) is valid \u2014 do not invent ship state.\n! **Fail ranking:** **invented-done** (false/unbound remote artifacts under pass) is **stricter** than **empty-done**. Unbound remote claims \u2192 invalid evidence (fail), not pass-with-notes.\n! Machine check: `validateHandoffEvidence` in `packages/core/src/handoff-evidence/` (see `templates/agent-prompt-preamble.md` \u00a711).\n\u2297 Fill PR / SHA / CI / review fields from recollection, narration, or prior-turn memory.\n\u2297 Claim `status: pass` with remote fields when `proof_status` is not `bound` or probes are missing (#3120).\n\n## Exit Condition\n\n! Exit when a complete Read-Write-Lint-Diff cycle produces **zero changes** -- no file edits in Write, no lint fixes in Lint, and no scope issues in Diff.\n\nAfter exiting:\n- ! Run `task check` one final time to confirm clean state\n- ~ The branch is now ready for push and PR creation\n\n\n## Significant decision log (#1396)\n\n! Before push, if this PR encodes a **significant** choice not already recorded, run `task decision:write` (significance filter: architecture, product behavior, security, boundaries, data model, topology, hard-to-reverse process).\n\n~ Check `task decision:list` for related process policy so the PR does not silently reverse a dogfood decision.\n\n\u2297 Invent revisit-free rationale in the PR body as a substitute for a decision record when the choice is significant.\n\u2297 Noise the log with trivial scope completions.\n\nDocs: `docs/decision-log.md`.\n\n## Anti-Patterns\n\n- \u2297 Submit a PR without running this pre-PR loop (Read-Write-Lint-Diff) -- every PR branch should pass at least one full cycle\n- \u2297 Exit the loop after the Lint phase without completing the Diff phase -- Diff catches scope creep and unintended changes that Lint cannot detect\n- \u2297 Skip the Read phase and jump directly to Lint -- Read catches semantic issues (missing content, wrong RFC2119 markers, incomplete acceptance criteria) that linters do not check\n- \u2297 Make out-of-scope fixes during Write -- this introduces scope creep that Diff will flag, forcing another iteration\n- \u2297 Ignore the iteration count -- more than 3 iterations usually indicates oscillating fixes or an unclear spec task\n- \u2297 Add a prohibition (`!` or `\u2297`) without scanning the same file for conflicting softer-strength rules (`~`, `\u2249`) that reference the same term\n- \u2297 Skip `task pr:check-closing-keywords` (#737) before pushing a PR. Intent mode (#3015) also refuses bare/conditional real `Closes #N` without `--allow-close`. The negation-context substring match is the Layer 0 (prevention) gate that prevents the recurring auto-close of umbrella / staying-OPEN issues observed in #697 (closed #642), #401 (closed #642), #700 (closed #233), and #735 (closed #734) -- each incident required manual reopen and downstream cleanup. The lint's three-state exit (0 clean / 1 hits found / 2 config error) MUST be treated as a hard refusal: rewrite the PR body / commit messages until clean, OR pass `--allow-known-false-positives` ONLY for legitimately-quoted occurrences (test fixtures, documentation that discusses the trigger token literally). See `skills/deft-directive-swarm/SKILL.md` Phase 6 Step 1 for the corresponding Layer 3 (recovery) `pr:check-protected-issues` rule (#701)\n- \u2297 Invent remote PR/SHA/CI/review claims in handoff evidence without same-turn probe binding \u2014 invented-done (#3120)\n- \u2297 Fill remote ship/gate fields from memory when only local work completed; legal partial omits PR fields (#3120)\n- \u2297 Clear a failing gate by editing the gate (definition, verifier, reward, required check, coverage floor, policy, eval fixture) instead of the work under test \u2014 gate integrity (#3156); see [docs/gate-integrity.md](../../docs/gate-integrity.md)\n- \u2297 Under a hard turn/cost budget, gold-plate pre-PR polish past the stated bar until the budget expires (#3266)\n- \u2297 Exit pre-PR after skipping deepen-for-budget without naming the skip in the summary (#3266 / #1006)\n",
178
178
  "frontmatter_extra": null
179
179
  },
180
180
  {
@@ -260,11 +260,16 @@
260
260
  "shepherd the PR",
261
261
  "watch the PR",
262
262
  "keep merge-ready",
263
- "PR shepherd"
263
+ "PR shepherd",
264
+ "pursue residual",
265
+ "follow-up hard-stop",
266
+ "same as conf-hold",
267
+ "continue dual-stopped PR",
268
+ "re-babysit residual"
264
269
  ],
265
270
  "path": "skills/deft-directive-review-cycle/SKILL.md",
266
271
  "version": "0.1",
267
- "body": "# Deft Directive Review Cycle\n\nStructured workflow for responding to bot reviewer (Greptile) findings on a PR.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, \u2249=SHOULD NOT, \u2297=MUST NOT, ?=MAY.\n\n## Principle Authority (#1471 / #212)\n\n! Universal review-cycle principles live in [`coding/review.md`](../../coding/review.md) (RFC2119): read-all-findings, severity P0/P1/P2 + merge-blocking semantics, single batch commit, cross-file grep of changed terms, local structured-data validation (SHOULD), no push mid-review, exit when no P0/P1 remain (P2 non-blocking), and post-merge closing-keyword verification.\n\n! This skill is the **Greptile + GitHub adapter** only: polling cadence, confidence-score thresholds, check-run detection, dual-source fetch (`gh` + MCP) for Comments Outside Diff, fail-closed Step 6 `ReviewerStatus`, review-monitor lease, and merge gates. Apply `coding/review.md` for the process; do not restate that principle list inline.\n\n~ Future adapters (CodeRabbit, Codacy, host babysit) SHOULD implement the same `coding/review.md` principles with their own mechanics.\n\n## Platform Requirements\n\n! This skill requires **GitHub** as the SCM platform and the **GitHub CLI (`gh`)** to be installed and authenticated. PR comment fetching, check-run queries, and review submission all depend on `gh`.\n\n\n## Ordered-plan exit / advance (#2402)\n\n! When the review-cycle exit condition is met (no P0/P1 remaining / CLEAN verdict):\n\n1. Return control to the caller \u2014 do **not** discover adjacent backlog work.\n2. If an ordered-plan sequence is active and this PR matched the current entry, run `task plan-sequence:advance`.\n3. If another entry remains, the caller may continue **only** to that entry (one unit).\n4. If the sequence is exhausted, stop and ask. Do not open another PR from queue intuition or chaining text.\n\n\u2297 Exit the review cycle into `task triage:queue` or an unrelated PR without fresh operator approval.\n\n## When to Use\n\n- User says \"review cycle\", \"check reviews\", or \"run review cycle\" on a PR\n- Operator asks to **babysit**, **shepherd**, or **watch** a PR -- including the Cursor product action **babysit-pull-request-in-cloud** (#2261 / #1862 intent-routing class)\n- A bot reviewer (Greptile) has posted findings on an open PR\n- Dispatching a cloud or background agent to monitor and resolve PR review findings until merge-ready\n\n## Cursor global babysit supersession (#2261)\n\nOn repos with `.deft/core/` installed, **PR shepherding intent** routes here -- not the Cursor-global `babysit` skill (`~/.cursor/skills-cursor/babysit/SKILL.md`). The product action **babysit-pull-request-in-cloud** shares the babysit name but MUST chain into this review-cycle surface on Deft-managed projects.\n\n- ! Orchestrators dispatching cloud/background workers for PR shepherding MUST include `templates/agent-prompt-preamble.md` (or reference it) and mandate reading this skill as the first workflow step.\n- ! Cloud babysit workers use `worker_role: review-monitor` (or `drive-to: merge-ready` implementation workers that own the review cycle) -- not a generic babysit loop without Phase 1 audit or Step 6 exit predicate (#1259).\n- \u2297 Route **babysit-pull-request-in-cloud** to Cursor global babysit when `.deft/core/` is present -- that bypasses xBRIEF preflight, `task check`, Greptile fail-closed exit, and CHANGELOG discipline (#2261 recurrence).\n\n### OpenClaw babysit supersession (#2876 / #2261)\n\nOn OpenClaw hosts with Directive installed (`.deft/core/` or equivalent content deposit), **babysit / shepherd / watch** intent likewise routes here -- not host-local freestyle poll loops and not OpenClaw `cron` alone.\n\n- ! When the OpenClaw tool surface exposes `sessions_spawn`, Approach 1 is the **default** babysit path: spawn a background review-monitor via `sessions_spawn` (register with `--platform-primitive sessions_spawn` or the alias `openclaw-sessions-spawn`).\n- ! Prefer a **visible** Control UI subagent (`visible:true` when the tool surface allows) when OpenClaw Control UI is the operator control plane so humans can inspect the monitor (#3044; invisible empty settles are higher FC04 residual risk).\n- ! Long review-monitor ownership (>~3 min) MUST NOT block the parent OpenClaw session \u2014 background `sessions_spawn` + parent yield; same Gap D rule as Cursor/Grok Build (#1880).\n- ! Prefer deep-think gates inside the monitor via the dual-invoke probe order (#2893): `deft pr:watch` / `deft pr:merge-ready` first, then `task deft:pr:watch` when the Taskfile include is present, then the #2878 gh-only fallback \u2014 bare `task pr:watch` is not the consumer form.\n- \u2297 Treat OpenClaw `cron` (or any host scheduler alone) as Approach 1. Cron/timer re-invocation is Approach 2 only when `sessions_spawn` is unavailable.\n- \u2297 Freestyle main-session `gh pr view` / `sleep` poll + ad-hoc cron when `sessions_spawn` is available \u2014 that is the statusreport#153 / #2876 process-routing failure mode.\n\n## Branch-Protection Policy Guard\n\n! Before entering the review/fix loop, run the skill-level branch-policy guard (#746 / #747). Halt before any state mutation if the project's `plan.policy.allowDirectCommitsToMaster` is unresolvable AND the operator has not set `DEFT_ALLOW_DEFAULT_BRANCH_COMMIT=1`. Concretely:\n\n```\ntask verify:branch || exit 1\n```\n\nThe skill MUST NOT modify files, push, or comment on the PR until the guard passes -- this catches the case where a malformed PROJECT-DEFINITION quietly disabled the policy and the agent would have committed directly to master mid-review.\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (Phase 1 audit gates, Phase 2 Step 4 monitoring approach selection, Phase 5->6 ready-to-merge gate, Step 6 exit-condition prompts) MUST follow [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md): the final two numbered options MUST be `Discuss` and `Back`, in that order. The Discuss-pause semantic is documented verbatim there -- on `Discuss` selection the agent MUST halt the in-progress sequence immediately, prompt `What would you like to discuss?`, and resume only on an explicit user signal (re-asking the original question, saying `resume`/`continue`, or re-issuing the prior selection). Implicit resumption is forbidden.\n\n## Pre-Flight Check\n\n! Before entering the review/fix loop, verify the Greptile configuration supports it:\n\n1. ! `triggerOnUpdates` must be enabled (via Greptile dashboard or `.greptile/config.json`) \u2014 without this, Greptile only reviews the initial PR and never re-reviews after fix pushes, so the loop cannot reach the exit condition\n2. ~ `statusCheck` should be enabled so Greptile posts a `\"Greptile Review\"` check run on each commit \u2014 this is the signal the org ruleset uses to gate merges\n3. ? If Greptile does not re-review after a push despite `triggerOnUpdates` being enabled, comment `@greptileai` on the PR as a manual re-trigger fallback\n\n! Greptile posts **check runs** (GitHub Checks API), not **commit statuses** (Statuses API). To verify the check run is present on a commit:\n\n```\ngh api repos/<owner>/<repo>/commits/<sha>/check-runs --jq '.check_runs[] | select(.name == \"Greptile Review\")'\n```\n\n\u2297 Use `commits/<sha>/statuses` to check for Greptile \u2014 that endpoint will always be empty.\n\n~ See `tools/greptile.md` for recommended dashboard and per-repo settings.\n\n## Phase 1 \u2014 Deft Process Audit\n\n! Before touching code, verify ALL prerequisites are satisfied. Fix any gaps first:\n\n1. ! Verify `skills/deft-directive-pre-pr/SKILL.md` was run before PR creation -- the PR branch should have passed at least one full pre-PR cycle (Read-Write-Lint-Diff). If not, run it now before proceeding.\n2. ! `PROJECT-DEFINITION.xbrief.json` and `xbrief/` lifecycle folders have scope xBRIEF coverage for all changes in the PR\n3. ! `CHANGELOG.md` has entries under `[Unreleased]` for the PR's changes\n4. ! `task check` passes fully (fmt + lint + typecheck + tests + coverage \u226575%)\n5. ! `.github/PULL_REQUEST_TEMPLATE.md` checklist is satisfied in the PR description\n6. ! If the PR touches 3+ files: verify a `/deft:change` `proposal.xbrief.json` exists in `history/changes/` for this branch and was explicitly confirmed by the user (affirmative response, not a broad 'proceed'), or document N/A with reason in the PR checklist\n7. ! Verify the PR is on a feature branch -- work MUST NOT have been committed directly to the default branch (master/main)\n\n~ **PR scope gate:** If the PR spans 3+ unrelated surfaces (e.g. a skill, a tool doc, and a strategy -- with no shared issue or scope xBRIEF linking them), warn the user that broad PRs increase review churn and Greptile noise. Recommend splitting into focused PRs unless all changes trace to the same scope xBRIEF or issue bundle.\n\n! Phase 1 audit gaps must be resolved before merging \u2014 but hold the fixes (do NOT commit or push them independently). Proceed to Phase 2 analysis to gather bot findings, then batch all Phase 1 + Phase 2 fixes into a single commit.\n\u2297 Commit or push Phase 1 audit fixes independently before gathering Phase 2 findings.\n\n## Phase 2 \u2014 Review/Fix Loop\n\n### Step 1: Fetch ALL bot comments\n\n! Retrieve findings using BOTH methods \u2014 each catches different comment categories:\n\n```\ngh pr view <number> --comments\n```\n\n! Use `do_not_summarize_output: true` \u2014 summarizers silently drop the \"Comments Outside Diff\" section from large bot comments.\n\n~ **Oversized output fallback:** If `do_not_summarize_output: true` produces output too large to process, extract the relevant section with:\n\n- **PowerShell (Windows):** `gh pr view <number> --comments | Select-String \"Outside Diff\" -Context 50`\n- **Unix/macOS:** `gh pr view <number> --comments | grep -A 50 \"Outside Diff\"`\n\nBoth commands extract the \"Comments Outside Diff\" section with surrounding context, avoiding the need to process the full output.\n\n~ **Windows + Grok Build (#1353):** Avoid `|`, `>`, or `2>&1` in `run_terminal_command` strings -- use Python `pathlib`/`subprocess` or plain task commands instead.\n\n! **MCP capability probe** (mirrors deft-directive-swarm Phase 3 pattern): Before attempting MCP `get_review_comments`, probe whether MCP GitHub tools are available in the current session. Detection: attempt a lightweight MCP call (e.g. list available tools or a no-op query) -- if it succeeds, MCP is available; if it errors or the tool is not in the available set, MCP is unavailable.\n\n- **MCP available**: ! Use MCP `get_review_comments` as the second source to catch Comments Outside Diff.\n- **MCP unavailable** (e.g. non-MCP agents including `start_agent` / `spawn_subagent` (\"grok-build\") dispatch, cloud agents, `oz agent run`): ! Use `gh api repos/<owner>/<repo>/pulls/<number>/comments` as the explicit fallback for the second review source. Document in the commit message or PR comment why MCP was skipped (e.g. \"MCP unavailable in this session -- used gh api fallback for review comments\"). The platform descriptor from runtime detection determines MCP availability independently of the dispatch primitive.\n\n\u2297 Report \"all comments resolved\" without verifying both sources.\n\u2297 Skip the second review source without probing for MCP capability and documenting the fallback used.\n\n~ **Late-arriving bot review re-check:** If the initial dual-source fetch returns no bot review on the current HEAD SHA, wait ~60s and re-fetch before evaluating the Step 6 exit condition. Bot reviewers (Greptile) typically land within 3-7 min of PR creation/push; an empty first pass is more likely \"review pending\" than \"review clean\".\n\n\u2297 Declare the exit condition met based on a single fetch that returned no bot review \u2014 re-fetch at least once after a ~60s delay first.\n\n~ This codifies a user-rule precedent on late-arriving bot reviews into the deft-internal deterministic tier. The [`templates/swarm-greptile-poller-prompt.md`](../../templates/swarm-greptile-poller-prompt.md) loop body already handles the same case for push-driven cycles via its per-poll fetch -- the rule above closes the orthogonal cold-start path where the one-shot review-cycle entry runs on a freshly-opened PR before any fix push has triggered the Step 4 polling loop.\n\n### Step 2: Analyze ALL findings before changing anything\n\n! Apply [`coding/review.md`](../../coding/review.md) before any code change: read **all** findings, classify P0/P1/P2, and plan **one** batch. Do not start per-finding fixes mid-read.\n\nGreptile adapter analysis extras:\n\n- Identify cross-file dependencies (a term, value, or field mentioned in multiple files)\n- ! **Scope-check each finding against the active story xBRIEF** (`plan.items[].narrative.Acceptance`) before coding \u2014 see Out-of-AC gate (#2881) below\n\n### Out-of-AC findings / active-story scope gate (#2881)\n\nBabysit and review-cycle are **not** a second unbounded implementation mandate. When Greptile (or another reviewer) raises design-adjacent work outside the active story's acceptance criteria, default to follow-up \u2014 not silent redesign mid-babysit (PR #2871 / #2869 \u2192 #2880 recurrence).\n\n! Given an active story xBRIEF with fixed `plan.items`, when a finding is **outside** those Acceptance criteria:\n\n1. ! File or propose a **follow-up** GitHub issue / scope xBRIEF for the out-of-AC work, **or**\n2. ! Amend the active brief's `plan.items` (and narratives) **with explicit operator consent** before implementing a new subsystem,\n3. ! Then continue babysit only for in-AC and carve-out findings.\n\n! **P0 carve-out vs new-subsystem-needs-story:**\n\n- ! P0 security / correctness defects on files **already touched** by the PR MAY land in the same PR without a new story.\n- ! New ledgers, idempotency protocols, cross-cutting reliability contracts, or multi-commit redesigns that expand story meaning **require** a separate story or an amended brief before code.\n\n! **Confidence-only holds (0 P0/P1):** when confidence is below threshold (e.g. `Confidence Score: 3/5`) with zero P0 and zero P1 findings, the skill does **not** mandate unbounded redesign to raise confidence. Offer one of:\n\n1. Follow-up issue / residual-risk note in the PR,\n2. Operator override path (document in PR comment),\n3. Minimal in-AC polish only \u2014 then re-evaluate Step 6.\n\n! **`issue:emit` related-ref footgun:** `task issue:emit` treats any `plan.references[]` entry whose type matches `github-issue` / `x-xbrief/github-issue` / `x-vbrief/github-issue` as **already tracked** and SKIPs creating a new issue. When linking **related** (non-primary) work:\n\n- ! Use a non-emit-tracking type for related issues (e.g. keep related links in narratives / PR body / `Refs #N` prose), **or** designate a single primary origin github-issue ref that emit should honor.\n- \u2297 Add related-issue `x-*/github-issue` refs to a brief that still needs `issue:emit` for its primary origin \u2014 emit will SKIP as already tracked.\n\n\u2297 Expand active story scope past xBRIEF AC mid-babysit without follow-up or consented amend (#2881).\n\u2297 Treat confidence-only holds as authorization to invent new subsystems in-tree.\n\n\n### Dual stop \u2014 review fix loops (#2442)\n\nReview fix cycles are multi-iteration work and MUST carry dual stop (`main.md` `## Dual Stop Rule (#2442)`). Single-turn re-checks are exempt.\n\n**Defaults for this skill (override only with an explicit operator envelope):**\n\n| Loop class | Success stop | Default failure stop |\n|------------|--------------|----------------------|\n| Greptile / bot fix batch (Step 3 \u2192 re-review) | No P0/P1 on current HEAD; confidence meets `minGreptileConfidence` | **max 3** fix-batch iterations across the whole review ownership (do **not** reset the counter on push when the same primary fingerprint remains) **or** **2** consecutive re-reviews with the same primary P0/P1 fingerprint and no material fix |\n| Confidence-only hold (0 P0/P1, score below floor) | Confidence meets floor, or operator chooses document/accept path | **max 1** optional polish pass, then stop (do not redesign unbounded \u2014 see confidence-only holds above) |\n\n**On failure stop:**\n\n- ! Halt automatic re-fix. Prefer `BLOCKED:` with PR number, HEAD SHA, blocker class (`review_cycle_cap` / `greptile_p0_p1` / `no_progress`), what was tried, and human decision needed (preamble \u00a711 / #2843).\n- \u2297 Continue silent fix rounds after the envelope is exhausted.\n- \u2297 Reset the fix-batch counter solely by re-pushing, empty-committing, or swapping workers when the same primary finding fingerprint remains (poll-wait timer MAY reset for a new HEAD; the dual-stop fix-batch counter MUST NOT).\n\n**Enforcement note:** skill defaults are behavioral. Durable delivery/acceptance circuit breaker: **#3143** packages/core/src/delivery-attempt/ (\u001bvaluatePreDispatch). Docs: docs/delivery-attempt.md.\n\n### Step 3: Fix all findings in ONE batch commit\n\n! Apply [`coding/review.md`](../../coding/review.md) single-batch, cross-file grep, and local structured-data validation rules. Land **all** in-scope fixes in one commit (or one intentional batch), never per-finding pushes.\n\nGreptile adapter pre-commit gate:\n\n- ! Before committing any Greptile fix, re-read the FULL current Greptile review and confirm all P0/P1 issues are addressed in the staged changes \u2014 this is the pre-commit gate that prevents per-finding fix commits\n- ! Run `task check` before committing\n- ! **Fail-loud completion claim (#1006)**: when reporting fix-batch completion (to the user, in the commit message, in a PR comment, or in a status message to a parent agent), MUST surface the OUTCOMES not the intent -- name the P0/P1 finding count addressed (\"addressed 3/3 P0 findings, 2/2 P1 findings, 0 deferred\" -- NOT \"all findings addressed\"), report the `task check` result with the test-collection counts (\"task check: 412 collected, 412 passed, 0 skipped, 0 xfailed\" -- NOT \"task check passed\"), and explicitly call out any finding intentionally deferred with the reason. Apply `coding/coding.md` `## Fail Loud: Completion Claims Require Outcome Verification (#1006)` to every claim emitted during the review cycle\n- \u2297 Claim \"all Greptile findings addressed\" without verifying that the staged fix actually closes every P0/P1 currently surfaced in the review body -- a fix that addresses 3 out of 4 P1 findings and reports completion is the exact failure mode #1006 forbids\n- \u2297 Claim \"task check passes\" when any test was skipped, xfailed, or run with errors suppressed -- report the full collection counts instead (#1006)\n- ? **Pre-existing failure carve-out**: If `task check` fails due to a pre-existing issue unrelated to the PR's changes, a partial test suite run is acceptable ONLY if BOTH conditions are met: (a) the `task check` failure is pre-existing with an open GitHub issue number tracking it, AND (b) the PR description explicitly notes the failure and includes the issue reference (e.g. \"task check: test_foo fails due to #NNN (pre-existing)\"). Without both conditions, the full `task check` pass remains mandatory.\n- ~ Commit message: `fix: address Greptile review findings (batch)`\n\n### Step 3b: Proactive test coverage scan\n\n! After committing the fix batch but before pushing, scan the changed lines for untested code paths:\n\n1. ! Run `git --no-pager diff HEAD~1 HEAD --name-only` to identify files touched in the fix batch\n2. ! For each changed file that has a corresponding test file, review whether the fix introduced or modified logic that lacks test coverage\n3. ! If untested code paths are found, write tests and amend them into the fix batch commit (or add as a second commit in the same push)\n4. ! Run `task check` again after adding tests to verify they pass\n\n~ This eliminates one CI round-trip per fix cycle \u2014 catching coverage gaps before CI does.\n\n\u2297 Push fix commits without scanning for untested code paths in changed files.\n\n### Step 4: Push and wait\n\n! Push the batch commit, then wait for the bot to review the latest commit.\n\n! After pushing, the agent MUST autonomously poll for review updates and continue the review cycle without stopping to ask the user. Do not pause for confirmation, do not ask \"should I continue?\", do not wait for user input between push and review completion. The review/fix loop is designed to run to the exit condition without human intervention.\n\n! Mid-review push rule: see [`coding/review.md`](../../coding/review.md) (no push while review in progress). Adapter rationale: every push re-triggers Greptile and resets the review clock.\n\n\u2297 Push any additional commits \u2014 including unrelated fixes, doc updates, or lessons \u2014 while waiting for the bot to finish reviewing the current head. If you discover additional work while waiting, stage it locally but do NOT push until the current review completes.\n\n\n\n### Greptile CLEAN vs CI holdout (`pr:watch` / #2688)\n\n! When waiting on a Greptile verdict for a `drive-to: merge-ready` worker (or any review-cycle owner), prefer the dual-invoke probe order below over ad-hoc sleep loops (#1056 / #2893). Parse `clean_gate_holdout` on every probe.\n\n### Gates-surface dual invoke order (#2893 / #2878)\n\nDeep-think gates (`pr:watch`, `pr:merge-ready`, `review-monitor:*`) have **three ordered invoke paths**. Agents MUST probe in this order; bare `task pr:watch` is **not** the sole (or first) consumer form.\n\n! **Probe order (MUST):**\n\n1. **`deft` / `directive` CLI first** \u2014 attempt `deft pr:watch --help` (or `directive pr:watch --help`). Primary for npm/package-manager installs; works without a root Taskfile. CLI forms take flags **without** go-task's bare `--` separator (e.g. `deft pr:watch <N> --json`, `deft verify:review-monitor --pr <N>`).\n2. **`task deft:<verb>` second** \u2014 when a root Taskfile includes `.deft/core/Taskfile.yml` under key `deft:`, go-task exposes **namespaced** tasks (`task deft:pr:watch`, `task deft:verify:review-monitor`, `task deft:review-monitor:register`). Probe `task --list` / `task deft:pr:watch -- --help`. Task forms **require** the bare `--` separator before verb flags (e.g. `task deft:pr:watch -- <N>`, `task deft:verify:review-monitor -- --pr <N>`).\n3. **#2878 gh-only fallback last** \u2014 only when both CLI and namespaced task probes fail, classify **missing-task: pr:watch** (or **missing-task: review-monitor**) and use the official gh-only subset below.\n\n\u2297 Treat bare `task pr:watch` / `task review-monitor:register` as the only prescribed consumer form \u2014 under include key `deft:` those un-namespaced names are absent; that probe failure is not proof the gate is unavailable if `deft` or `task deft:` works (#2893).\n\u2297 Pass go-task's bare `--` separator into `deft`/`directive` CLI forms (e.g. `deft pr:watch -- --help`) \u2014 CLI parsers reject the standalone `--` and the probe fails falsely (#2893).\n\n### Missing gate surface / consumer gh-only fallback (#2878)\n\nSome consumer repos (e.g. sister product deposits) ship Directive skills but have **no working invoke path** for `pr:watch` / `review-monitor:*` (no `deft` CLI on PATH, no Taskfile include \u2192 no `task deft:\u2026`). Agents MUST NOT invent a non-skill poll loop when every probe fails.\n\n! **After dual-invoke probe fails (#2893):** classify the session as **missing-task: pr:watch** (or the specific verb) and fail-loud:\n\n```\nBLOCKED: missing-task pr:watch on this consumer\nRemediation:\n 1. Prefer `deft pr:watch` / install `@deftai/directive` so the CLI surface works, OR\n 2. Add the root Taskfile include (doctor gates-surface snippet) so `task deft:pr:watch` works, OR\n 3. Use the official gh-only fallback subset below (still this skill \u2014 not freestyle).\n```\n\n! **Official gh-only fallback** (when both `deft`/`directive` and `task deft:<verb>` probes fail for pr:watch / review-monitor):\n\n1. Still select Approach 1 when a sub-agent primitive exists (OpenClaw `sessions_spawn`, Cursor `Task`, Claude Code `Agent`, `spawn_subagent`, `start_agent`) \u2014 spawn a review-monitor that runs the gh-only loop; do not block the parent.\n2. **Do not call** gate verbs via any surface the probe showed absent \u2014 those invocations cannot succeed and must not gate the spawn.\n3. Ownership claim without the tasks: post/update the sticky `<!-- deft:review-owner -->` PR comment via `gh api` (same field shape as the task-written lease) **or** keep ownership in the parent and document `missing-task: review-monitor` in the PR/parent handback. Never invent `.deft/review-monitor.json`.\n4. Poll with adaptive cadence (20-30s / 60s / 90s) using:\n - `gh pr view <N> --comments` (dual-source + Step 1 rules still apply)\n - `gh pr checks <N>`\n - `gh api repos/<owner>/<repo>/pulls/<N> -q .head.sha` for HEAD pin\n - `gh api repos/<owner>/<repo>/commits/<sha>/check-runs` for Greptile terminal check-run\n5. Evaluate the same Step 6 fail-closed all-of (terminal check-run + HEAD SHA + Last reviewed commit + confidence meets resolved min (policy/dogfood/default; see Step 6 #3095) + no P0/P1).\n6. Surface missing-task once to the operator/parent on first detection; do not silently rebrand freestyle sleep as `pr:watch`.\n\n\u2297 Fake a successful `pr:watch` or `review-monitor:*` gate when every dual-invoke probe failed.\n\u2297 Block Approach 1 / parent yield on missing `review-monitor:*` after the dual-invoke probe \u2014 use the gh lease claim or parent-owned gh-only poll instead (#2878).\n\u2297 Invent ad-hoc `sleep` / main-session poll / OpenClaw cron loops outside Approach 1\u20133 when the skill already names this fallback (#2878 / statusreport#153 recurrence).\n\u2297 Skip Step 6 fail-closed fields because deterministic tasks are missing \u2014 the gh surfaces above remain mandatory.\n\n! When `clean_gate_holdout=ci_failures` and Greptile otherwise satisfies the probe-side Step 6 fields (SHA match on HEAD, confidence meets resolved min (policy/dogfood/default; see Step 6 #3095), no P0/P1, not errored): **MUST NOT** idle-poll hoping CI heals. Treat Greptile CLEAN + CI red with the **same ownership** as a Greptile P0 for a merge-ready worker \u2014 one fix batch, re-push, re-probe.\n\n! On persistent `ci_failures` holdout: exit the Greptile wait immediately, fetch failing check annotations (`gh pr checks <N>`, CodeQL / required-check details, or `ci_failed_checks` from `pr:watch --json`), fix or escalate with evidence, then re-enter the review loop after CI is green.\n\n! PR body \"Test plan\" checkboxes being `[x]` do **not** authorize idle wait \u2014 merge-ready is `pr:watch` CLEAN / the merge path only.\n\n\u2297 Treat `pr:watch` TIMEOUT or long PENDING with `clean_gate_holdout=ci_failures` as \"Greptile still reviewing\" \u2014 it means **CI blocked the clean gate**.\n\n~ Surface the holdout to the user/parent on the first stable `ci_failures` probe (fail-loud), not after burning `max-wait-minutes`. See also [`templates/swarm-greptile-poller-prompt.md`](../../templates/swarm-greptile-poller-prompt.md) CLEAN gate evaluation (#1039).\n\n\n### Runner capacity stall (`runner_capacity_stall` / #2672)\n\n! Framework CI prefers Blacksmith with a timed GH-hosted failover (~20 minute stall budget). When `task pr:watch --json` / `task pr:merge-ready` reports `ci_ready_state=runner_capacity_stall` (or verdict `RUNNER_CAPACITY_STALL`, exit 2): **wait for auto-failover** to the ubuntu-latest lane and the authoritative aggregator check. Do **not** invent `--skip-ci` or merge with pending required checks.\n\n! `runner_capacity_stall` is distinct from ordinary `not_ready_yet` (under budget / `in_progress`) and from execution hangs (#2652). Capacity stall means required checks stayed `queued` with no runner claimed past the budget.\n\n\u2297 Use `--skip-ci` / merge-with-pending because CI is capacity-stalled \u2014 the failover path is the unblock; skip-ci is an incident-only release escape hatch (#2652), not a runner-capacity remedy.\n\n### CI weather reason codes + thrash caps (#3167)\n\n`pr:watch` / `pr:merge-ready` expose machine-distinguishable `ci_ready_state` values (also `--json`) so agents stop conflating Actions weather with product test failure:\n\n| `ci_ready_state` / verdict | Meaning | Agent action |\n|----------------------------|---------|--------------|\n| `ci_never_scheduled` / `CI_NEVER_SCHEDULED` | No CI workflow check-run for HEAD (empty or bots-only: Greptile/SLizard) | Cap re-triggers; then **BLOCKED** \u2014 do not multi-hour empty-commit thrash |\n| `runner_capacity_stall` / `RUNNER_CAPACITY_STALL` | Required still `queued`, no runner past budget (#2672) | Wait auto-failover; \u2297 `--skip-ci` |\n| `ci_failures` / `CI_BLOCKED` | Completed `failure` / `timed_out` with product evidence (#2688) | Own like Greptile P0 \u2014 fix or escalate |\n| `ci_cancelled_no_failover` / `CI_CANCELLED_NO_FAILOVER` | Primary `cancelled` and no green required sibling (failover skipped/not armed; workflow sibling **#3168**) | Cap re-triggers; then **BLOCKED** |\n| Greptile CLEAN fields / `greptile_pending` | Existing Step 6 / SHA / confidence | Unchanged |\n\n! **Thrash caps (MUST):** Under stable `ci_never_scheduled`, `ci_cancelled_no_failover`, or repeated capacity stall after failover wait budget, limit **CI re-trigger attempts** (empty-commit push, close/reopen, rebase-for-enqueue) to **at most 2** total across the ownership span. On the **2nd** failed re-trigger (or immediately when the weather code is stable and Greptile Step 6 is already clean), stop automatic re-push and emit a structured **BLOCKED** handoff.\n\n### Platform status probe + outage attribution (#3180)\n\n! When `ci_ready_state` is weather-class (`ci_never_scheduled`, `runner_capacity_stall`, `ci_cancelled_no_failover`, `ci_failures`), CI never starts for HEAD, or many PRs share an empty-check pattern: **MUST probe public status pages** before workflow thrash or drive-by edits. Gates surface static URLs in `pr:watch` / `pr:merge-ready` JSON and human output (v1: no network fetch required).\n\n1. ! **GitHub Status** (Actions, Webhooks): https://www.githubstatus.com/\n2. ! **Blacksmith Status**: https://status.blacksmith.sh/\n\n**Attribution table:**\n\n| Observation | `attribution` | Agent action |\n|-------------|---------------|--------------|\n| GH Actions and/or Webhooks major/partial outage | `platform` | Platform incident; \u2297 workflow drive-by edits; \u2297 empty-commit thrash past thrash caps; wait + re-check HEAD runs + local `task check` |\n| Blacksmith red while GH Actions green | `capacity` | Runner-provider incident; failover doctrine (#2672 / #3168) |\n| Both green + still `ci_never_scheduled` on this PR only | `repo_config` | Workflow paths, branch filters, required-check names, Actions disabled / org policy |\n| Unclear / mixed | `unknown` | Cap thrash; BLOCKED with both status URLs; operator decision |\n\n! **Anti-thrash during attributed platform outage:** After thrash caps, stop automatic re-push loops. Remediation is wait + re-probe HEAD check-runs, not inventing workflow edits for a global outage.\n\n\u2297 Merge or `--skip-ci` solely because a status page is red \u2014 status is attribution for wait/thrash policy, not a second branch-protection oracle.\n\u2297 Blame Blacksmith when GH Actions/Webhooks are the red components and Blacksmith runners are operational.\n\u2297 Edit workflows / empty-commit thrash to \"fix\" a documented global Actions/webhook outage without a status-page probe.\n\nCross-links: #3167 (weather codes), #3168 (failover arms), #2672 (capacity stall), #2688 (Greptile CLEAN + CI holdout).\n\n! **BLOCKED handoff template (CI weather):**\n\n```text\nBLOCKED: ci_weather\nPR: <N>\nHEAD: <sha>\nREASON: ci_never_scheduled|ci_cancelled_no_failover|runner_capacity_stall\nGREPTILE: CLEAN|P0/P1|pending (Step 6 fields)\nCI: <ci_ready_state from pr:watch --json>\nplatform_status_github: https://www.githubstatus.com/\nplatform_status_blacksmith: https://status.blacksmith.sh/\nincident_url: <optional status-page incident URL or n/a>\nattribution: platform|capacity|repo_config|unknown\nATTEMPTS: empty-commit=<0-2> close-reopen=<0-2>\nREMEDIATION: wait for platform recovery | capacity failover (#3168) | repo config fix | human admin-merge playbook below | operator decision\nREDISPATCH_OK: yes|no\n```\n\n! Ownership of Greptile CLEAN + CI holdout is still real (#2688) \u2014 **ownership \u2260 infinite wait**. After thrash caps, hand off; do not burn multi-hour `gh run watch` / empty-commit loops when Greptile is already CLEAN.\n\n! **Envelope selection under CI weather (#3153):** Prefer deliberate `stop-at: pr-open` implement + this skill as the partner merge-path babysit when known capacity/outage weather dominates; see swarm Envelope selection SLA and partner merge-path section above. Cross-link only \u2014 do not re-spec the tree here.\n\n\u2297 Multi-hour empty-commit / close-reopen / rebase thrash after thrash caps when `ci_ready_state` is `ci_never_scheduled` or `ci_cancelled_no_failover`.\n\u2297 Treat `ci_never_scheduled` as ordinary Greptile latency (`sha_match` / `terminal_check_run` only).\n\u2297 Silent `--skip-ci` / admin merge without the outage playbook audit trail below.\n\n### SLizard advisory-only for merge-ready wait (#3167)\n\n! Required bot for **merge-ready wait** / Step 6 exit ownership is **Greptile**. SLizard (Gemini Verify) is **advisory only**: timeouts, retries, missing check, or flaky SLizard conclusions MUST NOT gate the review-cycle wait loop or authorize unbounded re-push.\n\n! `task pr:merge-ready` may still surface SLizard structure when present (#2189); agents MUST NOT idle-poll or thrash solely for SLizard when Greptile Step 6 is clean. Prefer continue / BLOCKED on CI weather / human decision.\n\n\u2297 Block merge-ready babysit on SLizard alone when Greptile Step 6 all-of is satisfied on HEAD.\n\n### Outage admin-merge playbook (opt-in / human, #3167)\n\nWhen GitHub Actions is in a **documented major outage** (or multi-hour `ci_never_scheduled` / `ci_cancelled_no_failover` after thrash caps) and product + Greptile are ready:\n\n! Admin / human merge is **opt-in**, never the autonomous agent default. Preconditions:\n\n1. ! Greptile Step 6 fail-closed all-of on current HEAD (dogfood conf floor / `minGreptileConfidence`).\n2. ! Evidence of local or prior green `task check` / merge-gate when available.\n3. ! PR comment **audit note** naming the weather code, HEAD SHA, and who authorized override.\n4. ? Optional explicit env/policy for bot merge (`DEFT_ALLOW_BOT_MERGE` / `task policy:allow-bot-merge`) \u2014 **opt-in**, never silent default skip-ci.\n\n\u2297 Autonomous `--skip-ci` / `--admin` merge as the default under ordinary CI weather.\n\u2297 Replace branch protection with Greptile-only merge on normal days.\n\nWorkflow failover arming (Blacksmith cancelled \u2192 GH-hosted lane) is sibling issue **#3168** \u2014 this skill owns agent thrash caps and reason codes only.\n\n### Stall Detection Rubric (#564)\n\n! Track per poll: `startedAt` (timestamp of the first observation of the IN_PROGRESS check run for the current commit) and `commit.oid` (head SHA being reviewed). Both fields MUST be re-recorded every time the head SHA changes -- the rubric measures elapsed time on a single commit, not across the whole review cycle.\n\n! Expected duration baseline -- Greptile reviews typically complete in 2-5 minutes, with 7 minutes as the upper bound of normal. The escalation threshold is **3x expected = ~10 minutes** of continuous IN_PROGRESS on the same `commit.oid`. The 21-minute stall observed during the rc4 swarm cascade on PR #561 is the recurrence record; see [`../../meta/lessons.md`](../../../meta/lessons.md) `## Greptile Review Stall Detection (2026-04)`.\n\n! When elapsed time on the current `commit.oid` exceeds 10 minutes (3x expected) without the IN_PROGRESS check transitioning to a terminal state, the agent MUST escalate to the user. The escalation message MUST include: (1) the PR number; (2) the head SHA being reviewed; (3) the elapsed time since `startedAt`; (4) the four canonical user-decision options.\n\n! User-decision options at escalation -- render as a deterministic numbered menu per [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md) (final two options `Discuss` + `Back`):\n\n 1. Wait another N minutes (user picks N).\n 2. Manually re-trigger Greptile by commenting `@greptileai` on the PR (logs the override in a PR comment for auditability per the next rule).\n 3. Skip the bot review for this cycle and exit the loop with a documented reason.\n 4. Cancel the review cycle entirely.\n 5. Discuss.\n 6. Back.\n\n! Auto-restart detection -- when the polling loop observes a NEW `startedAt` (Greptile dropped its prior check run and started a fresh one without any push from the agent, e.g. service-side restart), the agent MUST reset its elapsed-time clock to the new `startedAt` AND notify the user that an auto-restart was detected. Resetting the clock without notifying is forbidden -- the user needs to know the cycle effectively re-started.\n\n! **`INCOMPLETE_BUT_RATED` stall signature (#1259):** when a poll observes a parsed `Confidence Score: X/5` number BUT no terminal check-run (no `completed` status with a `{success, neutral}` conclusion) AND/OR no HEAD-matching `Last reviewed commit:` completion marker, classify the state as **`INCOMPLETE_BUT_RATED`** \u2014 Greptile has emitted a confidence rating against a review that has NOT terminally landed on the current HEAD. This is NOT an exit condition (the Step 6 fail-closed all-of resolves the missing fields to `unknown`); treat it as a stall signature and keep polling, escalating per the 10-minute threshold above if it persists. A confidence number is the single most common false-positive for a premature exit \u2014 `INCOMPLETE_BUT_RATED` names the trap so the agent does not mistake a rating for a verdict.\n\n\u2297 Auto-retrigger Greptile (empty commits, force-pushes, agent-posted `@greptileai` comments, status-check rebuilds) without explicit user approval. The escalation menu's option 2 is the ONLY supported re-trigger path, and even that requires the user to pick it.\n\n! Document any user-approved override in a brief PR comment for auditability -- e.g. `Note: review-cycle stall detected at <SHA> after <N> min; user approved manual re-trigger via @greptileai per skills/deft-directive-review-cycle Stall Detection Rubric (#564).` This makes the override visible to humans reviewing the PR history and to future agents that resume the cycle.\n\n\u2297 Treat a stall as silent -- if the elapsed clock crosses the 10-minute threshold the agent MUST surface the menu, even if the agent is mid-poll. Continuing to poll past the threshold without user input is forbidden.\n\n### Owner Continuity Gate (#3090)\n\n! After any claim of `drive-to: merge-ready`, babysit, shepherd, or \"driving review-cycle / merge\" on an **open PR**, the **same turn** MUST end in exactly one of:\n\n- **A.** Approach 1 monitor live + sticky `<!-- deft:review-owner -->` lease registered (or #2878 gh-only lease equivalent). Parent yields with an **active** child / monitor and emits `review_cycle: in_progress:<pr>#<monitor_or_lease_ref>`.\n- **B.** Parent-retained ownership: parent does **not** mark the work complete; the next concrete action is an explicit dual-source poll/fix (Step 1 + Step 6). Emit `review_cycle: in_progress:<pr>#parent-retained` (or lease id when a sticky lease exists).\n- **C.** Explicit finish to caller/principal: `BLOCKED` / needs decision / `FAILED` with PR URL + HEAD SHA + why. Emit `review_cycle: skipped:<reason>` or keep `in_progress` only when a live owner remains; never freeform `started`.\n\n! **`review_cycle` evidence enum (portable \u2014 all consumers / handoffs / preamble \u00a711 / swarm finish messages):** **only**\n - `done` \u2014 Step 6 fail-closed all-of met on current HEAD (terminal check + HEAD pin + confidence bar + **0 P0/P1** via **dual-source**)\n - `in_progress:<pr>#<monitor_or_lease_ref>` \u2014 verifiable sticky lease, registered monitor id, or documented `parent-retained` ownership\n - `skipped:<reason>` \u2014 intentional skip (e.g. no-pr, operator cancel)\n - `n/a` \u2014 work never entered review-cycle\n\n! Layer **L4** `status: pass` (or equivalent process-green handoff) is **illegal** unless `review_cycle: done` **or** `review_cycle: in_progress:\u2026` with **verifiable** sticky lease / parent-retained ownership documented on that turn.\n\n! Opening a PR may use `in_progress` + lease; the **merge path** requires `done` (stricter product merge bars remain out of scope).\n\n! When dual-source fetch shows open P0/P1 under Step 6 / CLEAN evaluation: continue the fix loop **or** exit **BLOCKED** to the parent \u2014 never idle.\n\n! Optional machine gate: `deft verify:l4-owner --pr <N>` (or `task verify:l4-owner -- --pr <N>`; dual-invoke same order as other gates). Exit **0** only when a sticky lease is fresh on the PR **or** the caller asserts `--review-cycle done` after Step 6 (lease-or-done machine gate). `skipped` / `n/a` / parent-retained are process evidence only and do **not** satisfy this machine gate. Exit **1** on silent hold (no lease, no done). Pair with existing monitor-without-lease regression (#2797).\n\n\u2297 End an owning turn with **0 children**, **no sticky lease**, and **no finish signal** after a drive-to-merge / babysit / shepherd claim (**silent hold**).\n\u2297 Treat check-run **SUCCESS alone** as CLEAN or merge-ready while dual-source P0/P1 remain open.\n\u2297 Emit freeform `review_cycle: started` / `pending` / `initiated` or L4 `status: pass` without **A** (or parent-retained **B** with explicit next action) or full Step 6 `done`.\n\u2297 Solve Owner Continuity via host cron-as-Approach-1 or always-block-parent-until-merge \u2014 use A/B/C above (#2876 / #3090).\n\n~ **Eval / regression (#3090):** Given PR open + check SUCCESS + open inline P1s + agent text claims driving merge + turn ends with 0 subagents and no lease \u2192 **FAIL** (Owner Continuity Gate), not PASS.\n\n### Review Monitoring\n! **Background / independent dispatch (#1880 Gap D):** Long-running review-cycle owners and pollers (>~3 min) MUST be dispatched independently / in the background so the parent conversation stays interactive. On Cursor, use the Task tool background path (`run_in_background: true`) when the current agent is the top-level owner of that primitive (not a nested leaf \u2014 see Cursor leaf boundary). On Claude Code, top-level parents/orchestrators use the `Agent` tool with `run_in_background: true` (register primitive `claude-agent`, #3134); implementation leaves follow the Claude Code leaf boundary (blocking `pr:watch` or `stop-at: pr-open` sibling), not nested Agent. This generalizes the Approach-1 sub-agent monitor rule to implementation and fix workers as well \u2014 foreground dispatch is reserved for short tasks. The parent receives completion via `DONE` / `BLOCKED` / `FAILED` per `templates/agent-prompt-preamble.md` \u00a711.\n\n! **Worker-owns-lifecycle (#1880 Gap C):** When this skill runs as part of an implementation worker scoped `drive-to: merge-ready`, the worker owns the full review/fix loop through merge-ready in its own tool loop \u2014 do NOT exit at PR-open expecting the orchestrator to spawn a separate review leaf.\n\n! **Swarm monitor must not self-implement (#2843 / Gap C):** When a cohort monitor receives `BLOCKED` or DONE-with-blockers from a `drive-to: merge-ready` implementation leaf, the monitor MUST NOT enter the review/fix loop inline on Tier 1 \u2014 background-dispatch ONE continuation leaf scoped `drive-to: merge-ready` on the same worktree. Monitor-inline review-cycle is permitted only on Tier 3 or with explicit operator consent (see `skills/deft-directive-swarm/SKILL.md` Phase 5 completion-notification decision tree).\n\n### Partner merge-path when implement stops at PR-open (#3153)\n\n! This skill is the **required partner** for the swarm **Envelope selection SLA** (`skills/deft-directive-swarm/references/core-phase-0.md` / Phase 3). When an implement leaf was deliberately scoped **`stop-at: pr-open`** (or a merge-ready leaf failed thin DONE and recovery chose babysit ownership), the parent/monitor MUST **not** leave the open PR without a merge-path owner.\n\n! **First-class merge-path ownership (MUST, same turn as PR ground-truth):**\n\n1. ! Spawn **or** retain **exactly one** review-cycle owner for the open PR:\n - **Approach 1** review-monitor (`worker_role: review-monitor`) with sticky `<!-- deft:review-owner -->` lease (#3090 / #3044 / dual-invoke `review-monitor:register` when available), **or**\n - A continuation leaf scoped **`drive-to: merge-ready`** on that PR/worktree that owns babysit \u2192 merge-ready in its tool loop, **or**\n - Documented **parent-retained** ownership (`review_cycle: in_progress:<pr>#parent-retained`) with an explicit next poll/fix action \u2014 never silent hold.\n2. ! Route through **this skill** \u2014 \u2297 Cursor global babysit (`#2261`), freestyle main-session poll, or dual parallel monitors (`#3044`).\n3. ! Apply Owner Continuity Gate (#3090) and Single review-monitor lease (#3044) without exception: one sticky lease; force-takeover only when the prior owner is dead.\n4. ! **Post-merge `scope:complete` (#2321 / Gap C):** When the implement leaf stopped at pr-open, it MUST NOT have run `task scope:complete`. After the PR **merges**, the merge-path owner (or swarm Phase 6 `task swarm:finalize-cohort` / `task swarm:complete-cohort` / monitor) MUST run `task scope:complete` or `task scope:cancel`. `task verify:orphan-active` fails closed on stranded active briefs.\n5. ! **Human-merge / CLEAN-before-merge ownership (#3153 / #1193 / #2321):** When `plan.policy.requireHumanMerge` (or missing bot-merge authority) means the review owner reaches Greptile CLEAN / merge-ready but **cannot** squash-merge, lifecycle ownership is **not** complete. Prefer **durable** ownership (not a prose-only promise):\n - **Preferred:** Parent/monitor **retains** ownership (`review_cycle: in_progress:<pr>#parent-retained` or sticky lease held by the long-lived monitor) until human merge lands, then runs `scope:complete` (or Phase 6 `task swarm:finalize-cohort` / `task swarm:complete-cohort`).\n - **Allowed handoff:** Only to a **long-lived** parent/monitor / Phase 6 closer \u2014 same turn: (1) re-claim sticky `<!-- deft:review-owner -->` lease for the **recipient** (register/force as needed), (2) structured handback with PR, HEAD, `awaiting-human-merge`, and explicit post-merge `scope:complete` duty, (3) recipient acknowledges with `review_cycle: in_progress:<pr>#\u2026` before the giving agent exits.\n - ! Cohort through-merge: the **swarm monitor** is the default durable post-merge `scope:complete` owner for every `stop-at: pr-open` story (#2321) \u2014 do not rely on a review leaf that exits at CLEAN.\n - ! **Post-CLEAN wake path (MUST):** After CLEAN under human-merge, the durable owner MUST keep a **reachable observe path** until the PR is `MERGED` (or closed without merge \u2192 `scope:cancel` / operator decision). Concrete options (pick one, same ownership):\n 1. **Background poller** (Approach 1 preferred when Tier 1): spawn/retain a review-monitor or short poll loop that probes `gh api repos/<owner>/<repo>/pulls/<N>` for `merged` / `state` on adaptive cadence (or host merge webhook when available), then runs post-merge verification + `scope:complete`.\n 2. **Parent-retained yield-with-wake:** parent keeps `review_cycle: in_progress:<pr>#parent-retained` and re-enters on the next operator message / scheduled re-invocation (Approach 2) with an explicit first action of \"check merge state \u2192 if merged, `scope:complete`\".\n 3. **Phase 6 cohort closer:** for swarm, record the PR as `awaiting-human-merge` in the monitor checkpoint and **require** the Phase 6 pre-sweep merge re-poll (`skills/deft-directive-swarm/references/core-phase-5-6.md` \u00a7 Human-merge observe path / Step 1.5) before `task swarm:complete-cohort` / finalize \u2014 never skip `scope:complete` solely because Greptile was CLEAN earlier.\n \u2297 Keep only a sticky lease with no poller, no parent re-entry plan, and no Phase 6 re-poll checklist \u2014 that is ownership-in-name-only and still strands `scope:complete`.\n \u2297 Handoff to a short-lived leaf that exits at CLEAN without lease transfer.\n \u2297 Emit terminal `DONE` / stand down at CLEAN when merge authority is human-only and no **reachable** durable owner (sticky lease + live parent/monitor/cohort closer **with an observe path above**) remains for post-merge `scope:complete`.\n6. ! **Thin DONE recovery (#2943 / #3153):** A failed `drive-to: merge-ready` leaf that only opened a PR is **not** success. After ground truth, hand merge path to **one** of the owners above \u2014 never improvise a second lease or re-dispatch implement + babysit in parallel without releasing the first.\n\n! **Cohort through-merge intent is unchanged:** stories still land on master. Envelope selection only assigns **who owns implement vs who owns Greptile/CI/merge** under capacity stall, conf floors, wall-clock budgets, or large multi-gate stories. Happy-path single `drive-to: merge-ready` leaves remain the default and do not use this partner handoff.\n\n! **Does not authorize:** lowering `minGreptileConfidence`, `--skip-ci` for capacity stalls, or unbounded redesign on conf-only holds (#2881 / #2672 / #3095).\n\nCross-links: swarm decision tree `skills/deft-directive-swarm/references/core-phase-0.md` \u00a7 Envelope selection SLA; Phase 3 Gap C `skills/deft-directive-swarm/references/core-phase-3.md`; thin SKILL pointer `skills/deft-directive-swarm/SKILL.md` \u00a7 Envelope selection SLA.\n\n\n\n! Select the monitoring approach based on runtime capability detection (the matrix in `skills/deft-directive-swarm/SKILL.md` Phase 3 Step 1, extended per #1342 slices 1-2 for `spawn_subagent` / \"grok-build\", per #1877 for Cursor as first-class Tier-1 tiers, per #2876 for OpenClaw `sessions_spawn`, and per #3134 for Claude Code `claude-code` / `claude-agent`). Probe the environment (tool set + env vars) to obtain the stable platform descriptor (`grok-build`, `warp-orchestrated`, `warp-manual`, `cursor-composer`, `cursor-cloud-agent`, `claude-code`, `openclaw`, etc.) from the launch adapter / `get_platform_capabilities` and map the descriptor to the appropriate tier + dispatch primitive (`start_agent`, `spawn_subagent`, the Cursor `Task` tool, Claude Code `Agent` / `claude-agent`, or OpenClaw `sessions_spawn`). The descriptor (not hard-coded tool presence) is the single source of truth for both launch and review monitoring.\n\n- **Tier 1 (orchestrated sub-agent)** \u2192 Approach 1 (spawn review-monitor sub-agent via the primitive matching the descriptor: `start_agent`, `spawn_subagent`, the Cursor `Task` tool with `run_in_background: true`, Claude Code `Agent` with `run_in_background: true` / register `claude-agent`, or OpenClaw `sessions_spawn`)\n- **Tier 2 (no sub-agent primitive, but scheduler/timer/auto-reinvocation)** \u2192 Approach 2 (yield-between-polls) \u2014 includes OpenClaw `cron` / host scheduler **only when** `sessions_spawn` is unavailable (#2876)\n- **Tier 3 (interactive session, nothing else)** \u2192 Approach 3 (blocking sleep loop as last resort)\n\n! Detection: use the full runtime capability matrix (swarm Phase 3 + launch adapter from #1342 slice 2). The old single-probe for `start_agent` is superseded; the returned platform descriptor determines both the orchestration path and the MCP surface (see MCP probe below). If the descriptor is `grok-build` (spawn_subagent present, start_agent + WARP_* absent), treat as Tier 1 with the spawn_subagent poller path. If the descriptor is `cursor-composer` / `cursor-cloud-agent` (Cursor `Task` tool present, start_agent + WARP_* + spawn_subagent absent), treat as **Tier 1 with the backgrounded Cursor `Task` poller path** (#1877) \u2014 NOT Tier 3. Cursor's `Task` tool is a first-class sub-agent primitive; degrading a Cursor session to the Approach-3 blocking poll is the misclassification #1877 closes. If the descriptor is `claude-code` (Claude-unique `Agent` / `CLAUDECODE` / `DEFT_PROBE_CLAUDE_CODE` signals), treat as **Tier 1 with the backgrounded Claude Code `Agent` poller path** (#3134) \u2014 NOT Tier 3 and NOT `cursor-composer` (bare `Task` is not a Claude-unique signal). If the descriptor is `openclaw` (`sessions_spawn` present), treat as **Tier 1 with the backgrounded `sessions_spawn` poller path** (#2876) \u2014 NOT Approach 2 cron and NOT main-session gh poll.\n\n! Swarm agents (whether launched via `start_agent`, `spawn_subagent`, or OpenClaw `sessions_spawn` per the platform descriptor) SHOULD prefer Approach 1 for their own review-monitor sub-agent. Approach 2's yield-between-polls is not self-sustaining for swarm agents (see warning below). Always include the canonical `templates/agent-prompt-preamble.md` (AGENTS.md read mandate, #810 xBRIEF gate, #798 PowerShell UTF-8, pre-PR + review-cycle mandates) when spawning a poller sub-agent.\n\n! **Deterministic review-monitor gate (#2655 / #2814 / #2876 / #2893):** When Tier 1 is available **and** a dual-invoke probe succeeds for review-monitor verbs (`deft verify:review-monitor` / `deft review-monitor:register`, or `task deft:verify:review-monitor` / `task deft:review-monitor:register`), run that verify form before yielding, entering Approach 3, or claiming review monitoring started \u2014 CLI: `deft verify:review-monitor --pr <N> [--call-site solo]`; task: `task deft:verify:review-monitor -- --pr <N> [--call-site solo]`. After spawning Approach 1, claim the PR-anchored lease with the matching register form (CLI: `deft review-monitor:register --pr <N> --monitor-agent-id <id> --platform-primitive ...`; task: `task deft:review-monitor:register -- --pr <N> --monitor-agent-id <id> --platform-primitive start_agent|spawn_subagent|cursor-task|claude-agent|sessions_spawn|openclaw-sessions-spawn`). Release with the matching release form (CLI: `deft review-monitor:release --pr <N>`; task: `task deft:review-monitor:release -- --pr <N>`) when done. Exit `0` ready / `1` not ready or held-by-other / `2` config. The sole source of truth is the sticky GitHub PR comment (`<!-- deft:review-owner -->`); legacy `.deft/review-monitor.json` is obsolete and ignored. On register conflict, attach to the existing owner or stop \u2014 do not parallel-fix.\n\n! **Missing review-monitor surface carve-out (#2878 / #2893):** When dual-invoke probes fail for `pr:watch` **and** `review-monitor:*` (no `deft` CLI, no `task deft:` include), do **not** invoke those gates and do **not** block Approach 1 on them. Fail-loud once with `missing-task: review-monitor` / `missing-task: pr:watch`, then:\n1. Still spawn Approach 1 with the official gh-only fallback when a sub-agent primitive exists.\n2. Post (or update) the sticky lease comment via raw `gh api` using the same `<!-- deft:review-owner -->` field shape the tasks would write \u2014 parent may yield after that claim succeeds \u2014 **or**, if the agent cannot write issue comments, keep ownership in the parent with the gh-only poll and document that lease tasks were unavailable.\n3. Never invent a local `.deft/review-monitor.json` as a substitute gate.\n\u2297 Require successful review-monitor register/verify on a consumer where dual-invoke probes failed \u2014 that is the conf=3 / #2878 inconsistency Greptile flagged.\n\n! **Regression trigger (#2797 / #2878):** A leaf that claims a monitor is active without a preceding successful **GitHub sticky lease claim** MUST fail the review-monitor checklist/eval; a backgrounded `pr:watch` shell is insufficient. When a dual-invoke probe finds `review-monitor:register`, that form is the required claim path. When the missing-task carve-out applies (#2878), a raw `gh api` post/update of the same `<!-- deft:review-owner -->` sticky comment satisfies the claim (or the parent keeps ownership and does not claim a separate monitor). The regression fails only on a claim with **no** sticky lease evidence \u2014 not on consumers that legitimately lack the gate surface.\n\n\n\n! **CI-holdout carve-out (#2688):** When `task pr:watch --one-shot --json` reports `clean_gate_holdout=ci_failures` with Greptile fields otherwise satisfied on current HEAD, do **not** freeze on `verify:review-monitor` / spawn-monitor as if Greptile latency were the blocker. Fix CI first (same ownership as Greptile P0). Keep or register a review-monitor only while still waiting on Greptile latency; a `BLOCKED: ci_failures` DONE handback to the implementation owner is correct.\n\n\n! **Cursor leaf boundary (#2797 / #2893):** A Cursor `Task` leaf cannot reliably spawn another Cursor `Task`; nested Task (leaf spawning leaf) is unsupported for an Approach 1 review-monitor. A Cursor `drive-to: merge-ready` leaf MUST either keep ownership in the same agent by blocking on `deft pr:watch <N>` (or `task deft:pr:watch -- <N>` when include-present), or its envelope MUST instead be `stop-at: pr-open` so the orchestrator can spawn and register a sibling review-monitor. A background shell `pr:watch` is not a monitor and MUST NOT be claimed as one.\n\n! **Claude Code leaf boundary (#3134 / #2797 analogue):** Nested `Agent` (implementation leaf spawning a second-level review-monitor Agent) is unsupported/unreliable on some Claude Code surfaces. A Claude Code `drive-to: merge-ready` leaf MUST either keep ownership in the same agent by blocking on `deft pr:watch <N>` (or `task deft:pr:watch -- <N>` when include-present), or its envelope MUST instead be `stop-at: pr-open` so the orchestrator can spawn and register a sibling review-monitor with `--platform-primitive claude-agent`. \u2297 Background a nested Agent poller from an implementation leaf and exit claiming monitoring is active. Top-level parents/orchestrators that own the `Agent` primitive MAY still Approach-1 background a review-monitor Agent.\n\n**Approach 1 (preferred -- sub-agent orchestration available per platform descriptor):**\n\n! **Background dispatch (#1880 / #2876 / #3134):** Spawn the review-monitor sub-agent via the matching primitive IN THE BACKGROUND (Cursor: Task `run_in_background: true`; Claude Code: `Agent` `run_in_background: true`; Grok Build: `spawn_subagent` with parent yielding; OpenClaw: `sessions_spawn` with parent yielding). The parent MUST remain interactive while the poller runs \u2014 never block the parent OpenClaw/Cursor/Claude Code/Grok session for >~3 min of monitor ownership.\n\n! **Heartbeat contract for Cursor pollers (#1877 / #1166 / #2876 / #3134):** Claude Code `Agent` and OpenClaw `sessions_spawn` pollers share this contract. A Cursor `Task`, Claude Code `Agent`, or OpenClaw `sessions_spawn` review-monitor poller whose loop runs > ~3 min MUST honour the sub-agent heartbeat contract (`docs/subagent-heartbeat.md`), same as the `spawn_subagent` path \u2014 emit periodic progress so the parent can distinguish a live poller from a hung one.\n\n~ **Visible Control UI (OpenClaw / #3044):** When OpenClaw Control UI is the operator control plane, SHOULD spawn the review-monitor with `visible:true` when the tool surface allows so humans can inspect progress without attaching to the parent session; invisible empty settles are higher FC04 residual risk.\n\n! When the platform descriptor indicates Tier 1 (sub-agent support), spawn a review-monitor sub-agent using the primitive matching the descriptor:\n\n1. ! Launch via the matching primitive: `start_agent` (Warp), `spawn_subagent` (grok-build / TUI / non-Warp), the Cursor `Task` tool with `run_in_background: true` (`cursor-composer` / `cursor-cloud-agent`, #1877), the Claude Code `Agent` tool with `run_in_background: true` (`claude-code` / register `claude-agent`, #3134), **or OpenClaw `sessions_spawn` (`openclaw`, #2876)** with a prompt that instructs it to poll for Greptile completion. For `spawn_subagent`, Cursor `Task`, Claude Code `Agent`, and OpenClaw `sessions_spawn` the prompt MUST reference the canonical poller template `templates/swarm-greptile-poller-prompt.md` (with placeholders filled) plus the agent preamble; the working directory / context must be the PR branch (worktree or equivalent for hybrid).\n2. ! The sub-agent polls using the mechanism for its primitive: for `spawn_subagent` use `get_command_or_subagent_output` (adaptive cadence: ~20-30s first check after push, ~60s second, ~90s thereafter; Greptile typically lands in 3-7 min); for `start_agent` the native messaging path; for the Cursor `Task` tool the backgrounded-task completion-notification path; for Claude Code `Agent` the backgrounded-agent completion-notification path; for OpenClaw `sessions_spawn` the host session completion / messaging channel (prefer `task pr:watch` inside the child when available). Front-load the first check to catch fast reviews.\n3. ! When the exit condition is met (Greptile review current on the HEAD commit SHA, confidence meets resolved min (policy/dogfood/default; see Step 6 #3095), no P0/P1 remaining), the sub-agent reports completion back to the parent (via `send_message_to_agent`, the spawn_subagent result channel, or the OpenClaw sessions completion channel).\n4. ! The main conversation pane stays fully interactive during monitoring -- the user (or parent monitor) can continue other work.\n5. ! On receiving the completion message / result, the parent re-fetches findings (both gh pr view --comments and the secondary source) and proceeds to Step 5.\n\n\u2297 Use OpenClaw `cron` alone as Approach 1 when `sessions_spawn` is available \u2014 cron is Approach 2 scheduler fallback only (#2876).\n\n### Empty announce \u2260 done (parent DoD) (#3044 / FC04 residual)\n\n! When a review-monitor settle arrives with **empty body**, **missing `STATUS:` line**, or **status unknown** (including host `(no output)` / empty `subagent_announce`):\n\n1. ! The parent MUST run **same-turn ground truth** before any DONE / CLEAN / merge-ready claim: at least `gh pr view <N>` (or REST `pulls/<N>`), `gh pr checks <N>`, and current HEAD SHA (`gh api repos/<owner>/<repo>/pulls/<N> -q .head.sha`).\n2. ! Classify the settle as **FC04 residual** (empty babysit \u2260 done) until ground truth shows a terminal merge/close outcome **or** an explicit structured `BLOCKED` / `FAILED` handback.\n3. \u2297 Treat empty / unknown settle as `DONE`, `CLEAN`, merge-ready, or batch-complete.\n4. \u2297 Spawn a second review-monitor solely because the first settle was empty/unknown without completing the ground-truth batch first (#3044 dual-lease recurrence).\n\n~ Recurrence: enterprize PR #43 (2026-08-02) \u2014 first monitor polled live, host settled empty/unknown; parent spawned a second same-`taskName` monitor; dual lease collision while PR stayed open. See also `meta/lessons.md` and FC04 / growth friction R1 + R10.\n\n\n### Completion latch on settle replay (#3092)\n\n! **Empty settle** is not a latch hit \u2014 use Empty announce \u2260 done (#3044) above. When the parent has already emitted **one** consolidate for a monitor/leaf `runId` and the harness re-delivers an **identical or equivalent** non-empty settle for the same key, stay **silent** (no re-QC, no second final; host silent token when defined). Re-open only on new runId, principal reopen, or material new evidence. Full MUST: `templates/agent-prompt-preamble.md` \u00a711.5.\n\n### Single review-monitor lease (#3044 / #2814)\n\n! **One sticky lease per PR:** ownership is the single sticky GitHub PR comment `<!-- deft:review-owner -->` (or the dual-invoke `review-monitor:register` form that writes it). Parallel ownership is forbidden.\n\n! **Pre-spawn check:** before launching another Approach 1 review-monitor (`sessions_spawn`, `spawn_subagent`, Cursor `Task`, Claude Code `Agent`, `start_agent`):\n\n1. ! Read the sticky lease (dual-invoke `verify:review-monitor` when available, else `gh api` issues comments for `<!-- deft:review-owner -->`).\n2. ! List active same-PR / same-`taskName` subagents when the host exposes that surface (OpenClaw `subagents list` or equivalent).\n3. \u2297 Spawn a second monitor while a prior owner is **running**.\n4. \u2297 Spawn a second monitor when the last settle was **empty/unknown** and ground truth has **not** shown a terminal merge/close (or explicit structured handback that releases ownership).\n5. ! If the prior owner is **dead** (liveness fail / `REDISPATCH_OK` / `verify:subagent-alive` exit 1) and the PR is still open: spawn **one** replacement monitor and re-claim the lease with **`--force`** (CLI: `deft review-monitor:register --pr <N> --monitor-agent-id <id> --force` / task: `task review-monitor:register -- --pr <N> --monitor-agent-id <id> --force`, or host equivalent force takeover) so a non-expired foreign lease does not block replacement \u2014 then **update** the sticky lease comment to the new owner. Never silent dual ownership.\n6. ! On register conflict when the prior owner is **still alive**: attach to the existing owner or stop \u2014 do not parallel-fix.\n7. \u2297 Refuse replacement of a dead owner solely because the 30-minute lease has not expired without attempting force takeover (#3044).\n\n### Required non-empty monitor handback (#3044)\n\n! Approach 1 review-monitor prompts (including `templates/swarm-greptile-poller-prompt.md` and any host-filled spawn prompt) MUST require a **non-empty** final handback with these fields:\n\n```text\nSTATUS: DONE|BLOCKED|FAILED\nHEAD: <sha>\nCHECKS: <summary>\nMERGE: <url|error|n/a>\nISSUE: <closed|open|n/a>\nNOTES: <short>\n```\n\n\u2297 Empty final assistant message from a review-monitor.\n\u2297 Parent treating a settle that lacks `STATUS:` as success.\n\n~ **Visible Control UI risk (#3044):** When OpenClaw Control UI is the operator plane, prefer `visible:true` on the review-monitor spawn; invisible empty settles are higher risk for FC04 misclassification. Cross-link: `skills/deft-directive-swarm/references/host-openclaw.md` Babysit / review-monitor residual.\n\n\n\n**Approach 2 (fallback -- no sub-agent primitive for the descriptor):**\n\n! When the platform descriptor indicates no sub-agent orchestration (or the primitive is unavailable), use discrete tool calls with a yield between checks. For `grok-build` / spawn_subagent descriptor this path is normally avoided in favor of Approach 1; it exists for pure interactive or limited runtimes.\n\n1. ! Use the current shell execution tool (`run_terminal_command` or equivalent in the runtime) in wait mode to run `gh pr view <number> --comments` and `gh pr checks <number>`.\n2. ! After each check, yield control (end all tool calls) -- the agent runtime will re-invoke after its interval or on next interaction.\n3. ! Target adaptive cadence (20-30s / 60s / 90s) where the runtime permits. The full cadence is easiest in Approach 1 (sub-agent) or 3 (blocking); pure yield is runtime-controlled.\n4. ! No blocking shell pane lock -- the conversation remains interactive between checks.\n5. ~ Approach 2 requires a periodic re-invocation trigger (timer, scheduler, user nudge, or external orchestrator for hybrid/worktree cases). Without it the poller stops after the first yield.\n6. ! When the exit condition is met, proceed to Step 5.\n\n\u26a0\ufe0f **Swarm / hybrid limitation**: Approach 2 is NOT autonomous for swarm agents or manual worktree setups. Yielding ends the turn with no self-wake; the parent monitor (or external scheduler) must detect idle and re-trigger or send a message. For true `grok-build` / spawn_subagent hybrids, prefer Approach 1 (spawn_subagent + get_command_or_subagent_output poller) exactly as the swarm launch adapter does.\n\n\u2297 Use blocking `Start-Sleep` shell loops or `time.sleep()` loops EXCEPT as Approach 3 (see below) -- these lock the conversation and prevent user interaction.\n\u2297 Poll more frequently than every 20 seconds -- use a real delay between checks, not back-to-back calls. Adaptive cadence (20-30s / 60s / 90s) replaces the fixed 60s minimum.\n\n**Approach 3 (last resort -- interactive session, no `start_agent`, no timer/scheduler):**\n\n! Approach 3 is a blocking sleep-poll loop used ONLY when both Approach 1 and Approach 2 are unavailable (interactive session with no `start_agent` and no auto-reinvocation mechanism). Uses PowerShell `sleep` / Unix `sleep` commands between polls.\n\n! **User warning gate:** Before activating Approach 3, the agent MUST warn the user that the conversation pane will be locked during polling and ask for explicit confirmation. Example: \"No sub-agent or auto-reinvocation available. I will poll in a blocking loop (~20-30s / 60s / 90s cadence). The conversation will be locked during polling. Proceed? (yes/no)\"\n\n\u2297 Activate Approach 3 without first warning the user that it will lock the conversation pane.\n\n1. ! After receiving user confirmation, use a blocking shell loop with adaptive cadence:\n - First check: wait ~25 seconds (e.g. `sleep 25`), then poll\n - Second check: wait ~60 seconds, then poll\n - Subsequent checks: wait ~90 seconds, then poll\n2. ! Poll using `gh pr view <number> --comments` and `gh pr checks <number>` in the same shell session\n3. ! When the exit condition is met (Greptile review current, confidence meets resolved min (policy/dogfood/default; see Step 6 #3095), no P0/P1), exit the loop and proceed to Step 5\n4. ! If the user interrupts (Ctrl+C or equivalent), exit gracefully and report current review status\n\n! Greptile may advance its review by **editing an existing PR issue comment** rather than creating a new PR review object. Do NOT rely solely on `pulls/{number}/reviews` \u2014 that endpoint may remain stale at an older commit SHA even after Greptile has reviewed the latest commit.\n\n! To confirm the review is current, check **both** surfaces:\n\n1. **PR issue comments** (primary signal) \u2014 Greptile edits its existing summary comment in place:\n - `gh pr view <number> --comments` (with `do_not_summarize_output: true`)\n - Or `gh api repos/<owner>/<repo>/issues/<number>/comments`\n - Parse the comment body for `Last reviewed commit` and compare to the pushed commit SHA\n - Check the comment's `updated_at` timestamp to confirm it was refreshed after your push\n2. **PR review objects** (secondary signal) \u2014 may or may not be updated:\n - `gh api repos/<owner>/<repo>/pulls/<number>/reviews`\n - Check `commit_id` on the latest review object\n\n! Treat an edited Greptile issue comment as a valid new review pass even if no new PR review object was created.\n\n! Fetch the full untruncated comment body or use MCP `get_comments` to get the actual commit URL containing the full SHA \u2014 do NOT rely on grepping truncated link text.\n\n\u2297 Re-fetch or re-trigger while the bot's last review still targets an older commit on **both** surfaces.\n\n### Step 5: Re-fetch and analyze\n\n! Fetch the new review using both methods from Step 1.\n\n! Analyze all new findings before planning any changes.\n\n### Step 6: Exit condition check \u2014 fail-closed ReviewerStatus all-of (#1259)\n\n! The loop MAY exit clean ONLY when a SINGLE fresh fetch (not cached state, not a verdict assembled across earlier polls) satisfies ALL of the `ReviewerStatus` fields below. This is a **fail-closed all-of**: any field that is missing, unparsed, or ambiguous resolves to **`unknown`**, and `unknown` is NOT a pass \u2014 the agent stays in the loop and returns to Step 2. A PARTIAL or STALE Greptile review MUST NOT satisfy the exit predicate; the predicate is what prevents merging un-reviewed code while a P0/P1 finding is still in flight (#1259).\n\n1. ! **Terminal check-run** \u2014 the `Greptile Review` check run on the current HEAD has `status == \"completed\"` AND `conclusion` in `{success, neutral}`. The conclusions `null`, `cancelled`, `timed_out`, `stale`, `action_required`, and `failure` are explicitly NOT terminal-clean: any of them resolves to `unknown` and the loop continues. A check run still `queued` / `in_progress` is `unknown`.\n2. ! **HEAD-SHA pinned AT READ TIME** \u2014 read the current HEAD SHA in the SAME fetch used to evaluate this predicate (`gh api repos/<owner>/<repo>/pulls/<number> -q .head.sha`, read AT exit-evaluation time, NOT carried over from an earlier poll) and require `head_sha_reviewed == current HEAD`. A review whose reviewed SHA lags HEAD is `unknown`.\n3. ! **Completion marker present and matching** \u2014 the rolling-summary comment body carries `Last reviewed commit: <sha>` AND that `<sha>` matches the current HEAD. Extract the SHA with the markdown-link-aware NON-GREEDY regex below. Markdown link text can contain escaped brackets (e.g. a commit subject `add \\[Unreleased\\] entry`), so a greedy `[^\\]]*` stops at the first `]` and yields no match \u2192 false `unknown` on a clean review (#1326):\n\n ```\n Last reviewed commit:\\s*\\[.*?\\]\\(https?://github\\.com/[^/]+/[^/]+/commit/(?P<sha>[0-9a-f]{7,40})\n ```\n\n A missing or non-matching completion marker is `unknown`. See [`../../templates/swarm-greptile-poller-prompt.md`](../../templates/swarm-greptile-poller-prompt.md) `### Last reviewed commit:` for the canonical regex shared with the push-driven poller loop.\n4. ! **Confidence meets resolved min (#3095)** \u2014 the parsed `Confidence Score: X/5` is **>=** the resolved floor from `plan.policy.review.minGreptileConfidence` (inspect: `task policy:show --field=minGreptileConfidence`; `pr:watch` / `pr:merge-ready` share this SoT). Resolution order: typed project policy > framework dogfood detect (framework source \u2192 **5**) > consumer default (**4**, legacy confidence > 3 / 4/5+). A score below the floor, an unparsed confidence, or an absent confidence is `unknown`. Directive dogfood MUST NOT exit CLEAN on 4/5.\n5. ! **No P0/P1 findings** \u2014 the triple-tier (+ Tier 2.5) detector reports zero P0 and zero P1 findings (P2 issues are non-blocking style suggestions and do not gate the loop).\n\n! All five fields MUST hold on the SAME single fresh fetch. The agent MUST NOT assemble a \"pass\" by combining a terminal check-run observed on one poll with a confidence parsed on an earlier poll \u2014 the read is atomic per the SHA-pinned-AT-READ-TIME rule above.\n\n? If the bot says \"all prior issues resolved\" but lists new issues, treat it as one final batch \u2014 not the start of another loop. Go back to Step 2 one more time, re-evaluate this all-of, then stop.\n\n\u2297 Exit the loop on a confidence number alone while the check run is non-terminal (`queued` / `in_progress` / `cancelled` / `timed_out` / `stale` / `action_required`) \u2014 a confidence score is NOT a verdict without a terminal check-run AND a HEAD-matching completion marker (#1259).\n\u2297 Exit the loop against a reviewed SHA that lags the current HEAD \u2014 a partial or stale review MUST resolve to `unknown`, never to a pass (#1259).\n\nIf the exit predicate is not met (any field `unknown`), go back to Step 2.\n\n## Mechanical mergeability is necessary, never sufficient (#3225)\n\n! GitHub **Ready to merge**, green required checks, and formal review state without Changes-Requested are **necessary but never sufficient** clean signals. Reviewer bots on repos without enforced review wiring often express **should-not-merge** + sub-threshold confidence **only in comment body prose** (no formal `REQUEST_CHANGES`, no blocking CheckRun). A shepherd that merges on mechanical signals alone merges against explicit advisory verdicts.\n\n! **`task pr:merge-ready` / `task pr:watch` / Step 6 clean** MUST parse advisory bot verdict text and confidence from comment bodies (the #1282-style body extraction path; shared detector in `packages/core/src/content-contracts/skills/greptile-detector.ts`). Treat any of the following as **blocking** regardless of formal review state or the Ready-to-merge box:\n\n1. Advisory should-not-merge prose (`should-not-merge`, `Not safe to merge`, `Do not merge`, `Safe to merge once corrected`, `not ready to merge`, \u2026)\n2. Confidence below the resolved `minGreptileConfidence` floor (#3095 \u2014 project policy > dogfood 5 > consumer default 4)\n3. P0/P1 findings (triple-tier + inline threads) or errored Greptile sentinel\n\n! When advisory prose blocks or confidence is sub-threshold: continue the fix/document loop or exit **BLOCKED** \u2014 \u2297 do not treat mechanical mergeability as CLEAN.\n\n~ Recommend repo-level review-gate wiring (required review / blocking Greptile CheckRun) for org repos that lack it, so formal state and prose verdict cannot diverge silently. Directive dogfood already enforces #3095; portable babysit paths on other org repos still need this prose gate.\n\n\u2297 Merge because the merge box says Ready to merge while bot comment prose says should-not-merge or confidence is below the resolved floor (#3225 / #3095).\n\u2297 Treat formal Comment (non-blocking) review state as sufficient when the rolling-summary body carries an advisory block.\n\n## Pre-Merge Re-Poll Gate (#1259)\n\n! Immediately before any `gh pr merge` invocation, the agent MUST re-fetch reviewer state ONE more time \u2014 a fresh `gh pr view <number> --comments`, a fresh `gh api repos/<owner>/<repo>/commits/<HEAD>/check-runs`, and a fresh HEAD-SHA read \u2014 and re-evaluate the Step 6 fail-closed all-of against that fresh fetch. The exit-condition pass recorded at the end of the review loop is NOT sufficient authorization to merge: review state can go stale between the loop's last poll and the merge call (a new push, a Greptile re-trigger, a service-side check-run reset).\n\n! Treat the re-poll and the `gh pr merge` as an atomic freshness window. If the re-poll shows ANY field `unknown`, ABORT the merge and return to Step 2.\n\n! Re-poll MUST also re-check advisory should-not-merge prose + confidence (#3225) \u2014 mechanical Ready-to-merge alone is never sufficient.\n\n\u2297 Call `gh pr merge` on the strength of a review verdict observed earlier in the loop without an immediately-preceding re-poll that re-satisfies the Step 6 all-of \u2014 merging on cached review state is forbidden (#1259).\n\u2297 Call `gh pr merge` on mechanical Ready-to-merge / green checks while advisory bot prose still records should-not-merge or sub-threshold confidence (#3225).\n\n### Informal-clean missing canonical fields (#1543)\n\nGreptile can post a **separate** informal clean reply that says prior issues are resolved and the current diff is clean while omitting the canonical rolling-summary fields Directive merge gates require: `Last reviewed commit:` and `Confidence Score: X/5`. `task pr:merge-ready` and `task swarm:verify-review-clean` correctly refuse merge-ready in this state -- prose alone cannot prove review currency or confidence.\n\n! When the latest Greptile bot comment is found, reports P0=0 and P1=0, but BOTH canonical fields are unparsed, classify the state as **`informal-clean missing-canonical-fields`** (see `task pr:merge-ready` diagnostic output) instead of treating it as \"review still writing\" or silently polling.\n\n! Recovery for informal-clean missing canonical fields -- route to ONE of these operator actions; do NOT keep polling:\n\n1. Comment `@greptileai review` on the PR to retrigger a canonical rolling summary on the current HEAD.\n2. Wait for Greptile to edit its primary rolling-summary comment with both canonical fields, then re-run `task pr:merge-ready -- <N>`.\n3. Document an explicit operator override per `skills/deft-directive-swarm/SKILL.md` Phase 6 Step 1 (merge with rationale in the merge commit body).\n\n\u2297 Treat informal clean Greptile prose (`current diff is clean`, `looks solid`, `no new issues`) as merge-ready without canonical `Last reviewed commit:` and `Confidence Score: X/5` evidence.\n\n\u2297 Keep polling silently when `task pr:merge-ready` reports the informal-clean missing-canonical-fields diagnostic -- this is a blocked recovery state, not a late-arriving review.\n\n~ Swarm pollers MUST surface this state via the `### (6) INFORMAL-CLEAN` terminal exit in `templates/swarm-greptile-poller-prompt.md` instead of falling through to generic `(4) TIMEOUT` or `(5) STALL`.\n\n## Submitting GitHub Reviews\n\n! When submitting PR reviews via the GitHub MCP tool, always use `pull_request_review_write` with method `create` and the appropriate event:\n\n- `APPROVE` \u2014 formally approve the PR (shows green \"Approved\" status)\n- `REQUEST_CHANGES` \u2014 block the PR with requested changes\n- `COMMENT` \u2014 review feedback without approving or blocking\n\n\u2297 Use `add_issue_comment` for review notes \u2014 that creates a regular comment, not a formal review. Review notes must always go in the review body via `pull_request_review_write`.\n\n## GitHub Interface Selection\n\n~ Use the most efficient interface for the task:\n\n- **MCP GitHub tool** \u2014 structured/programmatic operations (querying issues, creating PRs, bulk operations, filtering data)\n- **GitHub CLI (`gh`)** \u2014 quick ad-hoc commands and direct shell integration\n\nChoose whichever minimizes steps and maximizes clarity for the given task.\n\n~ When MCP is unavailable (agents without MCP tools in their dispatch environment, including `start_agent` / `spawn_subagent` (\"grok-build\") cases, cloud agents, `oz agent run`), `gh` CLI is sufficient as the sole interface. The dual-source requirement (MCP + `gh`) in Step 1 applies only when both are available -- agents without MCP access should use `gh pr view --comments` and `gh api` as their primary and only review detection surface. Runtime capability detection (swarm Phase 3 matrix) informs both orchestration tier and MCP surface choice.\n\n## Framework Events Emitted Here\n\n! When the user replies `yes` / `confirmed` / `approve` on a ready-to-merge PR thread (Phase 5 -> 6 gate per the canonical #642 workflow comment), emit a `plan:approved` framework event via `task lifecycle:event` so the approval is captured as a structural artifact rather than prose-only:\n\n```\ntask lifecycle:event -- emit plan:approved \\\n --plan-ref https://github.com/<owner>/<repo>/pull/<N> \\\n --approver <github-login> \\\n --approval-phrase <yes|confirmed|approve> \\\n --pr-number <N>\n```\n\n? Downstream consumers of `plan:approved` (auto-merge bots, status updates, audit reporting) are explicitly deferred to follow-up work; this event currently emits a record only (#635 events behavioral wiring).\n\n## Post-Merge Verification\n\n! Apply [`coding/review.md`](../../coding/review.md) post-merge closing-keyword verification. Adapter HOW for GitHub:\n\n! After a PR is squash-merged, verify that all referenced issues were actually closed. Squash merges can silently fail to process closing keywords (`Closes #N`, `Fixes #N`) from the PR body (#167).\n\n1. ! For each issue referenced with a closing keyword in the PR body, run:\n ```\n gh issue view <N> --json state --jq .state\n ```\n2. ! If the issue state is not `CLOSED`, close it manually with a comment referencing the merged PR:\n ```\n gh issue close <N> --comment \"Closed by #<PR> (squash merge \u2014 auto-close did not trigger)\"\n ```\n3. ~ This step mirrors `skills/deft-directive-swarm/SKILL.md` Phase 6 Step 2 and applies to ALL PR merges, not just swarm runs.\n4. ! For PRs that referenced any umbrella / staying-OPEN issue (`Refs #N`), the INVERSE check applies: any protected issue that auto-closed MUST be reopened with a comment citing #701 and the merged PR. See `skills/deft-directive-swarm/SKILL.md` Phase 6 Step 1 protected-issue reopen sweep and `meta/lessons.md` `## GitHub Closing-Keyword False-Positive Layer 3` for the persistent `closingIssuesReferences` link case (Layer 3, #701).\n\n\n## Probe-then-fill remote claims (#3120)\n\n! Before filling any **remote** handoff field (PR URL, PR number, commit/HEAD SHA, CI green/success, review score) or claiming `status: pass` / ship/gate done, MUST **probe then fill**:\n\n1. Run same-turn `git` + forge probes (examples: `git rev-parse HEAD`, `gh api repos/<owner>/<repo>/pulls/<N>`, `task pr:watch -- <N> --one-shot`, checks API).\n2. Copy IDs / URLs / SHAs / scores **only** from that probe JSON/text into the evidence block.\n3. Set `proof_status: bound` and attach short raw probe snippets (`command` + `snippet`) for each remote claim.\n\n! Handoff evidence axes: **work** (local) / **ship** (pushed branch or PR) / **gate** (CI/review on HEAD). `proof_status` is `bound` | `unbound` | `n/a-no-remote-claim`.\n! **Legal partial:** local work `done` + ship `not_started` / `blocked` **without** PR/SHA/CI/review fields and `proof_status: n/a-no-remote-claim` (or `status: partial`) is valid \u2014 do not invent ship state.\n! **Fail ranking:** **invented-done** (false/unbound remote artifacts under pass) is **stricter** than **empty-done**. Unbound remote claims \u2192 invalid evidence (fail), not pass-with-notes.\n! Machine check: `validateHandoffEvidence` in `packages/core/src/handoff-evidence/` (see `templates/agent-prompt-preamble.md` \u00a711).\n\u2297 Fill PR / SHA / CI / review fields from recollection, narration, or prior-turn memory.\n\u2297 Claim `status: pass` with remote fields when `proof_status` is not `bound` or probes are missing (#3120).\n\n## Anti-Patterns\n\n- \u2297 Multi-hour empty-commit / close-reopen thrash after CI weather thrash caps when `ci_never_scheduled` or `ci_cancelled_no_failover` (#3167)\n- \u2297 Workflow thrash or empty-commit spam during attributed platform outage without status-page probe (#3180)\n- \u2297 Merge or `--skip-ci` solely because a status page is red without check-run evidence (#3180)\n- \u2297 Block merge-ready wait on SLizard alone when Greptile Step 6 is clean (#3167)\n- \u2297 Silent admin / `--skip-ci` merge under Actions outage without audit comment and opt-in authority (#3167)\n- \u2297 Leave a deliberate `stop-at: pr-open` (or thin-DONE recovery) open PR without spawning/retaining one review-cycle babysit owner + lease continuity and post-merge `scope:complete` plan (#3153)\n- \u2297 Stand down at CLEAN under human-merge policy without a durable owner (sticky lease + live parent/monitor/Phase 6 closer) **and** a post-CLEAN observe path (poller / parent wake / Phase 6 re-poll) for post-merge `scope:complete` (#3153 / #1193 / #2321)\n- \u2297 Handoff human-merge cleanup to a short-lived leaf that exits at CLEAN without re-claiming the sticky lease (#3153)\n- \u2297 Retain only a sticky lease after CLEAN with no poller, no parent re-entry, and no Phase 6 merge re-poll \u2014 ownership-in-name-only (#3153)\n- \u2297 Dual-lease or freestyle Cursor global babysit for the partner merge-path after implement stops at PR-open (#3153 / #2261 / #3044)\n- \u2297 End owning turn with 0 children, no sticky lease, and no finish after drive-to-merge / babysit / shepherd claim \u2014 silent hold (#3090)\n- \u2297 Emit freeform `review_cycle: started` / `pending` / `initiated` or L4 `status: pass` without `done` or verifiable `in_progress:<pr>#\u2026` lease/parent-retained (#3090)\n- \u2297 Treat check-run SUCCESS alone as CLEAN / merge-ready while dual-source P0/P1 remain (#3090)\n- \u2297 Ignore [`coding/review.md`](../../coding/review.md) while running this adapter \u2014 universal batch/severity/exit/post-merge rules live there\n- \u2297 Route PR shepherding to Cursor global `babysit` on Deft-managed repos when `.deft/core/` is installed -- use this review-cycle skill instead (#2261)\n- \u2297 Route OpenClaw babysit/shepherd/watch to main-session gh poll + cron when `sessions_spawn` is available -- use Approach 1 with `sessions_spawn` (#2876 / #2261)\n- \u2297 Treat OpenClaw `cron` alone as Approach 1 \u2014 cron/timer is Approach 2 only if spawn is unavailable (#2876)\n- \u2297 Route Claude Code babysit/shepherd/watch to Approach 3 blocking poll when Claude `Agent` spawn is available \u2014 use Approach 1 with backgrounded `Agent` / `claude-agent` (#3134)\n- \u2297 Misclassify Claude Code as `cursor-composer` from bare `Task` alone (#3134)\n- \u2297 Expand active story scope past xBRIEF AC mid-babysit without follow-up issue or consented brief amend (#2881)\n- \u2297 Treat confidence-only holds (0 P0/P1) as a mandate for unbounded redesign (#2881)\n- \u2297 Invent freestyle sleep/poll loops when dual-invoke probes fail for `pr:watch` \u2014 use the official gh-only fallback and fail-loud missing-task (#2878 / #2893)\n- \u2297 Treat bare `task pr:watch` as the only consumer gate form \u2014 probe `deft` then `task deft:` first (#2893)\n- \u2297 Treat a passing SLizard/Greptile check run, a non-blocking review comment, or an ad hoc fix commit as the review-cycle exit predicate -- Step 6 fail-closed all-of (#1259) and multi-reviewer registry triage (#769) still apply\n- \u2297 Push individual fix commits per finding\n- \u2297 Start fixing before analyzing ALL findings\n- \u2297 Rely on the bot to catch syntax errors in structured data files\n- \u2297 Re-trigger a bot review before the previous one has updated\n- \u2297 Report \"all comments resolved\" without checking both `gh pr view --comments` and a second source (`get_review_comments` via MCP, or `gh api` fallback when MCP is unavailable)\n- \u2297 Use `add_issue_comment` for formal review submission\n- \u2297 Commit or push Phase 1 audit fixes independently \u2014 always batch with Phase 2 fixes\n- \u2297 Proceed to Phase 2 while any Phase 1 prerequisite is unmet\n- \u2297 Rely solely on `pulls/{number}/reviews` to detect whether Greptile has reviewed the latest commit \u2014 Greptile may update via an edited issue comment instead of a new review object\n- \u2297 Push additional commits while Greptile is reviewing the current head \u2014 each push re-triggers Greptile and resets the review clock\n- \u2297 Use blocking `Start-Sleep` shell loops or `time.sleep()` loops to poll for review updates when Approach 1 or 2 is available -- Approach 3 (blocking loop) is permitted only as a last resort with user warning\n- \u2297 Poll more frequently than every 20 seconds -- use a real delay between checks, not back-to-back calls; adaptive cadence (20-30s / 60s / 90s) replaces the fixed 60s minimum\n- \u2297 Stop and ask the user whether to continue after pushing -- the review/fix loop MUST run autonomously to the exit condition\n- \u2297 Push fix commits without scanning changed lines for untested code paths \u2014 always check test coverage before pushing\n- \u2297 Push a fix commit that addresses fewer findings than the current Greptile review surfaces \u2014 if Greptile flags 3 issues, all 3 must be fixed in one commit before pushing\n- \u2297 Push after fixing a P1 without first checking whether the same Greptile review contains additional P0 or P1 findings\n- \u2297 Assume squash merge auto-closed referenced issues \u2014 always verify with `gh issue view` after merge (#167)\n- \u2297 Assume Approach 2 (yield-between-polls) produces a self-sustaining polling loop -- yielding ends the agent's turn with no self-wake; swarm agents will silently stop polling\n- \u2297 Skip the second review source (MCP or `gh api` fallback) without probing for MCP capability and documenting the fallback used\n- \u2297 Run a partial test suite instead of `task check` without documenting the pre-existing failure reason and open issue number in the PR body\n- \u2297 Create a PR without running `skills/deft-directive-pre-pr/SKILL.md` first -- the pre-PR quality loop catches issues before they reach the reviewer\n- \u2297 Activate Approach 3 (blocking `Start-Sleep` loop) without first warning the user that it will lock the conversation pane and receiving confirmation\n- \u2297 Exit the review loop on a Greptile confidence number alone while the check run is non-terminal -- a confidence score is NOT a verdict without a terminal check-run (`completed` + `{success, neutral}`) AND a HEAD-matching `Last reviewed commit:` completion marker (#1259)\n- \u2297 Call `gh pr merge` on cached/earlier review state without an immediately-preceding pre-merge re-poll that re-satisfies the Step 6 fail-closed all-of (#1259)\n- \u2297 Merge on mechanical Ready-to-merge / green checks while bot comment prose records should-not-merge or confidence below `minGreptileConfidence` (#3225 / #3095)\n- \u2297 Treat formal non-blocking review state as sufficient when rolling-summary body carries an advisory block (#3225)\n- \u2297 Treat empty/unknown review-monitor settle as DONE/CLEAN/merge-ready without same-turn ground truth (#3044 / FC04 residual)\n- \u2297 Spawn a second review-monitor while prior owner is running or last settle was empty/unknown without terminal ground truth (#3044)\n- \u2297 Accept empty review-monitor final message missing STATUS/HEAD/CHECKS/MERGE handback (#3044)\n- \u2297 Invent remote PR/SHA/CI/review claims in handoff evidence without same-turn probe binding \u2014 invented-done (#3120)\n- \u2297 Fill remote ship/gate fields from memory when only local work completed; legal partial omits PR fields (#3120)",
272
+ "body": "# Deft Directive Review Cycle\n\nStructured workflow for responding to bot reviewer (Greptile) findings on a PR.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, \u2249=SHOULD NOT, \u2297=MUST NOT, ?=MAY.\n\n## Principle Authority (#1471 / #212)\n\n! Universal review-cycle principles live in [`coding/review.md`](../../coding/review.md) (RFC2119): read-all-findings, severity P0/P1/P2 + merge-blocking semantics, single batch commit, cross-file grep of changed terms, local structured-data validation (SHOULD), no push mid-review, exit when no P0/P1 remain (P2 non-blocking), and post-merge closing-keyword verification.\n\n! This skill is the **Greptile + GitHub adapter** only: polling cadence, confidence-score thresholds, check-run detection, dual-source fetch (`gh` + MCP) for Comments Outside Diff, fail-closed Step 6 `ReviewerStatus`, review-monitor lease, and merge gates. Apply `coding/review.md` for the process; do not restate that principle list inline.\n\n~ Future adapters (CodeRabbit, Codacy, host babysit) SHOULD implement the same `coding/review.md` principles with their own mechanics.\n\n## Platform Requirements\n\n! This skill requires **GitHub** as the SCM platform and the **GitHub CLI (`gh`)** to be installed and authenticated. PR comment fetching, check-run queries, and review submission all depend on `gh`.\n\n\n## Ordered-plan exit / advance (#2402)\n\n! When the review-cycle exit condition is met (no P0/P1 remaining / CLEAN verdict):\n\n1. Return control to the caller \u2014 do **not** discover adjacent backlog work.\n2. If an ordered-plan sequence is active and this PR matched the current entry, run `task plan-sequence:advance`.\n3. If another entry remains, the caller may continue **only** to that entry (one unit).\n4. If the sequence is exhausted, stop and ask. Do not open another PR from queue intuition or chaining text.\n\n\u2297 Exit the review cycle into `task triage:queue` or an unrelated PR without fresh operator approval.\n\n## When to Use\n\n- User says \"review cycle\", \"check reviews\", or \"run review cycle\" on a PR\n- Operator asks to **babysit**, **shepherd**, or **watch** a PR -- including the Cursor product action **babysit-pull-request-in-cloud** (#2261 / #1862 intent-routing class)\n- A bot reviewer (Greptile) has posted findings on an open PR\n- Dispatching a cloud or background agent to monitor and resolve PR review findings until merge-ready\n- Operator re-authorizes after conf-hold / dual-stop residual: **pursue residual**, **follow-up hard-stop**, **same as conf-hold**, **continue dual-stopped PR**, or **re-babysit residual** \u2014 route to \u00a7 Operator follow-up after dual-stop / hard stop (#3273)\n\n## Cursor global babysit supersession (#2261)\n\nOn repos with `.deft/core/` installed, **PR shepherding intent** routes here -- not the Cursor-global `babysit` skill (`~/.cursor/skills-cursor/babysit/SKILL.md`). The product action **babysit-pull-request-in-cloud** shares the babysit name but MUST chain into this review-cycle surface on Deft-managed projects.\n\n- ! Orchestrators dispatching cloud/background workers for PR shepherding MUST include `templates/agent-prompt-preamble.md` (or reference it) and mandate reading this skill as the first workflow step.\n- ! Cloud babysit workers use `worker_role: review-monitor` (or `drive-to: merge-ready` implementation workers that own the review cycle) -- not a generic babysit loop without Phase 1 audit or Step 6 exit predicate (#1259).\n- \u2297 Route **babysit-pull-request-in-cloud** to Cursor global babysit when `.deft/core/` is present -- that bypasses xBRIEF preflight, `task check`, Greptile fail-closed exit, and CHANGELOG discipline (#2261 recurrence).\n\n### OpenClaw babysit supersession (#2876 / #2261)\n\nOn OpenClaw hosts with Directive installed (`.deft/core/` or equivalent content deposit), **babysit / shepherd / watch** intent likewise routes here -- not host-local freestyle poll loops and not OpenClaw `cron` alone.\n\n- ! When the OpenClaw tool surface exposes `sessions_spawn`, Approach 1 is the **default** babysit path: spawn a background review-monitor via `sessions_spawn` (register with `--platform-primitive sessions_spawn` or the alias `openclaw-sessions-spawn`).\n- ! Prefer a **visible** Control UI subagent (`visible:true` when the tool surface allows) when OpenClaw Control UI is the operator control plane so humans can inspect the monitor (#3044; invisible empty settles are higher FC04 residual risk).\n- ! Long review-monitor ownership (>~3 min) MUST NOT block the parent OpenClaw session \u2014 background `sessions_spawn` + parent yield; same Gap D rule as Cursor/Grok Build (#1880).\n- ! Prefer deep-think gates inside the monitor via the dual-invoke probe order (#2893): `deft pr:watch` / `deft pr:merge-ready` first, then `task deft:pr:watch` when the Taskfile include is present, then the #2878 gh-only fallback \u2014 bare `task pr:watch` is not the consumer form.\n- \u2297 Treat OpenClaw `cron` (or any host scheduler alone) as Approach 1. Cron/timer re-invocation is Approach 2 only when `sessions_spawn` is unavailable.\n- \u2297 Freestyle main-session `gh pr view` / `sleep` poll + ad-hoc cron when `sessions_spawn` is available \u2014 that is the statusreport#153 / #2876 process-routing failure mode.\n\n## Branch-Protection Policy Guard\n\n! Before entering the review/fix loop, run the skill-level branch-policy guard (#746 / #747). Halt before any state mutation if the project's `plan.policy.allowDirectCommitsToMaster` is unresolvable AND the operator has not set `DEFT_ALLOW_DEFAULT_BRANCH_COMMIT=1`. Concretely:\n\n```\ntask verify:branch || exit 1\n```\n\nThe skill MUST NOT modify files, push, or comment on the PR until the guard passes -- this catches the case where a malformed PROJECT-DEFINITION quietly disabled the policy and the agent would have committed directly to master mid-review.\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (Phase 1 audit gates, Phase 2 Step 4 monitoring approach selection, Phase 5->6 ready-to-merge gate, Step 6 exit-condition prompts) MUST follow [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md): the final two numbered options MUST be `Discuss` and `Back`, in that order. The Discuss-pause semantic is documented verbatim there -- on `Discuss` selection the agent MUST halt the in-progress sequence immediately, prompt `What would you like to discuss?`, and resume only on an explicit user signal (re-asking the original question, saying `resume`/`continue`, or re-issuing the prior selection). Implicit resumption is forbidden.\n\n## Pre-Flight Check\n\n! Before entering the review/fix loop, verify the Greptile configuration supports it:\n\n1. ! `triggerOnUpdates` must be enabled (via Greptile dashboard or `.greptile/config.json`) \u2014 without this, Greptile only reviews the initial PR and never re-reviews after fix pushes, so the loop cannot reach the exit condition\n2. ~ `statusCheck` should be enabled so Greptile posts a `\"Greptile Review\"` check run on each commit \u2014 this is the signal the org ruleset uses to gate merges\n3. ? If Greptile does not re-review after a push despite `triggerOnUpdates` being enabled, comment `@greptileai` on the PR as a manual re-trigger fallback\n\n! Greptile posts **check runs** (GitHub Checks API), not **commit statuses** (Statuses API). To verify the check run is present on a commit:\n\n```\ngh api repos/<owner>/<repo>/commits/<sha>/check-runs --jq '.check_runs[] | select(.name == \"Greptile Review\")'\n```\n\n\u2297 Use `commits/<sha>/statuses` to check for Greptile \u2014 that endpoint will always be empty.\n\n~ See `tools/greptile.md` for recommended dashboard and per-repo settings.\n\n## Phase 1 \u2014 Deft Process Audit\n\n! Before touching code, verify ALL prerequisites are satisfied. Fix any gaps first:\n\n1. ! Verify `skills/deft-directive-pre-pr/SKILL.md` was run before PR creation -- the PR branch should have passed at least one full pre-PR cycle (Read-Write-Lint-Diff). If not, run it now before proceeding.\n2. ! `PROJECT-DEFINITION.xbrief.json` and `xbrief/` lifecycle folders have scope xBRIEF coverage for all changes in the PR\n3. ! `CHANGELOG.md` has entries under `[Unreleased]` for the PR's changes\n4. ! `task check` passes fully (fmt + lint + typecheck + tests + coverage \u226575%)\n5. ! `.github/PULL_REQUEST_TEMPLATE.md` checklist is satisfied in the PR description\n6. ! If the PR touches 3+ files: verify a `/deft:change` `proposal.xbrief.json` exists in `history/changes/` for this branch and was explicitly confirmed by the user (affirmative response, not a broad 'proceed'), or document N/A with reason in the PR checklist\n7. ! Verify the PR is on a feature branch -- work MUST NOT have been committed directly to the default branch (master/main)\n\n~ **PR scope gate:** If the PR spans 3+ unrelated surfaces (e.g. a skill, a tool doc, and a strategy -- with no shared issue or scope xBRIEF linking them), warn the user that broad PRs increase review churn and Greptile noise. Recommend splitting into focused PRs unless all changes trace to the same scope xBRIEF or issue bundle.\n\n! Phase 1 audit gaps must be resolved before merging \u2014 but hold the fixes (do NOT commit or push them independently). Proceed to Phase 2 analysis to gather bot findings, then batch all Phase 1 + Phase 2 fixes into a single commit.\n\u2297 Commit or push Phase 1 audit fixes independently before gathering Phase 2 findings.\n\n## Phase 2 \u2014 Review/Fix Loop\n\n### Step 1: Fetch ALL bot comments\n\n! Retrieve findings using BOTH methods \u2014 each catches different comment categories:\n\n```\ngh pr view <number> --comments\n```\n\n! Use `do_not_summarize_output: true` \u2014 summarizers silently drop the \"Comments Outside Diff\" section from large bot comments.\n\n~ **Oversized output fallback:** If `do_not_summarize_output: true` produces output too large to process, extract the relevant section with:\n\n- **PowerShell (Windows):** `gh pr view <number> --comments | Select-String \"Outside Diff\" -Context 50`\n- **Unix/macOS:** `gh pr view <number> --comments | grep -A 50 \"Outside Diff\"`\n\nBoth commands extract the \"Comments Outside Diff\" section with surrounding context, avoiding the need to process the full output.\n\n~ **Windows + Grok Build (#1353):** Avoid `|`, `>`, or `2>&1` in `run_terminal_command` strings -- use Python `pathlib`/`subprocess` or plain task commands instead.\n\n! **MCP capability probe** (mirrors deft-directive-swarm Phase 3 pattern): Before attempting MCP `get_review_comments`, probe whether MCP GitHub tools are available in the current session. Detection: attempt a lightweight MCP call (e.g. list available tools or a no-op query) -- if it succeeds, MCP is available; if it errors or the tool is not in the available set, MCP is unavailable.\n\n- **MCP available**: ! Use MCP `get_review_comments` as the second source to catch Comments Outside Diff.\n- **MCP unavailable** (e.g. non-MCP agents including `start_agent` / `spawn_subagent` (\"grok-build\") dispatch, cloud agents, `oz agent run`): ! Use `gh api repos/<owner>/<repo>/pulls/<number>/comments` as the explicit fallback for the second review source. Document in the commit message or PR comment why MCP was skipped (e.g. \"MCP unavailable in this session -- used gh api fallback for review comments\"). The platform descriptor from runtime detection determines MCP availability independently of the dispatch primitive.\n\n\u2297 Report \"all comments resolved\" without verifying both sources.\n\u2297 Skip the second review source without probing for MCP capability and documenting the fallback used.\n\n~ **Late-arriving bot review re-check:** If the initial dual-source fetch returns no bot review on the current HEAD SHA, wait ~60s and re-fetch before evaluating the Step 6 exit condition. Bot reviewers (Greptile) typically land within 3-7 min of PR creation/push; an empty first pass is more likely \"review pending\" than \"review clean\".\n\n\u2297 Declare the exit condition met based on a single fetch that returned no bot review \u2014 re-fetch at least once after a ~60s delay first.\n\n~ This codifies a user-rule precedent on late-arriving bot reviews into the deft-internal deterministic tier. The [`templates/swarm-greptile-poller-prompt.md`](../../templates/swarm-greptile-poller-prompt.md) loop body already handles the same case for push-driven cycles via its per-poll fetch -- the rule above closes the orthogonal cold-start path where the one-shot review-cycle entry runs on a freshly-opened PR before any fix push has triggered the Step 4 polling loop.\n\n### Step 2: Analyze ALL findings before changing anything\n\n! Apply [`coding/review.md`](../../coding/review.md) before any code change: read **all** findings, classify P0/P1/P2, and plan **one** batch. Do not start per-finding fixes mid-read.\n\nGreptile adapter analysis extras:\n\n- Identify cross-file dependencies (a term, value, or field mentioned in multiple files)\n- ! **Scope-check each finding against the active story xBRIEF** (`plan.items[].narrative.Acceptance`) before coding \u2014 see Out-of-AC gate (#2881) below\n\n### Out-of-AC findings / active-story scope gate (#2881)\n\nBabysit and review-cycle are **not** a second unbounded implementation mandate. When Greptile (or another reviewer) raises design-adjacent work outside the active story's acceptance criteria, default to follow-up \u2014 not silent redesign mid-babysit (PR #2871 / #2869 \u2192 #2880 recurrence).\n\n! Given an active story xBRIEF with fixed `plan.items`, when a finding is **outside** those Acceptance criteria:\n\n1. ! File or propose a **follow-up** GitHub issue / scope xBRIEF for the out-of-AC work, **or**\n2. ! Amend the active brief's `plan.items` (and narratives) **with explicit operator consent** before implementing a new subsystem,\n3. ! Then continue babysit only for in-AC and carve-out findings.\n\n! **P0 carve-out vs new-subsystem-needs-story:**\n\n- ! P0 security / correctness defects on files **already touched** by the PR MAY land in the same PR without a new story.\n- ! New ledgers, idempotency protocols, cross-cutting reliability contracts, or multi-commit redesigns that expand story meaning **require** a separate story or an amended brief before code.\n\n! **Confidence-only holds (0 P0/P1):** when confidence is below threshold (e.g. `Confidence Score: 3/5`) with zero P0 and zero P1 findings, the skill does **not** mandate unbounded redesign to raise confidence. Offer one of:\n\n1. Follow-up issue / residual-risk note in the PR,\n2. Operator override path (document in PR comment),\n3. Minimal in-AC polish only \u2014 then re-evaluate Step 6.\n\n! **`issue:emit` related-ref footgun:** `task issue:emit` treats any `plan.references[]` entry whose type matches `github-issue` / `x-xbrief/github-issue` / `x-vbrief/github-issue` as **already tracked** and SKIPs creating a new issue. When linking **related** (non-primary) work:\n\n- ! Use a non-emit-tracking type for related issues (e.g. keep related links in narratives / PR body / `Refs #N` prose), **or** designate a single primary origin github-issue ref that emit should honor.\n- \u2297 Add related-issue `x-*/github-issue` refs to a brief that still needs `issue:emit` for its primary origin \u2014 emit will SKIP as already tracked.\n\n\u2297 Expand active story scope past xBRIEF AC mid-babysit without follow-up or consented amend (#2881).\n\u2297 Treat confidence-only holds as authorization to invent new subsystems in-tree.\n\n\n### Dual stop \u2014 review fix loops (#2442)\n\nReview fix cycles are multi-iteration work and MUST carry dual stop (`main.md` `## Dual Stop Rule (#2442)`). Single-turn re-checks are exempt.\n\n**Defaults for this skill (override only with an explicit operator envelope):**\n\n| Loop class | Success stop | Default failure stop |\n|------------|--------------|----------------------|\n| Greptile / bot fix batch (Step 3 \u2192 re-review) | No P0/P1 on current HEAD; confidence meets `minGreptileConfidence` | **max 3** fix-batch iterations across the whole review ownership (do **not** reset the counter on push when the same primary fingerprint remains) **or** **2** consecutive re-reviews with the same primary P0/P1 fingerprint and no material fix |\n| Confidence-only hold (0 P0/P1, score below floor) | Confidence meets floor, or operator chooses document/accept path | **max 1** optional polish pass, then stop (do not redesign unbounded \u2014 see confidence-only holds above) |\n\n**On failure stop:**\n\n- ! Halt automatic re-fix. Prefer `BLOCKED:` with PR number, HEAD SHA, blocker class (`review_cycle_cap` / `greptile_p0_p1` / `conf_floor` / `no_progress`), what was tried, and human decision needed (preamble \u00a711 / #2843).\n- ! **Halt-report resume line (MUST, #3273 / AC6):** End the terminal halt with residual class + conf (if any) + PR URL, example phrases (**pursue residual** | **follow-up hard-stop** | **same as conf-hold** | **continue dual-stopped PR**), and skill pointer to \u00a7 Operator follow-up after dual-stop / hard stop (#3273). Same affordance shape as swarm `references/core-phase-4.md`.\n- \u2297 Continue silent fix rounds after the envelope is exhausted.\n- \u2297 Reset the fix-batch counter solely by re-pushing, empty-committing, or swapping workers when the same primary finding fingerprint remains (poll-wait timer MAY reset for a new HEAD; the dual-stop fix-batch counter MUST NOT).\n\n**Enforcement note:** skill defaults are behavioral. Durable delivery/acceptance circuit breaker: **#3143** `packages/core/src/delivery-attempt/` (`evaluatePreDispatch`). Docs: `docs/delivery-attempt.md`.\n\n### Operator follow-up after dual-stop / hard stop (#3273)\n\nOperator-initiated resume after conf-hold, residual dual-stop, or hard-stop exit \u2014 **not** automatic re-thrash. Composes Greptile floor (#3095) and advisory should-not-merge (#3225). Portable consumer + maintainer (`task` / `deft` dual-invoke).\n\n**Triggers:** pursue residual \u00b7 follow-up hard-stop \u00b7 same as conf-hold \u00b7 continue dual-stopped PR \u00b7 re-babysit residual\n\n**One residual pass under operator consent:**\n1. Ground-truth: dual-invoke `pr:merge-ready` / `pr:watch --one-shot` (#2893).\n2. Apply **one** residual fix batch **or** one re-review wait \u2014 not both as an unbounded loop.\n3. If operator authorized a conf floor for **this PR only** (e.g. \u22654/5): post a PR audit comment (floor, HEAD SHA, authorizer). That is the human-merge / documented-override trail \u2014 it does **not** rewrite policy or make `pr:merge-ready` / `pr:watch` CLEAN below `minGreptileConfidence`. \u2297 Silent policy edit for one residual.\n4. Re-evaluate Step 6; merge when **policy** floor + gates met, or human-merge after the documented PR-local floor is met in the bot body; else halt again with a fresh resume line.\n5. Post-merge `scope:complete` when this owner holds lifecycle (#2321 / #3264).\n\n! Dual-stop re-entry: one residual pass then re-stop without new consent. Fresh operator consent required for another pass.\n\n\u2297 Unlimited auto-retry after dual-stop without new operator consent (#3273 / #2442).\n\u2297 Treat conf-only holds as authorization for unbounded redesign (#2881).\n\u2297 Lower project-wide `minGreptileConfidence` for one residual.\n\n### Step 3: Fix all findings in ONE batch commit\n\n! Apply [`coding/review.md`](../../coding/review.md) single-batch, cross-file grep, and local structured-data validation rules. Land **all** in-scope fixes in one commit (or one intentional batch), never per-finding pushes.\n\nGreptile adapter pre-commit gate:\n\n- ! Before committing any Greptile fix, re-read the FULL current Greptile review and confirm all P0/P1 issues are addressed in the staged changes \u2014 this is the pre-commit gate that prevents per-finding fix commits\n- ! Run `task check` before committing\n- ! **Fail-loud completion claim (#1006)**: when reporting fix-batch completion (to the user, in the commit message, in a PR comment, or in a status message to a parent agent), MUST surface the OUTCOMES not the intent -- name the P0/P1 finding count addressed (\"addressed 3/3 P0 findings, 2/2 P1 findings, 0 deferred\" -- NOT \"all findings addressed\"), report the `task check` result with the test-collection counts (\"task check: 412 collected, 412 passed, 0 skipped, 0 xfailed\" -- NOT \"task check passed\"), and explicitly call out any finding intentionally deferred with the reason. Apply `coding/coding.md` `## Fail Loud: Completion Claims Require Outcome Verification (#1006)` to every claim emitted during the review cycle\n- \u2297 Claim \"all Greptile findings addressed\" without verifying that the staged fix actually closes every P0/P1 currently surfaced in the review body -- a fix that addresses 3 out of 4 P1 findings and reports completion is the exact failure mode #1006 forbids\n- \u2297 Claim \"task check passes\" when any test was skipped, xfailed, or run with errors suppressed -- report the full collection counts instead (#1006)\n- ? **Pre-existing failure carve-out**: If `task check` fails due to a pre-existing issue unrelated to the PR's changes, a partial test suite run is acceptable ONLY if BOTH conditions are met: (a) the `task check` failure is pre-existing with an open GitHub issue number tracking it, AND (b) the PR description explicitly notes the failure and includes the issue reference (e.g. \"task check: test_foo fails due to #NNN (pre-existing)\"). Without both conditions, the full `task check` pass remains mandatory.\n- ~ Commit message: `fix: address Greptile review findings (batch)`\n\n### Step 3b: Proactive test coverage scan\n\n! After committing the fix batch but before pushing, scan the changed lines for untested code paths:\n\n1. ! Run `git --no-pager diff HEAD~1 HEAD --name-only` to identify files touched in the fix batch\n2. ! For each changed file that has a corresponding test file, review whether the fix introduced or modified logic that lacks test coverage\n3. ! If untested code paths are found, write tests and amend them into the fix batch commit (or add as a second commit in the same push)\n4. ! Run `task check` again after adding tests to verify they pass\n\n~ This eliminates one CI round-trip per fix cycle \u2014 catching coverage gaps before CI does.\n\n\u2297 Push fix commits without scanning for untested code paths in changed files.\n\n### Step 4: Push and wait\n\n! Push the batch commit, then wait for the bot to review the latest commit.\n\n! After pushing, the agent MUST autonomously poll for review updates and continue the review cycle without stopping to ask the user. Do not pause for confirmation, do not ask \"should I continue?\", do not wait for user input between push and review completion. The review/fix loop is designed to run to the exit condition without human intervention.\n\n! Mid-review push rule: see [`coding/review.md`](../../coding/review.md) (no push while review in progress). Adapter rationale: every push re-triggers Greptile and resets the review clock.\n\n\u2297 Push any additional commits \u2014 including unrelated fixes, doc updates, or lessons \u2014 while waiting for the bot to finish reviewing the current head. If you discover additional work while waiting, stage it locally but do NOT push until the current review completes.\n\n\n\n### Greptile CLEAN vs CI holdout (`pr:watch` / #2688)\n\n! When waiting on a Greptile verdict for a `drive-to: merge-ready` worker (or any review-cycle owner), prefer the dual-invoke probe order below over ad-hoc sleep loops (#1056 / #2893). Parse `clean_gate_holdout` on every probe.\n\n### Gates-surface dual invoke order (#2893 / #2878)\n\nDeep-think gates (`pr:watch`, `pr:merge-ready`, `review-monitor:*`) have **three ordered invoke paths**. Agents MUST probe in this order; bare `task pr:watch` is **not** the sole (or first) consumer form.\n\n! **Probe order (MUST):**\n\n1. **`deft` / `directive` CLI first** \u2014 attempt `deft pr:watch --help` (or `directive pr:watch --help`). Primary for npm/package-manager installs; works without a root Taskfile. CLI forms take flags **without** go-task's bare `--` separator (e.g. `deft pr:watch <N> --json`, `deft verify:review-monitor --pr <N>`).\n2. **`task deft:<verb>` second** \u2014 when a root Taskfile includes `.deft/core/Taskfile.yml` under key `deft:`, go-task exposes **namespaced** tasks (`task deft:pr:watch`, `task deft:verify:review-monitor`, `task deft:review-monitor:register`). Probe `task --list` / `task deft:pr:watch -- --help`. Task forms **require** the bare `--` separator before verb flags (e.g. `task deft:pr:watch -- <N>`, `task deft:verify:review-monitor -- --pr <N>`).\n3. **#2878 gh-only fallback last** \u2014 only when both CLI and namespaced task probes fail, classify **missing-task: pr:watch** (or **missing-task: review-monitor**) and use the official gh-only subset below.\n\n\u2297 Treat bare `task pr:watch` / `task review-monitor:register` as the only prescribed consumer form \u2014 under include key `deft:` those un-namespaced names are absent; that probe failure is not proof the gate is unavailable if `deft` or `task deft:` works (#2893).\n\u2297 Pass go-task's bare `--` separator into `deft`/`directive` CLI forms (e.g. `deft pr:watch -- --help`) \u2014 CLI parsers reject the standalone `--` and the probe fails falsely (#2893).\n\n### Missing gate surface / consumer gh-only fallback (#2878)\n\nSome consumer repos (e.g. sister product deposits) ship Directive skills but have **no working invoke path** for `pr:watch` / `review-monitor:*` (no `deft` CLI on PATH, no Taskfile include \u2192 no `task deft:\u2026`). Agents MUST NOT invent a non-skill poll loop when every probe fails.\n\n! **After dual-invoke probe fails (#2893):** classify the session as **missing-task: pr:watch** (or the specific verb) and fail-loud:\n\n```\nBLOCKED: missing-task pr:watch on this consumer\nRemediation:\n 1. Prefer `deft pr:watch` / install `@deftai/directive` so the CLI surface works, OR\n 2. Add the root Taskfile include (doctor gates-surface snippet) so `task deft:pr:watch` works, OR\n 3. Use the official gh-only fallback subset below (still this skill \u2014 not freestyle).\n```\n\n! **Official gh-only fallback** (when both `deft`/`directive` and `task deft:<verb>` probes fail for pr:watch / review-monitor):\n\n1. Still select Approach 1 when a sub-agent primitive exists (OpenClaw `sessions_spawn`, Cursor `Task`, Claude Code `Agent`, `spawn_subagent`, `start_agent`) \u2014 spawn a review-monitor that runs the gh-only loop; do not block the parent.\n2. **Do not call** gate verbs via any surface the probe showed absent \u2014 those invocations cannot succeed and must not gate the spawn.\n3. Ownership claim without the tasks: post/update the sticky `<!-- deft:review-owner -->` PR comment via `gh api` (same field shape as the task-written lease) **or** keep ownership in the parent and document `missing-task: review-monitor` in the PR/parent handback. Never invent `.deft/review-monitor.json`.\n4. Poll with adaptive cadence (20-30s / 60s / 90s) using:\n - `gh pr view <N> --comments` (dual-source + Step 1 rules still apply)\n - `gh pr checks <N>`\n - `gh api repos/<owner>/<repo>/pulls/<N> -q .head.sha` for HEAD pin\n - `gh api repos/<owner>/<repo>/commits/<sha>/check-runs` for Greptile terminal check-run\n5. Evaluate the same Step 6 fail-closed all-of (terminal check-run + HEAD SHA + Last reviewed commit + confidence meets resolved min (policy/dogfood/default; see Step 6 #3095) + no P0/P1).\n6. Surface missing-task once to the operator/parent on first detection; do not silently rebrand freestyle sleep as `pr:watch`.\n\n\u2297 Fake a successful `pr:watch` or `review-monitor:*` gate when every dual-invoke probe failed.\n\u2297 Block Approach 1 / parent yield on missing `review-monitor:*` after the dual-invoke probe \u2014 use the gh lease claim or parent-owned gh-only poll instead (#2878).\n\u2297 Invent ad-hoc `sleep` / main-session poll / OpenClaw cron loops outside Approach 1\u20133 when the skill already names this fallback (#2878 / statusreport#153 recurrence).\n\u2297 Skip Step 6 fail-closed fields because deterministic tasks are missing \u2014 the gh surfaces above remain mandatory.\n\n! When `clean_gate_holdout=ci_failures` and Greptile otherwise satisfies the probe-side Step 6 fields (SHA match on HEAD, confidence meets resolved min (policy/dogfood/default; see Step 6 #3095), no P0/P1, not errored): **MUST NOT** idle-poll hoping CI heals. Treat Greptile CLEAN + CI red with the **same ownership** as a Greptile P0 for a merge-ready worker \u2014 one fix batch, re-push, re-probe.\n\n! On persistent `ci_failures` holdout: exit the Greptile wait immediately, fetch failing check annotations (`gh pr checks <N>`, CodeQL / required-check details, or `ci_failed_checks` from `pr:watch --json`), fix or escalate with evidence, then re-enter the review loop after CI is green.\n\n! PR body \"Test plan\" checkboxes being `[x]` do **not** authorize idle wait \u2014 merge-ready is `pr:watch` CLEAN / the merge path only.\n\n\u2297 Treat `pr:watch` TIMEOUT or long PENDING with `clean_gate_holdout=ci_failures` as \"Greptile still reviewing\" \u2014 it means **CI blocked the clean gate**.\n\n~ Surface the holdout to the user/parent on the first stable `ci_failures` probe (fail-loud), not after burning `max-wait-minutes`. See also [`templates/swarm-greptile-poller-prompt.md`](../../templates/swarm-greptile-poller-prompt.md) CLEAN gate evaluation (#1039).\n\n\n### Runner capacity stall (`runner_capacity_stall` / #2672)\n\n! Framework CI prefers Blacksmith with a timed GH-hosted failover (~20 minute stall budget). When `task pr:watch --json` / `task pr:merge-ready` reports `ci_ready_state=runner_capacity_stall` (or verdict `RUNNER_CAPACITY_STALL`, exit 2): **wait for auto-failover** to the ubuntu-latest lane and the authoritative aggregator check. Do **not** invent `--skip-ci` or merge with pending required checks.\n\n! `runner_capacity_stall` is distinct from ordinary `not_ready_yet` (under budget / `in_progress`) and from execution hangs (#2652). Capacity stall means required checks stayed `queued` with no runner claimed past the budget.\n\n\u2297 Use `--skip-ci` / merge-with-pending because CI is capacity-stalled \u2014 the failover path is the unblock; skip-ci is an incident-only release escape hatch (#2652), not a runner-capacity remedy.\n\n### CI weather reason codes + thrash caps (#3167)\n\n`pr:watch` / `pr:merge-ready` expose machine-distinguishable `ci_ready_state` values (also `--json`) so agents stop conflating Actions weather with product test failure:\n\n| `ci_ready_state` / verdict | Meaning | Agent action |\n|----------------------------|---------|--------------|\n| `ci_never_scheduled` / `CI_NEVER_SCHEDULED` | No CI workflow check-run for HEAD (empty or bots-only: Greptile/SLizard) | Cap re-triggers; then **BLOCKED** \u2014 do not multi-hour empty-commit thrash |\n| `runner_capacity_stall` / `RUNNER_CAPACITY_STALL` | Required still `queued`, no runner past budget (#2672) | Wait auto-failover; \u2297 `--skip-ci` |\n| `ci_failures` / `CI_BLOCKED` | Completed `failure` / `timed_out` with product evidence (#2688) | Own like Greptile P0 \u2014 fix or escalate |\n| `ci_cancelled_no_failover` / `CI_CANCELLED_NO_FAILOVER` | Primary `cancelled` and no green required sibling (failover skipped/not armed; workflow sibling **#3168**) | Cap re-triggers; then **BLOCKED** |\n| Greptile CLEAN fields / `greptile_pending` | Existing Step 6 / SHA / confidence | Unchanged |\n\n! **Thrash caps (MUST):** Under stable `ci_never_scheduled`, `ci_cancelled_no_failover`, or repeated capacity stall after failover wait budget, limit **CI re-trigger attempts** (empty-commit push, close/reopen, rebase-for-enqueue) to **at most 2** total across the ownership span. On the **2nd** failed re-trigger (or immediately when the weather code is stable and Greptile Step 6 is already clean), stop automatic re-push and emit a structured **BLOCKED** handoff.\n\n### Platform status probe + outage attribution (#3180)\n\n! When `ci_ready_state` is weather-class (`ci_never_scheduled`, `runner_capacity_stall`, `ci_cancelled_no_failover`, `ci_failures`), CI never starts for HEAD, or many PRs share an empty-check pattern: **MUST probe public status pages** before workflow thrash or drive-by edits. Gates surface static URLs in `pr:watch` / `pr:merge-ready` JSON and human output (v1: no network fetch required).\n\n1. ! **GitHub Status** (Actions, Webhooks): https://www.githubstatus.com/\n2. ! **Blacksmith Status**: https://status.blacksmith.sh/\n\n**Attribution table:**\n\n| Observation | `attribution` | Agent action |\n|-------------|---------------|--------------|\n| GH Actions and/or Webhooks major/partial outage | `platform` | Platform incident; \u2297 workflow drive-by edits; \u2297 empty-commit thrash past thrash caps; wait + re-check HEAD runs + local `task check` |\n| Blacksmith red while GH Actions green | `capacity` | Runner-provider incident; failover doctrine (#2672 / #3168) |\n| Both green + still `ci_never_scheduled` on this PR only | `repo_config` | Workflow paths, branch filters, required-check names, Actions disabled / org policy |\n| Unclear / mixed | `unknown` | Cap thrash; BLOCKED with both status URLs; operator decision |\n\n! **Anti-thrash during attributed platform outage:** After thrash caps, stop automatic re-push loops. Remediation is wait + re-probe HEAD check-runs, not inventing workflow edits for a global outage.\n\n\u2297 Merge or `--skip-ci` solely because a status page is red \u2014 status is attribution for wait/thrash policy, not a second branch-protection oracle.\n\u2297 Blame Blacksmith when GH Actions/Webhooks are the red components and Blacksmith runners are operational.\n\u2297 Edit workflows / empty-commit thrash to \"fix\" a documented global Actions/webhook outage without a status-page probe.\n\nCross-links: #3167 (weather codes), #3168 (failover arms), #2672 (capacity stall), #2688 (Greptile CLEAN + CI holdout).\n\n! **BLOCKED handoff template (CI weather):**\n\n```text\nBLOCKED: ci_weather\nPR: <N>\nHEAD: <sha>\nREASON: ci_never_scheduled|ci_cancelled_no_failover|runner_capacity_stall\nGREPTILE: CLEAN|P0/P1|pending (Step 6 fields)\nCI: <ci_ready_state from pr:watch --json>\nplatform_status_github: https://www.githubstatus.com/\nplatform_status_blacksmith: https://status.blacksmith.sh/\nincident_url: <optional status-page incident URL or n/a>\nattribution: platform|capacity|repo_config|unknown\nATTEMPTS: empty-commit=<0-2> close-reopen=<0-2>\nREMEDIATION: wait for platform recovery | capacity failover (#3168) | repo config fix | human admin-merge playbook below | operator decision\nREDISPATCH_OK: yes|no\n```\n\n! Ownership of Greptile CLEAN + CI holdout is still real (#2688) \u2014 **ownership \u2260 infinite wait**. After thrash caps, hand off; do not burn multi-hour `gh run watch` / empty-commit loops when Greptile is already CLEAN.\n\n! **Envelope selection under CI weather (#3153):** Prefer deliberate `stop-at: pr-open` implement + this skill as the partner merge-path babysit when known capacity/outage weather dominates; see swarm Envelope selection SLA and partner merge-path section above. Cross-link only \u2014 do not re-spec the tree here.\n\n\u2297 Multi-hour empty-commit / close-reopen / rebase thrash after thrash caps when `ci_ready_state` is `ci_never_scheduled` or `ci_cancelled_no_failover`.\n\u2297 Treat `ci_never_scheduled` as ordinary Greptile latency (`sha_match` / `terminal_check_run` only).\n\u2297 Silent `--skip-ci` / admin merge without the outage playbook audit trail below.\n\n### SLizard advisory-only for merge-ready wait (#3167)\n\n! Required bot for **merge-ready wait** / Step 6 exit ownership is **Greptile**. SLizard (Gemini Verify) is **advisory only**: timeouts, retries, missing check, or flaky SLizard conclusions MUST NOT gate the review-cycle wait loop or authorize unbounded re-push.\n\n! `task pr:merge-ready` may still surface SLizard structure when present (#2189); agents MUST NOT idle-poll or thrash solely for SLizard when Greptile Step 6 is clean. Prefer continue / BLOCKED on CI weather / human decision.\n\n\u2297 Block merge-ready babysit on SLizard alone when Greptile Step 6 all-of is satisfied on HEAD.\n\n### Outage admin-merge playbook (opt-in / human, #3167)\n\nWhen GitHub Actions is in a **documented major outage** (or multi-hour `ci_never_scheduled` / `ci_cancelled_no_failover` after thrash caps) and product + Greptile are ready:\n\n! Admin / human merge is **opt-in**, never the autonomous agent default. Preconditions:\n\n1. ! Greptile Step 6 fail-closed all-of on current HEAD (dogfood conf floor / `minGreptileConfidence`).\n2. ! Evidence of local or prior green `task check` / merge-gate when available.\n3. ! PR comment **audit note** naming the weather code, HEAD SHA, and who authorized override.\n4. ? Optional explicit env/policy for bot merge (`DEFT_ALLOW_BOT_MERGE` / `task policy:allow-bot-merge`) \u2014 **opt-in**, never silent default skip-ci.\n\n\u2297 Autonomous `--skip-ci` / `--admin` merge as the default under ordinary CI weather.\n\u2297 Replace branch protection with Greptile-only merge on normal days.\n\nWorkflow failover arming (Blacksmith cancelled \u2192 GH-hosted lane) is sibling issue **#3168** \u2014 this skill owns agent thrash caps and reason codes only.\n\n### Stall Detection Rubric (#564)\n\n! Track per poll: `startedAt` (timestamp of the first observation of the IN_PROGRESS check run for the current commit) and `commit.oid` (head SHA being reviewed). Both fields MUST be re-recorded every time the head SHA changes -- the rubric measures elapsed time on a single commit, not across the whole review cycle.\n\n! Expected duration baseline -- Greptile reviews typically complete in 2-5 minutes, with 7 minutes as the upper bound of normal. The escalation threshold is **3x expected = ~10 minutes** of continuous IN_PROGRESS on the same `commit.oid`. The 21-minute stall observed during the rc4 swarm cascade on PR #561 is the recurrence record; see [`../../meta/lessons.md`](../../../meta/lessons.md) `## Greptile Review Stall Detection (2026-04)`.\n\n! When elapsed time on the current `commit.oid` exceeds 10 minutes (3x expected) without the IN_PROGRESS check transitioning to a terminal state, the agent MUST escalate to the user. The escalation message MUST include: (1) the PR number; (2) the head SHA being reviewed; (3) the elapsed time since `startedAt`; (4) the four canonical user-decision options.\n\n! User-decision options at escalation -- render as a deterministic numbered menu per [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md) (final two options `Discuss` + `Back`):\n\n 1. Wait another N minutes (user picks N).\n 2. Manually re-trigger Greptile by commenting `@greptileai` on the PR (logs the override in a PR comment for auditability per the next rule).\n 3. Skip the bot review for this cycle and exit the loop with a documented reason.\n 4. Cancel the review cycle entirely.\n 5. Discuss.\n 6. Back.\n\n! Auto-restart detection -- when the polling loop observes a NEW `startedAt` (Greptile dropped its prior check run and started a fresh one without any push from the agent, e.g. service-side restart), the agent MUST reset its elapsed-time clock to the new `startedAt` AND notify the user that an auto-restart was detected. Resetting the clock without notifying is forbidden -- the user needs to know the cycle effectively re-started.\n\n! **`INCOMPLETE_BUT_RATED` stall signature (#1259):** when a poll observes a parsed `Confidence Score: X/5` number BUT no terminal check-run (no `completed` status with a `{success, neutral}` conclusion) AND/OR no HEAD-matching `Last reviewed commit:` completion marker, classify the state as **`INCOMPLETE_BUT_RATED`** \u2014 Greptile has emitted a confidence rating against a review that has NOT terminally landed on the current HEAD. This is NOT an exit condition (the Step 6 fail-closed all-of resolves the missing fields to `unknown`); treat it as a stall signature and keep polling, escalating per the 10-minute threshold above if it persists. A confidence number is the single most common false-positive for a premature exit \u2014 `INCOMPLETE_BUT_RATED` names the trap so the agent does not mistake a rating for a verdict.\n\n\u2297 Auto-retrigger Greptile (empty commits, force-pushes, agent-posted `@greptileai` comments, status-check rebuilds) without explicit user approval. The escalation menu's option 2 is the ONLY supported re-trigger path, and even that requires the user to pick it.\n\n! Document any user-approved override in a brief PR comment for auditability -- e.g. `Note: review-cycle stall detected at <SHA> after <N> min; user approved manual re-trigger via @greptileai per skills/deft-directive-review-cycle Stall Detection Rubric (#564).` This makes the override visible to humans reviewing the PR history and to future agents that resume the cycle.\n\n\u2297 Treat a stall as silent -- if the elapsed clock crosses the 10-minute threshold the agent MUST surface the menu, even if the agent is mid-poll. Continuing to poll past the threshold without user input is forbidden.\n\n### Owner Continuity Gate (#3090)\n\n! After any claim of `drive-to: merge-ready`, babysit, shepherd, or \"driving review-cycle / merge\" on an **open PR**, the **same turn** MUST end in exactly one of:\n\n- **A.** Approach 1 monitor live + sticky `<!-- deft:review-owner -->` lease registered (or #2878 gh-only lease equivalent). Parent yields with an **active** child / monitor and emits `review_cycle: in_progress:<pr>#<monitor_or_lease_ref>`.\n- **B.** Parent-retained ownership: parent does **not** mark the work complete; the next concrete action is an explicit dual-source poll/fix (Step 1 + Step 6). Emit `review_cycle: in_progress:<pr>#parent-retained` (or lease id when a sticky lease exists).\n- **C.** Explicit finish to caller/principal: `BLOCKED` / needs decision / `FAILED` with PR URL + HEAD SHA + why. Emit `review_cycle: skipped:<reason>` or keep `in_progress` only when a live owner remains; never freeform `started`.\n\n! **`review_cycle` evidence enum (portable \u2014 all consumers / handoffs / preamble \u00a711 / swarm finish messages):** **only**\n - `done` \u2014 Step 6 fail-closed all-of met on current HEAD (terminal check + HEAD pin + confidence bar + **0 P0/P1** via **dual-source**)\n - `in_progress:<pr>#<monitor_or_lease_ref>` \u2014 verifiable sticky lease, registered monitor id, or documented `parent-retained` ownership\n - `skipped:<reason>` \u2014 intentional skip (e.g. no-pr, operator cancel)\n - `n/a` \u2014 work never entered review-cycle\n\n! Layer **L4** `status: pass` (or equivalent process-green handoff) is **illegal** unless `review_cycle: done` **or** `review_cycle: in_progress:\u2026` with **verifiable** sticky lease / parent-retained ownership documented on that turn.\n\n! Opening a PR may use `in_progress` + lease; the **merge path** requires `done` (stricter product merge bars remain out of scope).\n\n! When dual-source fetch shows open P0/P1 under Step 6 / CLEAN evaluation: continue the fix loop **or** exit **BLOCKED** to the parent \u2014 never idle.\n\n! Optional machine gate: `deft verify:l4-owner --pr <N>` (or `task verify:l4-owner -- --pr <N>`; dual-invoke same order as other gates). Exit **0** only when a sticky lease is fresh on the PR **or** the caller asserts `--review-cycle done` after Step 6 (lease-or-done machine gate). `skipped` / `n/a` / parent-retained are process evidence only and do **not** satisfy this machine gate. Exit **1** on silent hold (no lease, no done). Pair with existing monitor-without-lease regression (#2797).\n\n\u2297 End an owning turn with **0 children**, **no sticky lease**, and **no finish signal** after a drive-to-merge / babysit / shepherd claim (**silent hold**).\n\u2297 Treat check-run **SUCCESS alone** as CLEAN or merge-ready while dual-source P0/P1 remain open.\n\u2297 Emit freeform `review_cycle: started` / `pending` / `initiated` or L4 `status: pass` without **A** (or parent-retained **B** with explicit next action) or full Step 6 `done`.\n\u2297 Solve Owner Continuity via host cron-as-Approach-1 or always-block-parent-until-merge \u2014 use A/B/C above (#2876 / #3090).\n\n~ **Eval / regression (#3090):** Given PR open + check SUCCESS + open inline P1s + agent text claims driving merge + turn ends with 0 subagents and no lease \u2192 **FAIL** (Owner Continuity Gate), not PASS.\n\n### Review Monitoring\n! **Background / independent dispatch (#1880 Gap D):** Long-running review-cycle owners and pollers (>~3 min) MUST be dispatched independently / in the background so the parent conversation stays interactive. On Cursor, use the Task tool background path (`run_in_background: true`) when the current agent is the top-level owner of that primitive (not a nested leaf \u2014 see Cursor leaf boundary). On Claude Code, top-level parents/orchestrators use the `Agent` tool with `run_in_background: true` (register primitive `claude-agent`, #3134); implementation leaves follow the Claude Code leaf boundary (blocking `pr:watch` or `stop-at: pr-open` sibling), not nested Agent. This generalizes the Approach-1 sub-agent monitor rule to implementation and fix workers as well \u2014 foreground dispatch is reserved for short tasks. The parent receives completion via `DONE` / `BLOCKED` / `FAILED` per `templates/agent-prompt-preamble.md` \u00a711.\n\n! **Worker-owns-lifecycle (#1880 Gap C):** When this skill runs as part of an implementation worker scoped `drive-to: merge-ready`, the worker owns the full review/fix loop through merge-ready in its own tool loop \u2014 do NOT exit at PR-open expecting the orchestrator to spawn a separate review leaf.\n\n! **Swarm monitor must not self-implement (#2843 / Gap C):** When a cohort monitor receives `BLOCKED` or DONE-with-blockers from a `drive-to: merge-ready` implementation leaf, the monitor MUST NOT enter the review/fix loop inline on Tier 1 \u2014 background-dispatch ONE continuation leaf scoped `drive-to: merge-ready` on the same worktree. Monitor-inline review-cycle is permitted only on Tier 3 or with explicit operator consent (see `skills/deft-directive-swarm/SKILL.md` Phase 5 completion-notification decision tree).\n\n### Partner merge-path when implement stops at PR-open (#3153)\n\n! This skill is the **required partner** for the swarm **Envelope selection SLA** (`skills/deft-directive-swarm/references/core-phase-0.md` / Phase 3). When an implement leaf was deliberately scoped **`stop-at: pr-open`** (or a merge-ready leaf failed thin DONE and recovery chose babysit ownership), the parent/monitor MUST **not** leave the open PR without a merge-path owner.\n\n! **First-class merge-path ownership (MUST, same turn as PR ground-truth):**\n\n1. ! Spawn **or** retain **exactly one** review-cycle owner for the open PR:\n - **Approach 1** review-monitor (`worker_role: review-monitor`) with sticky `<!-- deft:review-owner -->` lease (#3090 / #3044 / dual-invoke `review-monitor:register` when available), **or**\n - A continuation leaf scoped **`drive-to: merge-ready`** on that PR/worktree that owns babysit \u2192 merge-ready in its tool loop, **or**\n - Documented **parent-retained** ownership (`review_cycle: in_progress:<pr>#parent-retained`) with an explicit next poll/fix action \u2014 never silent hold.\n2. ! Route through **this skill** \u2014 \u2297 Cursor global babysit (`#2261`), freestyle main-session poll, or dual parallel monitors (`#3044`).\n3. ! Apply Owner Continuity Gate (#3090) and Single review-monitor lease (#3044) without exception: one sticky lease; force-takeover only when the prior owner is dead.\n4. ! **Post-merge `scope:complete` (#2321 / Gap C):** When the implement leaf stopped at pr-open, it MUST NOT have run `task scope:complete`. After the PR **merges**, the merge-path owner (or swarm Phase 6 `task swarm:finalize-cohort` / `task swarm:complete-cohort` / monitor) MUST run `task scope:complete` or `task scope:cancel`. `task verify:orphan-active` fails closed on stranded active briefs.\n5. ! **Human-merge / CLEAN-before-merge ownership (#3153 / #1193 / #2321):** When `plan.policy.requireHumanMerge` (or missing bot-merge authority) means the review owner reaches Greptile CLEAN / merge-ready but **cannot** squash-merge, lifecycle ownership is **not** complete. Prefer **durable** ownership (not a prose-only promise):\n - **Preferred:** Parent/monitor **retains** ownership (`review_cycle: in_progress:<pr>#parent-retained` or sticky lease held by the long-lived monitor) until human merge lands, then runs `scope:complete` (or Phase 6 `task swarm:finalize-cohort` / `task swarm:complete-cohort`).\n - **Allowed handoff:** Only to a **long-lived** parent/monitor / Phase 6 closer \u2014 same turn: (1) re-claim sticky `<!-- deft:review-owner -->` lease for the **recipient** (register/force as needed), (2) structured handback with PR, HEAD, `awaiting-human-merge`, and explicit post-merge `scope:complete` duty, (3) recipient acknowledges with `review_cycle: in_progress:<pr>#\u2026` before the giving agent exits.\n - ! Cohort through-merge: the **swarm monitor** is the default durable post-merge `scope:complete` owner for every `stop-at: pr-open` story (#2321) \u2014 do not rely on a review leaf that exits at CLEAN.\n - ! **Post-CLEAN wake path (MUST):** After CLEAN under human-merge, the durable owner MUST keep a **reachable observe path** until the PR is `MERGED` (or closed without merge \u2192 `scope:cancel` / operator decision). Concrete options (pick one, same ownership):\n 1. **Background poller** (Approach 1 preferred when Tier 1): spawn/retain a review-monitor or short poll loop that probes `gh api repos/<owner>/<repo>/pulls/<N>` for `merged` / `state` on adaptive cadence (or host merge webhook when available), then runs post-merge verification + `scope:complete`.\n 2. **Parent-retained yield-with-wake:** parent keeps `review_cycle: in_progress:<pr>#parent-retained` and re-enters on the next operator message / scheduled re-invocation (Approach 2) with an explicit first action of \"check merge state \u2192 if merged, `scope:complete`\".\n 3. **Phase 6 cohort closer:** for swarm, record the PR as `awaiting-human-merge` in the monitor checkpoint and **require** the Phase 6 pre-sweep merge re-poll (`skills/deft-directive-swarm/references/core-phase-5-6.md` \u00a7 Human-merge observe path / Step 1.5) before `task swarm:complete-cohort` / finalize \u2014 never skip `scope:complete` solely because Greptile was CLEAN earlier.\n \u2297 Keep only a sticky lease with no poller, no parent re-entry plan, and no Phase 6 re-poll checklist \u2014 that is ownership-in-name-only and still strands `scope:complete`.\n \u2297 Handoff to a short-lived leaf that exits at CLEAN without lease transfer.\n \u2297 Emit terminal `DONE` / stand down at CLEAN when merge authority is human-only and no **reachable** durable owner (sticky lease + live parent/monitor/cohort closer **with an observe path above**) remains for post-merge `scope:complete`.\n6. ! **Thin DONE recovery (#2943 / #3153):** A failed `drive-to: merge-ready` leaf that only opened a PR is **not** success. After ground truth, hand merge path to **one** of the owners above \u2014 never improvise a second lease or re-dispatch implement + babysit in parallel without releasing the first.\n\n! **Cohort through-merge intent is unchanged:** stories still land on master. Envelope selection only assigns **who owns implement vs who owns Greptile/CI/merge** under capacity stall, conf floors, wall-clock budgets, or large multi-gate stories. Happy-path single `drive-to: merge-ready` leaves remain the default and do not use this partner handoff.\n\n! **Does not authorize:** lowering `minGreptileConfidence`, `--skip-ci` for capacity stalls, or unbounded redesign on conf-only holds (#2881 / #2672 / #3095).\n\nCross-links: swarm decision tree `skills/deft-directive-swarm/references/core-phase-0.md` \u00a7 Envelope selection SLA; Phase 3 Gap C `skills/deft-directive-swarm/references/core-phase-3.md`; thin SKILL pointer `skills/deft-directive-swarm/SKILL.md` \u00a7 Envelope selection SLA.\n\n\n\n! Select the monitoring approach based on runtime capability detection (the matrix in `skills/deft-directive-swarm/SKILL.md` Phase 3 Step 1, extended per #1342 slices 1-2 for `spawn_subagent` / \"grok-build\", per #1877 for Cursor as first-class Tier-1 tiers, per #2876 for OpenClaw `sessions_spawn`, and per #3134 for Claude Code `claude-code` / `claude-agent`). Probe the environment (tool set + env vars) to obtain the stable platform descriptor (`grok-build`, `warp-orchestrated`, `warp-manual`, `cursor-composer`, `cursor-cloud-agent`, `claude-code`, `openclaw`, etc.) from the launch adapter / `get_platform_capabilities` and map the descriptor to the appropriate tier + dispatch primitive (`start_agent`, `spawn_subagent`, the Cursor `Task` tool, Claude Code `Agent` / `claude-agent`, or OpenClaw `sessions_spawn`). The descriptor (not hard-coded tool presence) is the single source of truth for both launch and review monitoring.\n\n- **Tier 1 (orchestrated sub-agent)** \u2192 Approach 1 (spawn review-monitor sub-agent via the primitive matching the descriptor: `start_agent`, `spawn_subagent`, the Cursor `Task` tool with `run_in_background: true`, Claude Code `Agent` with `run_in_background: true` / register `claude-agent`, or OpenClaw `sessions_spawn`)\n- **Tier 2 (no sub-agent primitive, but scheduler/timer/auto-reinvocation)** \u2192 Approach 2 (yield-between-polls) \u2014 includes OpenClaw `cron` / host scheduler **only when** `sessions_spawn` is unavailable (#2876)\n- **Tier 3 (interactive session, nothing else)** \u2192 Approach 3 (blocking sleep loop as last resort)\n\n! Detection: use the full runtime capability matrix (swarm Phase 3 + launch adapter from #1342 slice 2). The old single-probe for `start_agent` is superseded; the returned platform descriptor determines both the orchestration path and the MCP surface (see MCP probe below). If the descriptor is `grok-build` (spawn_subagent present, start_agent + WARP_* absent), treat as Tier 1 with the spawn_subagent poller path. If the descriptor is `cursor-composer` / `cursor-cloud-agent` (Cursor `Task` tool present, start_agent + WARP_* + spawn_subagent absent), treat as **Tier 1 with the backgrounded Cursor `Task` poller path** (#1877) \u2014 NOT Tier 3. Cursor's `Task` tool is a first-class sub-agent primitive; degrading a Cursor session to the Approach-3 blocking poll is the misclassification #1877 closes. If the descriptor is `claude-code` (Claude-unique `Agent` / `CLAUDECODE` / `DEFT_PROBE_CLAUDE_CODE` signals), treat as **Tier 1 with the backgrounded Claude Code `Agent` poller path** (#3134) \u2014 NOT Tier 3 and NOT `cursor-composer` (bare `Task` is not a Claude-unique signal). If the descriptor is `openclaw` (`sessions_spawn` present), treat as **Tier 1 with the backgrounded `sessions_spawn` poller path** (#2876) \u2014 NOT Approach 2 cron and NOT main-session gh poll.\n\n! Swarm agents (whether launched via `start_agent`, `spawn_subagent`, or OpenClaw `sessions_spawn` per the platform descriptor) SHOULD prefer Approach 1 for their own review-monitor sub-agent. Approach 2's yield-between-polls is not self-sustaining for swarm agents (see warning below). Always include the canonical `templates/agent-prompt-preamble.md` (AGENTS.md read mandate, #810 xBRIEF gate, #798 PowerShell UTF-8, pre-PR + review-cycle mandates) when spawning a poller sub-agent.\n\n! **Deterministic review-monitor gate (#2655 / #2814 / #2876 / #2893):** When Tier 1 is available **and** a dual-invoke probe succeeds for review-monitor verbs (`deft verify:review-monitor` / `deft review-monitor:register`, or `task deft:verify:review-monitor` / `task deft:review-monitor:register`), run that verify form before yielding, entering Approach 3, or claiming review monitoring started \u2014 CLI: `deft verify:review-monitor --pr <N> [--call-site solo]`; task: `task deft:verify:review-monitor -- --pr <N> [--call-site solo]`. After spawning Approach 1, claim the PR-anchored lease with the matching register form (CLI: `deft review-monitor:register --pr <N> --monitor-agent-id <id> --platform-primitive ...`; task: `task deft:review-monitor:register -- --pr <N> --monitor-agent-id <id> --platform-primitive start_agent|spawn_subagent|cursor-task|claude-agent|sessions_spawn|openclaw-sessions-spawn`). Release with the matching release form (CLI: `deft review-monitor:release --pr <N>`; task: `task deft:review-monitor:release -- --pr <N>`) when done. Exit `0` ready / `1` not ready or held-by-other / `2` config. The sole source of truth is the sticky GitHub PR comment (`<!-- deft:review-owner -->`); legacy `.deft/review-monitor.json` is obsolete and ignored. On register conflict, attach to the existing owner or stop \u2014 do not parallel-fix.\n\n! **Missing review-monitor surface carve-out (#2878 / #2893):** When dual-invoke probes fail for `pr:watch` **and** `review-monitor:*` (no `deft` CLI, no `task deft:` include), do **not** invoke those gates and do **not** block Approach 1 on them. Fail-loud once with `missing-task: review-monitor` / `missing-task: pr:watch`, then:\n1. Still spawn Approach 1 with the official gh-only fallback when a sub-agent primitive exists.\n2. Post (or update) the sticky lease comment via raw `gh api` using the same `<!-- deft:review-owner -->` field shape the tasks would write \u2014 parent may yield after that claim succeeds \u2014 **or**, if the agent cannot write issue comments, keep ownership in the parent with the gh-only poll and document that lease tasks were unavailable.\n3. Never invent a local `.deft/review-monitor.json` as a substitute gate.\n\u2297 Require successful review-monitor register/verify on a consumer where dual-invoke probes failed \u2014 that is the conf=3 / #2878 inconsistency Greptile flagged.\n\n! **Regression trigger (#2797 / #2878):** A leaf that claims a monitor is active without a preceding successful **GitHub sticky lease claim** MUST fail the review-monitor checklist/eval; a backgrounded `pr:watch` shell is insufficient. When a dual-invoke probe finds `review-monitor:register`, that form is the required claim path. When the missing-task carve-out applies (#2878), a raw `gh api` post/update of the same `<!-- deft:review-owner -->` sticky comment satisfies the claim (or the parent keeps ownership and does not claim a separate monitor). The regression fails only on a claim with **no** sticky lease evidence \u2014 not on consumers that legitimately lack the gate surface.\n\n\n\n! **CI-holdout carve-out (#2688):** When `task pr:watch --one-shot --json` reports `clean_gate_holdout=ci_failures` with Greptile fields otherwise satisfied on current HEAD, do **not** freeze on `verify:review-monitor` / spawn-monitor as if Greptile latency were the blocker. Fix CI first (same ownership as Greptile P0). Keep or register a review-monitor only while still waiting on Greptile latency; a `BLOCKED: ci_failures` DONE handback to the implementation owner is correct.\n\n\n! **Cursor leaf boundary (#2797 / #2893):** A Cursor `Task` leaf cannot reliably spawn another Cursor `Task`; nested Task (leaf spawning leaf) is unsupported for an Approach 1 review-monitor. A Cursor `drive-to: merge-ready` leaf MUST either keep ownership in the same agent by blocking on `deft pr:watch <N>` (or `task deft:pr:watch -- <N>` when include-present), or its envelope MUST instead be `stop-at: pr-open` so the orchestrator can spawn and register a sibling review-monitor. A background shell `pr:watch` is not a monitor and MUST NOT be claimed as one.\n\n! **Claude Code leaf boundary (#3134 / #2797 analogue):** Nested `Agent` (implementation leaf spawning a second-level review-monitor Agent) is unsupported/unreliable on some Claude Code surfaces. A Claude Code `drive-to: merge-ready` leaf MUST either keep ownership in the same agent by blocking on `deft pr:watch <N>` (or `task deft:pr:watch -- <N>` when include-present), or its envelope MUST instead be `stop-at: pr-open` so the orchestrator can spawn and register a sibling review-monitor with `--platform-primitive claude-agent`. \u2297 Background a nested Agent poller from an implementation leaf and exit claiming monitoring is active. Top-level parents/orchestrators that own the `Agent` primitive MAY still Approach-1 background a review-monitor Agent.\n\n**Approach 1 (preferred -- sub-agent orchestration available per platform descriptor):**\n\n! **Background dispatch (#1880 / #2876 / #3134):** Spawn the review-monitor sub-agent via the matching primitive IN THE BACKGROUND (Cursor: Task `run_in_background: true`; Claude Code: `Agent` `run_in_background: true`; Grok Build: `spawn_subagent` with parent yielding; OpenClaw: `sessions_spawn` with parent yielding). The parent MUST remain interactive while the poller runs \u2014 never block the parent OpenClaw/Cursor/Claude Code/Grok session for >~3 min of monitor ownership.\n\n! **Heartbeat contract for Cursor pollers (#1877 / #1166 / #2876 / #3134):** Claude Code `Agent` and OpenClaw `sessions_spawn` pollers share this contract. A Cursor `Task`, Claude Code `Agent`, or OpenClaw `sessions_spawn` review-monitor poller whose loop runs > ~3 min MUST honour the sub-agent heartbeat contract (`docs/subagent-heartbeat.md`), same as the `spawn_subagent` path \u2014 emit periodic progress so the parent can distinguish a live poller from a hung one.\n\n~ **Visible Control UI (OpenClaw / #3044):** When OpenClaw Control UI is the operator control plane, SHOULD spawn the review-monitor with `visible:true` when the tool surface allows so humans can inspect progress without attaching to the parent session; invisible empty settles are higher FC04 residual risk.\n\n! When the platform descriptor indicates Tier 1 (sub-agent support), spawn a review-monitor sub-agent using the primitive matching the descriptor:\n\n1. ! Launch via the matching primitive: `start_agent` (Warp), `spawn_subagent` (grok-build / TUI / non-Warp), the Cursor `Task` tool with `run_in_background: true` (`cursor-composer` / `cursor-cloud-agent`, #1877), the Claude Code `Agent` tool with `run_in_background: true` (`claude-code` / register `claude-agent`, #3134), **or OpenClaw `sessions_spawn` (`openclaw`, #2876)** with a prompt that instructs it to poll for Greptile completion. For `spawn_subagent`, Cursor `Task`, Claude Code `Agent`, and OpenClaw `sessions_spawn` the prompt MUST reference the canonical poller template `templates/swarm-greptile-poller-prompt.md` (with placeholders filled) plus the agent preamble; the working directory / context must be the PR branch (worktree or equivalent for hybrid).\n2. ! The sub-agent polls using the mechanism for its primitive: for `spawn_subagent` use `get_command_or_subagent_output` (adaptive cadence: ~20-30s first check after push, ~60s second, ~90s thereafter; Greptile typically lands in 3-7 min); for `start_agent` the native messaging path; for the Cursor `Task` tool the backgrounded-task completion-notification path; for Claude Code `Agent` the backgrounded-agent completion-notification path; for OpenClaw `sessions_spawn` the host session completion / messaging channel (prefer `task pr:watch` inside the child when available). Front-load the first check to catch fast reviews.\n3. ! When the exit condition is met (Greptile review current on the HEAD commit SHA, confidence meets resolved min (policy/dogfood/default; see Step 6 #3095), no P0/P1 remaining), the sub-agent reports completion back to the parent (via `send_message_to_agent`, the spawn_subagent result channel, or the OpenClaw sessions completion channel).\n4. ! The main conversation pane stays fully interactive during monitoring -- the user (or parent monitor) can continue other work.\n5. ! On receiving the completion message / result, the parent re-fetches findings (both gh pr view --comments and the secondary source) and proceeds to Step 5.\n\n\u2297 Use OpenClaw `cron` alone as Approach 1 when `sessions_spawn` is available \u2014 cron is Approach 2 scheduler fallback only (#2876).\n\n### Empty announce \u2260 done (parent DoD) (#3044 / FC04 residual)\n\n! When a review-monitor settle arrives with **empty body**, **missing `STATUS:` line**, or **status unknown** (including host `(no output)` / empty `subagent_announce`):\n\n1. ! The parent MUST run **same-turn ground truth** before any DONE / CLEAN / merge-ready claim: at least `gh pr view <N>` (or REST `pulls/<N>`), `gh pr checks <N>`, and current HEAD SHA (`gh api repos/<owner>/<repo>/pulls/<N> -q .head.sha`).\n2. ! Classify the settle as **FC04 residual** (empty babysit \u2260 done) until ground truth shows a terminal merge/close outcome **or** an explicit structured `BLOCKED` / `FAILED` handback.\n3. \u2297 Treat empty / unknown settle as `DONE`, `CLEAN`, merge-ready, or batch-complete.\n4. \u2297 Spawn a second review-monitor solely because the first settle was empty/unknown without completing the ground-truth batch first (#3044 dual-lease recurrence).\n\n~ Recurrence: enterprize PR #43 (2026-08-02) \u2014 first monitor polled live, host settled empty/unknown; parent spawned a second same-`taskName` monitor; dual lease collision while PR stayed open. See also `meta/lessons.md` and FC04 / growth friction R1 + R10.\n\n\n### Completion latch on settle replay (#3092)\n\n! **Empty settle** is not a latch hit \u2014 use Empty announce \u2260 done (#3044) above. When the parent has already emitted **one** consolidate for a monitor/leaf `runId` and the harness re-delivers an **identical or equivalent** non-empty settle for the same key, stay **silent** (no re-QC, no second final; host silent token when defined). Re-open only on new runId, principal reopen, or material new evidence. Full MUST: `templates/agent-prompt-preamble.md` \u00a711.5.\n\n### Single review-monitor lease (#3044 / #2814)\n\n! **One sticky lease per PR:** ownership is the single sticky GitHub PR comment `<!-- deft:review-owner -->` (or the dual-invoke `review-monitor:register` form that writes it). Parallel ownership is forbidden.\n\n! **Pre-spawn check:** before launching another Approach 1 review-monitor (`sessions_spawn`, `spawn_subagent`, Cursor `Task`, Claude Code `Agent`, `start_agent`):\n\n1. ! Read the sticky lease (dual-invoke `verify:review-monitor` when available, else `gh api` issues comments for `<!-- deft:review-owner -->`).\n2. ! List active same-PR / same-`taskName` subagents when the host exposes that surface (OpenClaw `subagents list` or equivalent).\n3. \u2297 Spawn a second monitor while a prior owner is **running**.\n4. \u2297 Spawn a second monitor when the last settle was **empty/unknown** and ground truth has **not** shown a terminal merge/close (or explicit structured handback that releases ownership).\n5. ! If the prior owner is **dead** (liveness fail / `REDISPATCH_OK` / `verify:subagent-alive` exit 1) and the PR is still open: spawn **one** replacement monitor and re-claim the lease with **`--force`** (CLI: `deft review-monitor:register --pr <N> --monitor-agent-id <id> --force` / task: `task review-monitor:register -- --pr <N> --monitor-agent-id <id> --force`, or host equivalent force takeover) so a non-expired foreign lease does not block replacement \u2014 then **update** the sticky lease comment to the new owner. Never silent dual ownership.\n6. ! On register conflict when the prior owner is **still alive**: attach to the existing owner or stop \u2014 do not parallel-fix.\n7. \u2297 Refuse replacement of a dead owner solely because the 30-minute lease has not expired without attempting force takeover (#3044).\n\n### Required non-empty monitor handback (#3044)\n\n! Approach 1 review-monitor prompts (including `templates/swarm-greptile-poller-prompt.md` and any host-filled spawn prompt) MUST require a **non-empty** final handback with these fields:\n\n```text\nSTATUS: DONE|BLOCKED|FAILED\nHEAD: <sha>\nCHECKS: <summary>\nMERGE: <url|error|n/a>\nISSUE: <closed|open|n/a>\nNOTES: <short>\n```\n\n\u2297 Empty final assistant message from a review-monitor.\n\u2297 Parent treating a settle that lacks `STATUS:` as success.\n\n~ **Visible Control UI risk (#3044):** When OpenClaw Control UI is the operator plane, prefer `visible:true` on the review-monitor spawn; invisible empty settles are higher risk for FC04 misclassification. Cross-link: `skills/deft-directive-swarm/references/host-openclaw.md` Babysit / review-monitor residual.\n\n\n\n**Approach 2 (fallback -- no sub-agent primitive for the descriptor):**\n\n! When the platform descriptor indicates no sub-agent orchestration (or the primitive is unavailable), use discrete tool calls with a yield between checks. For `grok-build` / spawn_subagent descriptor this path is normally avoided in favor of Approach 1; it exists for pure interactive or limited runtimes.\n\n1. ! Use the current shell execution tool (`run_terminal_command` or equivalent in the runtime) in wait mode to run `gh pr view <number> --comments` and `gh pr checks <number>`.\n2. ! After each check, yield control (end all tool calls) -- the agent runtime will re-invoke after its interval or on next interaction.\n3. ! Target adaptive cadence (20-30s / 60s / 90s) where the runtime permits. The full cadence is easiest in Approach 1 (sub-agent) or 3 (blocking); pure yield is runtime-controlled.\n4. ! No blocking shell pane lock -- the conversation remains interactive between checks.\n5. ~ Approach 2 requires a periodic re-invocation trigger (timer, scheduler, user nudge, or external orchestrator for hybrid/worktree cases). Without it the poller stops after the first yield.\n6. ! When the exit condition is met, proceed to Step 5.\n\n\u26a0\ufe0f **Swarm / hybrid limitation**: Approach 2 is NOT autonomous for swarm agents or manual worktree setups. Yielding ends the turn with no self-wake; the parent monitor (or external scheduler) must detect idle and re-trigger or send a message. For true `grok-build` / spawn_subagent hybrids, prefer Approach 1 (spawn_subagent + get_command_or_subagent_output poller) exactly as the swarm launch adapter does.\n\n\u2297 Use blocking `Start-Sleep` shell loops or `time.sleep()` loops EXCEPT as Approach 3 (see below) -- these lock the conversation and prevent user interaction.\n\u2297 Poll more frequently than every 20 seconds -- use a real delay between checks, not back-to-back calls. Adaptive cadence (20-30s / 60s / 90s) replaces the fixed 60s minimum.\n\n**Approach 3 (last resort -- interactive session, no `start_agent`, no timer/scheduler):**\n\n! Approach 3 is a blocking sleep-poll loop used ONLY when both Approach 1 and Approach 2 are unavailable (interactive session with no `start_agent` and no auto-reinvocation mechanism). Uses PowerShell `sleep` / Unix `sleep` commands between polls.\n\n! **User warning gate:** Before activating Approach 3, the agent MUST warn the user that the conversation pane will be locked during polling and ask for explicit confirmation. Example: \"No sub-agent or auto-reinvocation available. I will poll in a blocking loop (~20-30s / 60s / 90s cadence). The conversation will be locked during polling. Proceed? (yes/no)\"\n\n\u2297 Activate Approach 3 without first warning the user that it will lock the conversation pane.\n\n1. ! After receiving user confirmation, use a blocking shell loop with adaptive cadence:\n - First check: wait ~25 seconds (e.g. `sleep 25`), then poll\n - Second check: wait ~60 seconds, then poll\n - Subsequent checks: wait ~90 seconds, then poll\n2. ! Poll using `gh pr view <number> --comments` and `gh pr checks <number>` in the same shell session\n3. ! When the exit condition is met (Greptile review current, confidence meets resolved min (policy/dogfood/default; see Step 6 #3095), no P0/P1), exit the loop and proceed to Step 5\n4. ! If the user interrupts (Ctrl+C or equivalent), exit gracefully and report current review status\n\n! Greptile may advance its review by **editing an existing PR issue comment** rather than creating a new PR review object. Do NOT rely solely on `pulls/{number}/reviews` \u2014 that endpoint may remain stale at an older commit SHA even after Greptile has reviewed the latest commit.\n\n! To confirm the review is current, check **both** surfaces:\n\n1. **PR issue comments** (primary signal) \u2014 Greptile edits its existing summary comment in place:\n - `gh pr view <number> --comments` (with `do_not_summarize_output: true`)\n - Or `gh api repos/<owner>/<repo>/issues/<number>/comments`\n - Parse the comment body for `Last reviewed commit` and compare to the pushed commit SHA\n - Check the comment's `updated_at` timestamp to confirm it was refreshed after your push\n2. **PR review objects** (secondary signal) \u2014 may or may not be updated:\n - `gh api repos/<owner>/<repo>/pulls/<number>/reviews`\n - Check `commit_id` on the latest review object\n\n! Treat an edited Greptile issue comment as a valid new review pass even if no new PR review object was created.\n\n! Fetch the full untruncated comment body or use MCP `get_comments` to get the actual commit URL containing the full SHA \u2014 do NOT rely on grepping truncated link text.\n\n\u2297 Re-fetch or re-trigger while the bot's last review still targets an older commit on **both** surfaces.\n\n### Step 5: Re-fetch and analyze\n\n! Fetch the new review using both methods from Step 1.\n\n! Analyze all new findings before planning any changes.\n\n### Step 6: Exit condition check \u2014 fail-closed ReviewerStatus all-of (#1259)\n\n! The loop MAY exit clean ONLY when a SINGLE fresh fetch (not cached state, not a verdict assembled across earlier polls) satisfies ALL of the `ReviewerStatus` fields below. This is a **fail-closed all-of**: any field that is missing, unparsed, or ambiguous resolves to **`unknown`**, and `unknown` is NOT a pass \u2014 the agent stays in the loop and returns to Step 2. A PARTIAL or STALE Greptile review MUST NOT satisfy the exit predicate; the predicate is what prevents merging un-reviewed code while a P0/P1 finding is still in flight (#1259).\n\n1. ! **Terminal check-run** \u2014 the `Greptile Review` check run on the current HEAD has `status == \"completed\"` AND `conclusion` in `{success, neutral}`. The conclusions `null`, `cancelled`, `timed_out`, `stale`, `action_required`, and `failure` are explicitly NOT terminal-clean: any of them resolves to `unknown` and the loop continues. A check run still `queued` / `in_progress` is `unknown`.\n2. ! **HEAD-SHA pinned AT READ TIME** \u2014 read the current HEAD SHA in the SAME fetch used to evaluate this predicate (`gh api repos/<owner>/<repo>/pulls/<number> -q .head.sha`, read AT exit-evaluation time, NOT carried over from an earlier poll) and require `head_sha_reviewed == current HEAD`. A review whose reviewed SHA lags HEAD is `unknown`.\n3. ! **Completion marker present and matching** \u2014 the rolling-summary comment body carries `Last reviewed commit: <sha>` AND that `<sha>` matches the current HEAD. Extract the SHA with the markdown-link-aware NON-GREEDY regex below. Markdown link text can contain escaped brackets (e.g. a commit subject `add \\[Unreleased\\] entry`), so a greedy `[^\\]]*` stops at the first `]` and yields no match \u2192 false `unknown` on a clean review (#1326):\n\n ```\n Last reviewed commit:\\s*\\[.*?\\]\\(https?://github\\.com/[^/]+/[^/]+/commit/(?P<sha>[0-9a-f]{7,40})\n ```\n\n A missing or non-matching completion marker is `unknown`. See [`../../templates/swarm-greptile-poller-prompt.md`](../../templates/swarm-greptile-poller-prompt.md) `### Last reviewed commit:` for the canonical regex shared with the push-driven poller loop.\n4. ! **Confidence meets resolved min (#3095)** \u2014 the parsed `Confidence Score: X/5` is **>=** the resolved floor from `plan.policy.review.minGreptileConfidence` (inspect: `task policy:show --field=minGreptileConfidence`; `pr:watch` / `pr:merge-ready` share this SoT). Resolution order: typed project policy > framework dogfood detect (framework source \u2192 **5**) > consumer default (**4**, legacy confidence > 3 / 4/5+). A score below the floor, an unparsed confidence, or an absent confidence is `unknown`. Directive dogfood MUST NOT exit CLEAN on 4/5.\n5. ! **No P0/P1 findings** \u2014 the triple-tier (+ Tier 2.5) detector reports zero P0 and zero P1 findings (P2 issues are non-blocking style suggestions and do not gate the loop).\n\n! All five fields MUST hold on the SAME single fresh fetch. The agent MUST NOT assemble a \"pass\" by combining a terminal check-run observed on one poll with a confidence parsed on an earlier poll \u2014 the read is atomic per the SHA-pinned-AT-READ-TIME rule above.\n\n? If the bot says \"all prior issues resolved\" but lists new issues, treat it as one final batch \u2014 not the start of another loop. Go back to Step 2 one more time, re-evaluate this all-of, then stop.\n\n\u2297 Exit the loop on a confidence number alone while the check run is non-terminal (`queued` / `in_progress` / `cancelled` / `timed_out` / `stale` / `action_required`) \u2014 a confidence score is NOT a verdict without a terminal check-run AND a HEAD-matching completion marker (#1259).\n\u2297 Exit the loop against a reviewed SHA that lags the current HEAD \u2014 a partial or stale review MUST resolve to `unknown`, never to a pass (#1259).\n\nIf the exit predicate is not met (any field `unknown`), go back to Step 2.\n\n## Mechanical mergeability is necessary, never sufficient (#3225)\n\n! GitHub **Ready to merge**, green required checks, and formal review state without Changes-Requested are **necessary but never sufficient** clean signals. Reviewer bots on repos without enforced review wiring often express **should-not-merge** + sub-threshold confidence **only in comment body prose** (no formal `REQUEST_CHANGES`, no blocking CheckRun). A shepherd that merges on mechanical signals alone merges against explicit advisory verdicts.\n\n! **`task pr:merge-ready` / `task pr:watch` / Step 6 clean** MUST parse advisory bot verdict text and confidence from comment bodies (the #1282-style body extraction path; shared detector in `packages/core/src/content-contracts/skills/greptile-detector.ts`). Treat any of the following as **blocking** regardless of formal review state or the Ready-to-merge box:\n\n1. Advisory should-not-merge prose (`should-not-merge`, `Not safe to merge`, `Do not merge`, `Safe to merge once corrected`, `not ready to merge`, \u2026)\n2. Confidence below the resolved `minGreptileConfidence` floor (#3095 \u2014 project policy > dogfood 5 > consumer default 4)\n3. P0/P1 findings (triple-tier + inline threads) or errored Greptile sentinel\n\n! When advisory prose blocks or confidence is sub-threshold: continue the fix/document loop or exit **BLOCKED** \u2014 \u2297 do not treat mechanical mergeability as CLEAN.\n\n~ Recommend repo-level review-gate wiring (required review / blocking Greptile CheckRun) for org repos that lack it, so formal state and prose verdict cannot diverge silently. Directive dogfood already enforces #3095; portable babysit paths on other org repos still need this prose gate.\n\n\u2297 Merge because the merge box says Ready to merge while bot comment prose says should-not-merge or confidence is below the resolved floor (#3225 / #3095).\n\u2297 Treat formal Comment (non-blocking) review state as sufficient when the rolling-summary body carries an advisory block.\n\n## Pre-Merge Re-Poll Gate (#1259)\n\n! Immediately before any `gh pr merge` invocation, the agent MUST re-fetch reviewer state ONE more time \u2014 a fresh `gh pr view <number> --comments`, a fresh `gh api repos/<owner>/<repo>/commits/<HEAD>/check-runs`, and a fresh HEAD-SHA read \u2014 and re-evaluate the Step 6 fail-closed all-of against that fresh fetch. The exit-condition pass recorded at the end of the review loop is NOT sufficient authorization to merge: review state can go stale between the loop's last poll and the merge call (a new push, a Greptile re-trigger, a service-side check-run reset).\n\n! Treat the re-poll and the `gh pr merge` as an atomic freshness window. If the re-poll shows ANY field `unknown`, ABORT the merge and return to Step 2.\n\n! Re-poll MUST also re-check advisory should-not-merge prose + confidence (#3225) \u2014 mechanical Ready-to-merge alone is never sufficient.\n\n\u2297 Call `gh pr merge` on the strength of a review verdict observed earlier in the loop without an immediately-preceding re-poll that re-satisfies the Step 6 all-of \u2014 merging on cached review state is forbidden (#1259).\n\u2297 Call `gh pr merge` on mechanical Ready-to-merge / green checks while advisory bot prose still records should-not-merge or sub-threshold confidence (#3225).\n\n### Informal-clean missing canonical fields (#1543)\n\nGreptile can post a **separate** informal clean reply that says prior issues are resolved and the current diff is clean while omitting the canonical rolling-summary fields Directive merge gates require: `Last reviewed commit:` and `Confidence Score: X/5`. `task pr:merge-ready` and `task swarm:verify-review-clean` correctly refuse merge-ready in this state -- prose alone cannot prove review currency or confidence.\n\n! When the latest Greptile bot comment is found, reports P0=0 and P1=0, but BOTH canonical fields are unparsed, classify the state as **`informal-clean missing-canonical-fields`** (see `task pr:merge-ready` diagnostic output) instead of treating it as \"review still writing\" or silently polling.\n\n! Recovery for informal-clean missing canonical fields -- route to ONE of these operator actions; do NOT keep polling:\n\n1. Comment `@greptileai review` on the PR to retrigger a canonical rolling summary on the current HEAD.\n2. Wait for Greptile to edit its primary rolling-summary comment with both canonical fields, then re-run `task pr:merge-ready -- <N>`.\n3. Document an explicit operator override per `skills/deft-directive-swarm/SKILL.md` Phase 6 Step 1 (merge with rationale in the merge commit body).\n\n\u2297 Treat informal clean Greptile prose (`current diff is clean`, `looks solid`, `no new issues`) as merge-ready without canonical `Last reviewed commit:` and `Confidence Score: X/5` evidence.\n\n\u2297 Keep polling silently when `task pr:merge-ready` reports the informal-clean missing-canonical-fields diagnostic -- this is a blocked recovery state, not a late-arriving review.\n\n~ Swarm pollers MUST surface this state via the `### (6) INFORMAL-CLEAN` terminal exit in `templates/swarm-greptile-poller-prompt.md` instead of falling through to generic `(4) TIMEOUT` or `(5) STALL`.\n\n## Submitting GitHub Reviews\n\n! When submitting PR reviews via the GitHub MCP tool, always use `pull_request_review_write` with method `create` and the appropriate event:\n\n- `APPROVE` \u2014 formally approve the PR (shows green \"Approved\" status)\n- `REQUEST_CHANGES` \u2014 block the PR with requested changes\n- `COMMENT` \u2014 review feedback without approving or blocking\n\n\u2297 Use `add_issue_comment` for review notes \u2014 that creates a regular comment, not a formal review. Review notes must always go in the review body via `pull_request_review_write`.\n\n## GitHub Interface Selection\n\n~ Use the most efficient interface for the task:\n\n- **MCP GitHub tool** \u2014 structured/programmatic operations (querying issues, creating PRs, bulk operations, filtering data)\n- **GitHub CLI (`gh`)** \u2014 quick ad-hoc commands and direct shell integration\n\nChoose whichever minimizes steps and maximizes clarity for the given task.\n\n~ When MCP is unavailable (agents without MCP tools in their dispatch environment, including `start_agent` / `spawn_subagent` (\"grok-build\") cases, cloud agents, `oz agent run`), `gh` CLI is sufficient as the sole interface. The dual-source requirement (MCP + `gh`) in Step 1 applies only when both are available -- agents without MCP access should use `gh pr view --comments` and `gh api` as their primary and only review detection surface. Runtime capability detection (swarm Phase 3 matrix) informs both orchestration tier and MCP surface choice.\n\n## Framework Events Emitted Here\n\n! When the user replies `yes` / `confirmed` / `approve` on a ready-to-merge PR thread (Phase 5 -> 6 gate per the canonical #642 workflow comment), emit a `plan:approved` framework event via `task lifecycle:event` so the approval is captured as a structural artifact rather than prose-only:\n\n```\ntask lifecycle:event -- emit plan:approved \\\n --plan-ref https://github.com/<owner>/<repo>/pull/<N> \\\n --approver <github-login> \\\n --approval-phrase <yes|confirmed|approve> \\\n --pr-number <N>\n```\n\n? Downstream consumers of `plan:approved` (auto-merge bots, status updates, audit reporting) are explicitly deferred to follow-up work; this event currently emits a record only (#635 events behavioral wiring).\n\n## Post-Merge Verification\n\n! Apply [`coding/review.md`](../../coding/review.md) post-merge closing-keyword verification. Adapter HOW for GitHub:\n\n! After a PR is squash-merged, verify that all referenced issues were actually closed. Squash merges can silently fail to process closing keywords (`Closes #N`, `Fixes #N`) from the PR body (#167).\n\n1. ! For each issue referenced with a closing keyword in the PR body, run:\n ```\n gh issue view <N> --json state --jq .state\n ```\n2. ! If the issue state is not `CLOSED`, close it manually with a comment referencing the merged PR:\n ```\n gh issue close <N> --comment \"Closed by #<PR> (squash merge \u2014 auto-close did not trigger)\"\n ```\n3. ~ This step mirrors `skills/deft-directive-swarm/SKILL.md` Phase 6 Step 2 and applies to ALL PR merges, not just swarm runs.\n4. ! For PRs that referenced any umbrella / staying-OPEN issue (`Refs #N`), the INVERSE check applies: any protected issue that auto-closed MUST be reopened with a comment citing #701 and the merged PR. See `skills/deft-directive-swarm/SKILL.md` Phase 6 Step 1 protected-issue reopen sweep and `meta/lessons.md` `## GitHub Closing-Keyword False-Positive Layer 3` for the persistent `closingIssuesReferences` link case (Layer 3, #701).\n\n\n## Probe-then-fill remote claims (#3120)\n\n! Before filling any **remote** handoff field (PR URL, PR number, commit/HEAD SHA, CI green/success, review score) or claiming `status: pass` / ship/gate done, MUST **probe then fill**:\n\n1. Run same-turn `git` + forge probes (examples: `git rev-parse HEAD`, `gh api repos/<owner>/<repo>/pulls/<N>`, `task pr:watch -- <N> --one-shot`, checks API).\n2. Copy IDs / URLs / SHAs / scores **only** from that probe JSON/text into the evidence block.\n3. Set `proof_status: bound` and attach short raw probe snippets (`command` + `snippet`) for each remote claim.\n\n! Handoff evidence axes: **work** (local) / **ship** (pushed branch or PR) / **gate** (CI/review on HEAD). `proof_status` is `bound` | `unbound` | `n/a-no-remote-claim`.\n! **Legal partial:** local work `done` + ship `not_started` / `blocked` **without** PR/SHA/CI/review fields and `proof_status: n/a-no-remote-claim` (or `status: partial`) is valid \u2014 do not invent ship state.\n! **Fail ranking:** **invented-done** (false/unbound remote artifacts under pass) is **stricter** than **empty-done**. Unbound remote claims \u2192 invalid evidence (fail), not pass-with-notes.\n! Machine check: `validateHandoffEvidence` in `packages/core/src/handoff-evidence/` (see `templates/agent-prompt-preamble.md` \u00a711).\n\u2297 Fill PR / SHA / CI / review fields from recollection, narration, or prior-turn memory.\n\u2297 Claim `status: pass` with remote fields when `proof_status` is not `bound` or probes are missing (#3120).\n\n## Anti-Patterns\n\n- \u2297 Multi-hour empty-commit / close-reopen thrash after CI weather thrash caps when `ci_never_scheduled` or `ci_cancelled_no_failover` (#3167)\n- \u2297 Workflow thrash or empty-commit spam during attributed platform outage without status-page probe (#3180)\n- \u2297 Merge or `--skip-ci` solely because a status page is red without check-run evidence (#3180)\n- \u2297 Block merge-ready wait on SLizard alone when Greptile Step 6 is clean (#3167)\n- \u2297 Silent admin / `--skip-ci` merge under Actions outage without audit comment and opt-in authority (#3167)\n- \u2297 Leave a deliberate `stop-at: pr-open` (or thin-DONE recovery) open PR without spawning/retaining one review-cycle babysit owner + lease continuity and post-merge `scope:complete` plan (#3153)\n- \u2297 Stand down at CLEAN under human-merge policy without a durable owner (sticky lease + live parent/monitor/Phase 6 closer) **and** a post-CLEAN observe path (poller / parent wake / Phase 6 re-poll) for post-merge `scope:complete` (#3153 / #1193 / #2321)\n- \u2297 Handoff human-merge cleanup to a short-lived leaf that exits at CLEAN without re-claiming the sticky lease (#3153)\n- \u2297 Retain only a sticky lease after CLEAN with no poller, no parent re-entry, and no Phase 6 merge re-poll \u2014 ownership-in-name-only (#3153)\n- \u2297 Dual-lease or freestyle Cursor global babysit for the partner merge-path after implement stops at PR-open (#3153 / #2261 / #3044)\n- \u2297 End owning turn with 0 children, no sticky lease, and no finish after drive-to-merge / babysit / shepherd claim \u2014 silent hold (#3090)\n- \u2297 Emit freeform `review_cycle: started` / `pending` / `initiated` or L4 `status: pass` without `done` or verifiable `in_progress:<pr>#\u2026` lease/parent-retained (#3090)\n- \u2297 Treat check-run SUCCESS alone as CLEAN / merge-ready while dual-source P0/P1 remain (#3090)\n- \u2297 Ignore [`coding/review.md`](../../coding/review.md) while running this adapter \u2014 universal batch/severity/exit/post-merge rules live there\n- \u2297 Route PR shepherding to Cursor global `babysit` on Deft-managed repos when `.deft/core/` is installed -- use this review-cycle skill instead (#2261)\n- \u2297 Route OpenClaw babysit/shepherd/watch to main-session gh poll + cron when `sessions_spawn` is available -- use Approach 1 with `sessions_spawn` (#2876 / #2261)\n- \u2297 Treat OpenClaw `cron` alone as Approach 1 \u2014 cron/timer is Approach 2 only if spawn is unavailable (#2876)\n- \u2297 Route Claude Code babysit/shepherd/watch to Approach 3 blocking poll when Claude `Agent` spawn is available \u2014 use Approach 1 with backgrounded `Agent` / `claude-agent` (#3134)\n- \u2297 Misclassify Claude Code as `cursor-composer` from bare `Task` alone (#3134)\n- \u2297 Expand active story scope past xBRIEF AC mid-babysit without follow-up issue or consented brief amend (#2881)\n- \u2297 Treat confidence-only holds (0 P0/P1) as a mandate for unbounded redesign (#2881)\n- \u2297 Dual-stop / conf-residual terminal halt without #3273 resume line (residual class + pursue residual / follow-up hard-stop / same as conf-hold / continue dual-stopped PR + skill section pointer) (#3273)\n- \u2297 Unlimited residual auto-retry after dual-stop without new operator consent (#3273 / #2442)\n- \u2297 Invent freestyle sleep/poll loops when dual-invoke probes fail for `pr:watch` \u2014 use the official gh-only fallback and fail-loud missing-task (#2878 / #2893)\n- \u2297 Treat bare `task pr:watch` as the only consumer gate form \u2014 probe `deft` then `task deft:` first (#2893)\n- \u2297 Treat a passing SLizard/Greptile check run, a non-blocking review comment, or an ad hoc fix commit as the review-cycle exit predicate -- Step 6 fail-closed all-of (#1259) and multi-reviewer registry triage (#769) still apply\n- \u2297 Push individual fix commits per finding\n- \u2297 Start fixing before analyzing ALL findings\n- \u2297 Rely on the bot to catch syntax errors in structured data files\n- \u2297 Re-trigger a bot review before the previous one has updated\n- \u2297 Report \"all comments resolved\" without checking both `gh pr view --comments` and a second source (`get_review_comments` via MCP, or `gh api` fallback when MCP is unavailable)\n- \u2297 Use `add_issue_comment` for formal review submission\n- \u2297 Commit or push Phase 1 audit fixes independently \u2014 always batch with Phase 2 fixes\n- \u2297 Proceed to Phase 2 while any Phase 1 prerequisite is unmet\n- \u2297 Rely solely on `pulls/{number}/reviews` to detect whether Greptile has reviewed the latest commit \u2014 Greptile may update via an edited issue comment instead of a new review object\n- \u2297 Push additional commits while Greptile is reviewing the current head \u2014 each push re-triggers Greptile and resets the review clock\n- \u2297 Use blocking `Start-Sleep` shell loops or `time.sleep()` loops to poll for review updates when Approach 1 or 2 is available -- Approach 3 (blocking loop) is permitted only as a last resort with user warning\n- \u2297 Poll more frequently than every 20 seconds -- use a real delay between checks, not back-to-back calls; adaptive cadence (20-30s / 60s / 90s) replaces the fixed 60s minimum\n- \u2297 Stop and ask the user whether to continue after pushing -- the review/fix loop MUST run autonomously to the exit condition\n- \u2297 Push fix commits without scanning changed lines for untested code paths \u2014 always check test coverage before pushing\n- \u2297 Push a fix commit that addresses fewer findings than the current Greptile review surfaces \u2014 if Greptile flags 3 issues, all 3 must be fixed in one commit before pushing\n- \u2297 Push after fixing a P1 without first checking whether the same Greptile review contains additional P0 or P1 findings\n- \u2297 Assume squash merge auto-closed referenced issues \u2014 always verify with `gh issue view` after merge (#167)\n- \u2297 Assume Approach 2 (yield-between-polls) produces a self-sustaining polling loop -- yielding ends the agent's turn with no self-wake; swarm agents will silently stop polling\n- \u2297 Skip the second review source (MCP or `gh api` fallback) without probing for MCP capability and documenting the fallback used\n- \u2297 Run a partial test suite instead of `task check` without documenting the pre-existing failure reason and open issue number in the PR body\n- \u2297 Create a PR without running `skills/deft-directive-pre-pr/SKILL.md` first -- the pre-PR quality loop catches issues before they reach the reviewer\n- \u2297 Activate Approach 3 (blocking `Start-Sleep` loop) without first warning the user that it will lock the conversation pane and receiving confirmation\n- \u2297 Exit the review loop on a Greptile confidence number alone while the check run is non-terminal -- a confidence score is NOT a verdict without a terminal check-run (`completed` + `{success, neutral}`) AND a HEAD-matching `Last reviewed commit:` completion marker (#1259)\n- \u2297 Call `gh pr merge` on cached/earlier review state without an immediately-preceding pre-merge re-poll that re-satisfies the Step 6 fail-closed all-of (#1259)\n- \u2297 Merge on mechanical Ready-to-merge / green checks while bot comment prose records should-not-merge or confidence below `minGreptileConfidence` (#3225 / #3095)\n- \u2297 Treat formal non-blocking review state as sufficient when rolling-summary body carries an advisory block (#3225)\n- \u2297 Treat empty/unknown review-monitor settle as DONE/CLEAN/merge-ready without same-turn ground truth (#3044 / FC04 residual)\n- \u2297 Spawn a second review-monitor while prior owner is running or last settle was empty/unknown without terminal ground truth (#3044)\n- \u2297 Accept empty review-monitor final message missing STATUS/HEAD/CHECKS/MERGE handback (#3044)\n- \u2297 Invent remote PR/SHA/CI/review claims in handoff evidence without same-turn probe binding \u2014 invented-done (#3120)\n- \u2297 Fill remote ship/gate fields from memory when only local work completed; legal partial omits PR fields (#3120)",
268
273
  "frontmatter_extra": null
269
274
  },
270
275
  {
@@ -286,11 +291,16 @@
286
291
  "triggers": [
287
292
  "swarm",
288
293
  "parallel agents",
289
- "run agents"
294
+ "run agents",
295
+ "pursue residual",
296
+ "follow-up hard-stop",
297
+ "same as conf-hold",
298
+ "continue dual-stopped PR",
299
+ "re-babysit residual"
290
300
  ],
291
301
  "path": "skills/deft-directive-swarm/SKILL.md",
292
302
  "version": "0.1",
293
- "body": "# Deft Directive Swarm\n\nStructured workflow for a monitor agent to orchestrate N parallel local agents working on story-level xBRIEFs from `xbrief/active/`.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, \u2249=SHOULD NOT, \u2297=MUST NOT, ?=MAY.\n\n**\u26a0\ufe0f See also**: [swarm.md](../../swarm/swarm.md) | [deft-directive-review-cycle](../deft-directive-review-cycle/SKILL.md)\n\n## Platform Requirements\n\n! This skill requires **GitHub** as the SCM platform and the **GitHub CLI (`gh`)** to be installed and authenticated. Issue fetching, PR creation, and post-merge verification all depend on `gh`.\n\n## Branch-Protection Policy Guard\n\n! Before any state mutation (creating worktrees, dispatching sub-agents, opening PRs), run the skill-level branch-policy guard (#746 / #747). Halt with the actionable disclosure message when the project's `plan.policy.allowDirectCommitsToMaster` is unresolvable AND `DEFT_ALLOW_DEFAULT_BRANCH_COMMIT` is unset:\n\n```\ntask verify:branch || exit 1\n```\n\nThe swarm skill creates branches per agent so the guard is mostly informational here, but a malformed PROJECT-DEFINITION (missing `plan.policy` block AND no legacy narrative) is a fail-closed signal worth surfacing before the swarm spawns N agents.\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (Phase 0 Step 0 queue-driven promote prompts (#1142 / N2), Step 0.5 bridge approval gate, Step 5 final-approval gate, Phase 1 Step 3 file-overlap audit gate, Phase 5->6 ready-to-merge gate) MUST follow [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md): render the canonical numbered menu in chat unless the host UI visibly preserves numeric option labels and returns numeric selections or exact displayed option text. The final two numbered options MUST be `Discuss` and `Back`, in that order. The Discuss-pause semantic is documented verbatim there -- on `Discuss` selection the agent MUST halt the in-progress sequence immediately, prompt `What would you like to discuss?`, and resume only on an explicit user signal. Implicit resumption is forbidden, and fallback chat replies MUST map only to the displayed number or exact displayed option text.\n\n## When to Use\n\n- User says \"run agents\", \"parallel agents\", \"swarm\", or \"launch N agents on stories\"\n- Multiple independent story-level xBRIEFs in `xbrief/active/` need to be worked on simultaneously\n- A batch of stories are ready and have no mutual dependencies\n\n## Prerequisites\n\n- ! `xbrief/active/` contains one or more story-level xBRIEFs with status `running`\n- ! GitHub CLI (`gh`) is authenticated\n- ! `git` supports worktrees (`git worktree` available)\n- ~ `oz` CLI available (for `oz agent run-cloud` cloud launch \u2014 see host-generic / Phase 3)\n\n## Host-adapter load path (#2928)\n\nLarge multi-host skills use a **host-neutral core** plus **one** per-host adapter after detect.\n\n| Step | Action |\n|------|--------|\n| 1 | Read this thin SKILL (triggers, MUST gates, detect, route table) |\n| 2 | Run **Runtime Capability Detection** (below) \u2192 stable platform descriptor |\n| 3 | Load host-neutral depth: `references/core-phase-*.md` + `references/core-ops.md` as needed for the current phase |\n| 4 | Load **exactly one** `references/host-*.md` from the route table |\n| 5 | Launch / monitor / hand off using core + that adapter only |\n\n### Route table (detect \u2192 one adapter)\n\n| Detected descriptor | Spawn primitive | Load adapter |\n|---------------------|-----------------|--------------|\n| `warp-orchestrated` / `warp-manual` | `start_agent` / Warp tabs | [`references/host-warp.md`](references/host-warp.md) |\n| `cursor-composer` / `cursor-cloud-agent` | Cursor `Task` | [`references/host-cursor.md`](references/host-cursor.md) |\n| `claude-code` | Claude `Agent` (`run_in_background`) / `claude-agent` | [`references/host-claude-code.md`](references/host-claude-code.md) |\n| `openclaw` | `sessions_spawn` | [`references/host-openclaw.md`](references/host-openclaw.md) |\n| `grok-build` | `spawn_subagent` | [`references/host-grok-build.md`](references/host-grok-build.md) |\n| `generic-terminal` (or explicit cloud) | serial / paste / `oz agent run-cloud` | [`references/host-generic.md`](references/host-generic.md) |\n\n### Core reference index (host-neutral)\n\n| Phase / topic | File |\n|---------------|------|\n| Phase 0 \u2014 Allocate | [`references/core-phase-0.md`](references/core-phase-0.md) |\n| Phase 1\u20132 \u2014 Select + Setup | [`references/core-phase-1-2.md`](references/core-phase-1-2.md) |\n| Phase 3 \u2014 Launch (neutral + detect detail) | [`references/core-phase-3.md`](references/core-phase-3.md) |\n| Phase 4 \u2014 Monitor | [`references/core-phase-4.md`](references/core-phase-4.md) |\n| Phase 5\u20136 \u2014 Review + Close | [`references/core-phase-5-6.md`](references/core-phase-5-6.md) |\n| Crash recovery, prompts, anti-patterns | [`references/core-ops.md`](references/core-ops.md) |\n\n\u2297 Load all host adapters \u201cjust in case.\u201d Unused host wiring stays out of context (#2928).\n\u2249 Paste full host manuals into this thin SKILL \u2014 keep detect short; depth lives in one adapter.\n\n## Hard gates (all hosts)\n\n### Worktree isolation before parallel spawn\n\n! One isolated git worktree per parallel agent (Phase 2). Create worktrees or consume a worktree-map **before** dispatch.\n! On **OpenClaw**, parallel leaves: worktree or worktree-map **before** `sessions_spawn`; worker cwd = that worktree; fail loud if the cohort would share the repo root (#2929). Full rules: [`references/host-openclaw.md`](references/host-openclaw.md).\n\u2297 DIY multi-leaf `sessions_spawn` without worktree prep (#2929).\n\n### Next-phase tool dispatch (#2934)\n\n! After a coding cohort completes (last expected child completion / cohort phase boundary), the parent **MUST** in the **same turn** either:\n- dispatch the next phase with a real tool call (`sessions_spawn` / host spawn / `task swarm:launch` / review-cycle start / merge cascade start), **or**\n- write explicit terminal status (`blocked` / `awaiting-human` / `done`) with a machine-checkable reason.\n\n\u2297 End the turn with only narrative \u201cI will spawn\u2026\u201d / \u201creview next\u201d and zero tools (#2934).\n~ Keep a small phase-state note: `cohort_id \u2192 phase \u2192 next_action|terminal`.\n\n### Parent-monitor after leaf announce (#2943 / hard-stop #3131)\n\n! After any leaf completion event (`subagent_announce` / parent-push / host completion notify), the parent\u2019s **first response** MUST be one of:\n- tool-first ground-truth batch (`gh` / `git` / worktree or file status) then one consolidate, **or**\n- host yield (`sessions_yield` on OpenClaw, or equivalent), **or**\n- one short user answer that is **not** a repeated progress line.\n\n! **Hard-stop (machine-checkable, not prose-only):** **MUST NOT** emit N>2 near-identical assistant sentences (or streaming text chunks) in one turn with no `tool_use` / yield \u2014 **FC14** text-repetition hang. Library: `evaluateParentTurnShape` in `@deftai/directive-core/parent-turn-shape` (`packages/core/src/parent-turn-shape/`). Hosts SHOULD abort the turn when `ok === false`. Operator recovery: `docs/openclaw-agent-host.md` \u00a7 Operator recovery \u2014 FC14. Soft skill text is **not** sole mitigation (#3131).\n\n! **Thin DONE = failed leaf:** completion without PR URL / merge evidence is **failed** (re-dispatch or take over) \u2014 not success. Prefer structured fields when present (`prUrl`, `mergeStatus`, `emptyDiff`).\n\n\u2297 Multi-sentence progress-only first response after announce with zero tools / yield (#2943 text-repetition hang).\n\u2297 N>2 near-identical assistant sentences with no tool_use / yield (FC14 / #3131 hard-stop).\n\u2297 Treat thin DONE (no PR URL / merge evidence) as success (#2943).\n\u2297 Rely on soft skill prose alone as the sole mitigation for the parent hang (#3131).\n\n\n\n### Completion latch after first consolidate (#3092)\n\n! After the parent emits **one** user/caller-visible consolidate for a child `runId` / settle batch, **identical or equivalent completion replay** for the same key MUST be **silent** (no tools, no re-QC, no second final; host silent token when defined, e.g. OpenClaw `NO_REPLY`). Re-open only on new `runId`/batch, principal explicit reopen, or materially new evidence (new HEAD, new blocker class). Replay storms: at most one fail-loud note, then silent. Full MUST: `templates/agent-prompt-preamble.md` \u00a711.5. Depth: `references/core-phase-5-6.md`. Orthogonal to empty settle \u2260 done (#3044).\n\n### Dual stop \u2014 repair and monitor loops (#2442)\n\n! Multi-iteration swarm **repair** and **monitor** loops MUST carry dual stop: success (goal/AC/clean gate) **and** a failure/budget stop. Single-turn probes (one status check, one heartbeat read) are exempt. Principle: `main.md` `## Dual Stop Rule (#2442)`. Defaults and halt-report shape live in [`references/core-phase-4.md`](references/core-phase-4.md) (monitor / takeover) and [`references/core-ops.md`](references/core-ops.md) (prompts + anti-patterns).\n\n! Default failure envelope for repair/monitor class work (unless the operator or xBRIEF names a stricter one):\n- **max iterations:** 3 monitor repair actions (re-dispatch, takeover complete, re-trigger review) for the same leaf/PR failure class, **or**\n- **no-progress:** same error / same Greptile P0-P1 fingerprint / same idle state **3+** times with no material worktree or review change (composes with Phase 4 \"stuck in an error loop\" takeover trigger), **or**\n- **budget:** existing poll caps (`pr:watch` max-wait, Greptile service-error single retry + escalate) count as budget stops -- do not invent a second unbounded poll loop outside them.\n\n! On failure stop: halt automatic continuation; emit an operator-visible report (what was tried, what is missing, what human decision is needed). \u2297 Silent re-dispatch or infinite monitor continuation after the envelope is exhausted.\n\n! Composes with minimal-subgraph repair guidance (#2439): keep repairs minimal **and** bounded by dual-stop -- minimal repair is not a license to thrash. Durable delivery/acceptance circuit-breaker: **#3143** `packages/core/src/delivery-attempt/` (`evaluatePreDispatch`, unit ledger). Docs: `docs/delivery-attempt.md`. Skill defaults remain behavioral; mechanical gate lives in core.\n\n## Runtime Capability Detection (summary)\n\n! Before selecting a launch method, probe the environment. Full probe text: [`references/core-phase-3.md`](references/core-phase-3.md).\n\n1. ! **Probe for `start_agent` tool** \u2014 Warp orchestrated.\n2. ! **Probe for Warp environment** \u2014 `WARP_*` without `start_agent` \u2192 warp-manual.\n3. ! **Probe for the Cursor `Task` tool** \u2014 Tier 1; descriptor `cursor-composer` / `cursor-cloud-agent` (#1877). Require Cursor signals (`CURSOR_*` or Cursor-only Task surface) \u2014 not bare `Task` alone.\n4. ! **Probe for Claude Code** \u2014 Tier 1; descriptor `claude-code` (#3134). Claude-unique signals only: `Agent` (or `CreateAgent` / `SubagentStart`) with background / `run_in_background`, and/or `DEFT_PROBE_CLAUDE_CODE` / `DEFT_AGENT_RUNTIME=claude-code` / `CLAUDECODE`. \u2297 Misclassify as `cursor-composer` via bare `Task`.\n5. ! **Probe for the OpenClaw `sessions_spawn` tool** \u2014 Tier 1; descriptor `openclaw` (#2875). Do NOT misclassify as `grok-build` or `generic-terminal`.\n6. ! **Probe for `spawn_subagent` tool** \u2014 descriptor `grok-build`.\n7. ! **Select launch path automatically** \u2014 load the matching host adapter (route table). No static A/B/C menu.\n8. ! **Return a stable platform descriptor** for Phase 4/6: `warp-orchestrated`, `warp-manual`, `cursor-composer`, `cursor-cloud-agent`, `claude-code`, `openclaw`, `grok-build`, or `generic-terminal`.\n9. ? **Cloud escape hatch** \u2014 `oz agent run-cloud` only on explicit user request (host-generic).\n\n\u2297 Present static launch options instead of detecting capabilities at runtime.\n\u2297 Offer Warp-specific launch paths when not inside Warp.\n\u2297 Classify Claude Code as `cursor-composer` / `generic-terminal` when Claude-unique signals are present (#3134).\n\n## Retained addressable sub-agents (#3158)\n\nNamed mode **beside** dispatch-and-collect. Canon: [`../../swarm/swarm.md`](../../swarm/swarm.md) `## Retained addressable sub-agents (#3158)`.\n\n| Mode | When | Mid-scope gate |\n|------|------|----------------|\n| **retained-child** (message-later / steer-mid-flight) | Host keeps a live, addressable child (`agent_id` / session name); parent can re-message or steer mid-flight | Single dispatch MAY pause for approval and continue the **same** child |\n| **dispatch-and-collect** (one-shot) | Host has no continue/resume; worker terminal on tool-loop exit | **Split-dispatch** mandatory (#954): Scope A \u2192 report \u2192 approve \u2192 Scope B |\n\n! After platform detect, read the loaded host adapter's **Retained / continue-by-id** note. Prefer continue-by-agent-id / resume-by-name / steerable mid-flight **only when that adapter documents support**.\n! When the host cannot retain: keep one-shot envelopes and split-dispatch mid-scope gates. Do not claim message-later semantics the platform cannot deliver.\n! Stance (#3164): retention is **orchestration only** \u2014 not mid-run constitution self-edit (managed AGENTS, pinned skills, policy).\n! Topology (#3155): retained children MUST obey nuclear-family A2A bounds (parent/sibling/child only).\n\u2297 Force a second full dispatch on a retain-capable host solely because a mid-scope gate exists \u2014 re-message the live child instead.\n\u2297 Invent retain / resume on hosts whose adapter marks one-shot only.\n\n## Phase overview\n\n| Phase | Goal | Depth |\n|-------|------|-------|\n| 0 Allocate | Queue cohort, readiness, approval | `core-phase-0.md` |\n| 1 Select | Confirm candidates, file-overlap | `core-phase-1-2.md` |\n| 2 Setup | Worktrees + prompt files | `core-phase-1-2.md` |\n| 3 Launch | Detect, preflight, **one** host spawn | `core-phase-3.md` + **one** `host-*.md` |\n| 4 Monitor | Heartbeats, takeover, no duplicate agents | `core-phase-4.md` (+ host notes) |\n| 5 Review | Greptile clean, gates, **next-phase tools** | `core-phase-5-6.md` |\n| 6 Close | Merge cascade, cohort sweep, cleanup | `core-phase-5-6.md` |\n\n! Follow phases in order. Depth files hold the operative MUST rules; this page is the dispatch card.\n\n## Effort estimate on dispatch (#1581)\n\n! When plan items carry optional `effort` (S/M/L/XL with time anchors in `vbrief/vbrief.md`), use them for sizing: S/M single-agent, L may need a dedicated agent, XL blocks dispatch until broken into S/M/L. Activate fails closed on XL. Depth: [`references/core-phase-0.md`](references/core-phase-0.md) Steps 2\u20133.\n! Plan-item effort is **post-planning** (confirms/corrects provisional intake estimates). It is **not** session-start ritual input; ceremony dial (#3214) starts rapid and escalates \u2014 do not block cold-start ritual on missing plan-item `effort`. Headless: no operator confirmation for size or stage transitions.\n\n## Critical anti-patterns (dispatch card)\n\n- \u2297 Load all host adapters \u201cjust in case\u201d (#2928)\n- \u2297 Parallel OpenClaw `sessions_spawn` on shared repo root without worktrees (#2929)\n- \u2297 Prose-only phase handoff after cohort complete (\u201cI will spawn\u2026\u201d) (#2934)\n- \u2297 Multi-sentence progress-only first response after leaf announce with zero tools / yield (#2943)\n- \u2297 N>2 near-identical assistant sentences with no tool_use / yield (FC14 / #3131 hard-stop)\n- \u2297 Treat thin DONE (no PR URL / merge evidence) as success (#2943)\n- \u2297 Rely on soft skill prose alone as the sole parent-hang mitigation (#3131)\n- \u2297 Second+ user-visible consolidate for the same child runId without new evidence (#3092)\n- \u2297 Assign overlapping files to multiple agents\n- \u2297 Dispatch or activate work that still has `plan.items[].effort: \"XL\"` without breakdown (#1581)\n- \u2297 Merge before Greptile exit condition (score > 3, no P0/P1)\n- \u2297 Skip Phase 0 approval before Phase 1\n- \u2297 Misclassify OpenClaw `sessions_spawn` as `grok-build` or `generic-terminal` (#2875)\n- \u2297 Misclassify Claude Code as `cursor-composer` / `generic-terminal` (#3134)\n- \u2297 Run multi-iteration repair/monitor loops without a failure stop or with silent continuation after the envelope is exhausted (#2442)\n- \u2297 Force a second full dispatch on a retain-capable host solely for a mid-scope gate, or invent retain on one-shot hosts (#3158)\n- \u2297 Use retained-child messaging for mid-run constitution self-edit (#3158 / #3164)\n\nFull anti-pattern list: [`references/core-ops.md`](references/core-ops.md).",
303
+ "body": "# Deft Directive Swarm\n\nStructured workflow for a monitor agent to orchestrate N parallel local agents working on story-level xBRIEFs from `xbrief/active/`.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, \u2249=SHOULD NOT, \u2297=MUST NOT, ?=MAY.\n\n**\u26a0\ufe0f See also**: [swarm.md](../../swarm/swarm.md) | [deft-directive-review-cycle](../deft-directive-review-cycle/SKILL.md)\n\n## Platform Requirements\n\n! This skill requires **GitHub** as the SCM platform and the **GitHub CLI (`gh`)** to be installed and authenticated. Issue fetching, PR creation, and post-merge verification all depend on `gh`.\n\n## Branch-Protection Policy Guard\n\n! Before any state mutation (creating worktrees, dispatching sub-agents, opening PRs), run the skill-level branch-policy guard (#746 / #747). Halt with the actionable disclosure message when the project's `plan.policy.allowDirectCommitsToMaster` is unresolvable AND `DEFT_ALLOW_DEFAULT_BRANCH_COMMIT` is unset:\n\n```\ntask verify:branch || exit 1\n```\n\nThe swarm skill creates branches per agent so the guard is mostly informational here, but a malformed PROJECT-DEFINITION (missing `plan.policy` block AND no legacy narrative) is a fail-closed signal worth surfacing before the swarm spawns N agents.\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (Phase 0 Step 0 queue-driven promote prompts (#1142 / N2), Step 0.5 bridge approval gate, Step 5 final-approval gate, Phase 1 Step 3 file-overlap audit gate, Phase 5->6 ready-to-merge gate) MUST follow [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md): render the canonical numbered menu in chat unless the host UI visibly preserves numeric option labels and returns numeric selections or exact displayed option text. The final two numbered options MUST be `Discuss` and `Back`, in that order. The Discuss-pause semantic is documented verbatim there -- on `Discuss` selection the agent MUST halt the in-progress sequence immediately, prompt `What would you like to discuss?`, and resume only on an explicit user signal. Implicit resumption is forbidden, and fallback chat replies MUST map only to the displayed number or exact displayed option text.\n\n## When to Use\n\n- User says \"run agents\", \"parallel agents\", \"swarm\", or \"launch N agents on stories\"\n- Multiple independent story-level xBRIEFs in `xbrief/active/` need to be worked on simultaneously\n- A batch of stories are ready and have no mutual dependencies\n- Operator re-authorizes a dual-stopped / hard-stopped / conf-hold unit: **pursue residual**, **follow-up hard-stop**, **same as conf-hold**, **continue dual-stopped PR**, or **re-babysit residual** \u2014 route to \u00a7 Operator follow-up after dual-stop / hard stop (#3273)\n\n## Prerequisites\n\n- ! `xbrief/active/` contains one or more story-level xBRIEFs with status `running`\n- ! GitHub CLI (`gh`) is authenticated\n- ! `git` supports worktrees (`git worktree` available)\n- ~ `oz` CLI available (for `oz agent run-cloud` cloud launch \u2014 see host-generic / Phase 3)\n\n## Host-adapter load path (#2928)\n\nLarge multi-host skills use a **host-neutral core** plus **one** per-host adapter after detect.\n\n| Step | Action |\n|------|--------|\n| 1 | Read this thin SKILL (triggers, MUST gates, detect, route table) |\n| 2 | Run **Runtime Capability Detection** (below) \u2192 stable platform descriptor |\n| 3 | Load host-neutral depth: `references/core-phase-*.md` + `references/core-ops.md` as needed for the current phase |\n| 4 | Load **exactly one** `references/host-*.md` from the route table |\n| 5 | Launch / monitor / hand off using core + that adapter only |\n\n### Route table (detect \u2192 one adapter)\n\n| Detected descriptor | Spawn primitive | Load adapter |\n|---------------------|-----------------|--------------|\n| `warp-orchestrated` / `warp-manual` | `start_agent` / Warp tabs | [`references/host-warp.md`](references/host-warp.md) |\n| `cursor-composer` / `cursor-cloud-agent` | Cursor `Task` | [`references/host-cursor.md`](references/host-cursor.md) |\n| `claude-code` | Claude `Agent` (`run_in_background`) / `claude-agent` | [`references/host-claude-code.md`](references/host-claude-code.md) |\n| `openclaw` | `sessions_spawn` | [`references/host-openclaw.md`](references/host-openclaw.md) |\n| `grok-build` | `spawn_subagent` | [`references/host-grok-build.md`](references/host-grok-build.md) |\n| `generic-terminal` (or explicit cloud) | serial / paste / `oz agent run-cloud` | [`references/host-generic.md`](references/host-generic.md) |\n\n### Core reference index (host-neutral)\n\n| Phase / topic | File |\n|---------------|------|\n| Phase 0 \u2014 Allocate | [`references/core-phase-0.md`](references/core-phase-0.md) |\n| Phase 1\u20132 \u2014 Select + Setup | [`references/core-phase-1-2.md`](references/core-phase-1-2.md) |\n| Phase 3 \u2014 Launch (neutral + detect detail) | [`references/core-phase-3.md`](references/core-phase-3.md) |\n| Phase 4 \u2014 Monitor | [`references/core-phase-4.md`](references/core-phase-4.md) |\n| Phase 5\u20136 \u2014 Review + Close | [`references/core-phase-5-6.md`](references/core-phase-5-6.md) |\n| Crash recovery, prompts, anti-patterns | [`references/core-ops.md`](references/core-ops.md) |\n\n\u2297 Load all host adapters \u201cjust in case.\u201d Unused host wiring stays out of context (#2928).\n\u2249 Paste full host manuals into this thin SKILL \u2014 keep detect short; depth lives in one adapter.\n\n## Hard gates (all hosts)\n\n### Worktree isolation before parallel spawn\n\n! One isolated git worktree per parallel agent (Phase 2). Create worktrees or consume a worktree-map **before** dispatch.\n! On **OpenClaw**, parallel leaves: worktree or worktree-map **before** `sessions_spawn`; worker cwd = that worktree; fail loud if the cohort would share the repo root (#2929). Full rules: [`references/host-openclaw.md`](references/host-openclaw.md).\n\u2297 DIY multi-leaf `sessions_spawn` without worktree prep (#2929).\n\n### Next-phase tool dispatch (#2934)\n\n! After a coding cohort completes (last expected child completion / cohort phase boundary), the parent **MUST** in the **same turn** either:\n- dispatch the next phase with a real tool call (`sessions_spawn` / host spawn / `task swarm:launch` / review-cycle start / merge cascade start), **or**\n- write explicit terminal status (`blocked` / `awaiting-human` / `done`) with a machine-checkable reason.\n\n\u2297 End the turn with only narrative \u201cI will spawn\u2026\u201d / \u201creview next\u201d and zero tools (#2934).\n~ Keep a small phase-state note: `cohort_id \u2192 phase \u2192 next_action|terminal`.\n\n### Parent-monitor after leaf announce (#2943 / hard-stop #3131)\n\n! After any leaf completion event (`subagent_announce` / parent-push / host completion notify), the parent\u2019s **first response** MUST be one of:\n- tool-first ground-truth batch (`gh` / `git` / worktree or file status) then one consolidate, **or**\n- host yield (`sessions_yield` on OpenClaw, or equivalent), **or**\n- one short user answer that is **not** a repeated progress line.\n\n! **Hard-stop (machine-checkable, not prose-only):** **MUST NOT** emit N>2 near-identical assistant sentences (or streaming text chunks) in one turn with no `tool_use` / yield \u2014 **FC14** text-repetition hang. Library: `evaluateParentTurnShape` in `@deftai/directive-core/parent-turn-shape` (`packages/core/src/parent-turn-shape/`). Hosts SHOULD abort the turn when `ok === false`. Operator recovery: `docs/openclaw-agent-host.md` \u00a7 Operator recovery \u2014 FC14. Soft skill text is **not** sole mitigation (#3131).\n\n! **Thin DONE = failed leaf:** completion without PR URL / merge evidence is **failed** (re-dispatch or take over) \u2014 not success. Prefer structured fields when present (`prUrl`, `mergeStatus`, `emptyDiff`).\n\n\u2297 Multi-sentence progress-only first response after announce with zero tools / yield (#2943 text-repetition hang).\n\u2297 N>2 near-identical assistant sentences with no tool_use / yield (FC14 / #3131 hard-stop).\n\u2297 Treat thin DONE (no PR URL / merge evidence) as success (#2943).\n\u2297 Rely on soft skill prose alone as the sole mitigation for the parent hang (#3131).\n\n\n\n### Completion latch after first consolidate (#3092)\n\n! After the parent emits **one** user/caller-visible consolidate for a child `runId` / settle batch, **identical or equivalent completion replay** for the same key MUST be **silent** (no tools, no re-QC, no second final; host silent token when defined, e.g. OpenClaw `NO_REPLY`). Re-open only on new `runId`/batch, principal explicit reopen, or materially new evidence (new HEAD, new blocker class). Replay storms: at most one fail-loud note, then silent. Full MUST: `templates/agent-prompt-preamble.md` \u00a711.5. Depth: `references/core-phase-5-6.md`. Orthogonal to empty settle \u2260 done (#3044).\n\n### Dual stop \u2014 repair and monitor loops (#2442)\n\n! Multi-iteration swarm **repair** and **monitor** loops MUST carry dual stop: success (goal/AC/clean gate) **and** a failure/budget stop. Single-turn probes (one status check, one heartbeat read) are exempt. Principle: `main.md` `## Dual Stop Rule (#2442)`. Defaults and halt-report shape live in [`references/core-phase-4.md`](references/core-phase-4.md) (monitor / takeover) and [`references/core-ops.md`](references/core-ops.md) (prompts + anti-patterns).\n\n! Default failure envelope for repair/monitor class work (unless the operator or xBRIEF names a stricter one):\n- **max iterations:** 3 monitor repair actions (re-dispatch, takeover complete, re-trigger review) for the same leaf/PR failure class, **or**\n- **no-progress:** same error / same Greptile P0-P1 fingerprint / same idle state **3+** times with no material worktree or review change (composes with Phase 4 \"stuck in an error loop\" takeover trigger), **or**\n- **budget:** existing poll caps (`pr:watch` max-wait, Greptile service-error single retry + escalate) count as budget stops -- do not invent a second unbounded poll loop outside them.\n\n! On failure stop: halt automatic continuation; emit an operator-visible report (what was tried, what is missing, what human decision is needed). \u2297 Silent re-dispatch or infinite monitor continuation after the envelope is exhausted.\n\n! **Halt-report resume line (MUST, #3273 / AC6):** Terminal dual-stop / hard-stop / conf-residual halt reports MUST end with residual class + conf (if any) + PR URL, example resume phrases (**pursue residual** | **follow-up hard-stop** | **same as conf-hold** | **continue dual-stopped PR**), and pointer to \u00a7 Operator follow-up after dual-stop / hard stop. Full template: [`references/core-phase-4.md`](references/core-phase-4.md).\n\n! Composes with minimal-subgraph repair guidance (#2439): keep repairs minimal **and** bounded by dual-stop -- minimal repair is not a license to thrash. Durable delivery/acceptance circuit-breaker: **#3143** `packages/core/src/delivery-attempt/` (`evaluatePreDispatch`, unit ledger). Docs: `docs/delivery-attempt.md`. Skill defaults remain behavioral; mechanical gate lives in core.\n\n### Operator follow-up after dual-stop / hard stop (#3273)\n\nOperator-initiated **one residual pass** after dual-stop / hard stop / conf-hold \u2014 not automatic re-thrash. Depth (steps, anti-thrash, conf-floor this-PR-only): [`references/core-phase-4.md`](references/core-phase-4.md) same section title. Thin pointer: dual-invoke `pr:merge-ready` / `pr:watch`; spawn **one** residual worker or review-cycle owner; document authorized conf floor for this PR only as human-merge/override trail (\u2297 silent policy rewrite; `pr:merge-ready` still uses policy floor); re-stop without new consent. \u2297 Unlimited auto-retry. \u2297 Parent self-implement (#2843). Portable consumer + maintainer.\n\n## Runtime Capability Detection (summary)\n\n! Before selecting a launch method, probe the environment. Full probe text: [`references/core-phase-3.md`](references/core-phase-3.md).\n\n1. ! **Probe for `start_agent` tool** \u2014 Warp orchestrated.\n2. ! **Probe for Warp environment** \u2014 `WARP_*` without `start_agent` \u2192 warp-manual.\n3. ! **Probe for the Cursor `Task` tool** \u2014 Tier 1; descriptor `cursor-composer` / `cursor-cloud-agent` (#1877). Require Cursor signals (`CURSOR_*` or Cursor-only Task surface) \u2014 not bare `Task` alone.\n4. ! **Probe for Claude Code** \u2014 Tier 1; descriptor `claude-code` (#3134). Claude-unique signals only: `Agent` (or `CreateAgent` / `SubagentStart`) with background / `run_in_background`, and/or `DEFT_PROBE_CLAUDE_CODE` / `DEFT_AGENT_RUNTIME=claude-code` / `CLAUDECODE`. \u2297 Misclassify as `cursor-composer` via bare `Task`.\n5. ! **Probe for the OpenClaw `sessions_spawn` tool** \u2014 Tier 1; descriptor `openclaw` (#2875). Do NOT misclassify as `grok-build` or `generic-terminal`.\n6. ! **Probe for `spawn_subagent` tool** \u2014 descriptor `grok-build`.\n7. ! **Select launch path automatically** \u2014 load the matching host adapter (route table). No static A/B/C menu.\n8. ! **Return a stable platform descriptor** for Phase 4/6: `warp-orchestrated`, `warp-manual`, `cursor-composer`, `cursor-cloud-agent`, `claude-code`, `openclaw`, `grok-build`, or `generic-terminal`.\n9. ? **Cloud escape hatch** \u2014 `oz agent run-cloud` only on explicit user request (host-generic).\n\n\u2297 Present static launch options instead of detecting capabilities at runtime.\n\u2297 Offer Warp-specific launch paths when not inside Warp.\n\u2297 Classify Claude Code as `cursor-composer` / `generic-terminal` when Claude-unique signals are present (#3134).\n\n## Retained addressable sub-agents (#3158)\n\nNamed mode **beside** dispatch-and-collect. Canon: [`../../swarm/swarm.md`](../../swarm/swarm.md) `## Retained addressable sub-agents (#3158)`.\n\n| Mode | When | Mid-scope gate |\n|------|------|----------------|\n| **retained-child** (message-later / steer-mid-flight) | Host keeps a live, addressable child (`agent_id` / session name); parent can re-message or steer mid-flight | Single dispatch MAY pause for approval and continue the **same** child |\n| **dispatch-and-collect** (one-shot) | Host has no continue/resume; worker terminal on tool-loop exit | **Split-dispatch** mandatory (#954): Scope A \u2192 report \u2192 approve \u2192 Scope B |\n\n! After platform detect, read the loaded host adapter's **Retained / continue-by-id** note. Prefer continue-by-agent-id / resume-by-name / steerable mid-flight **only when that adapter documents support**.\n! When the host cannot retain: keep one-shot envelopes and split-dispatch mid-scope gates. Do not claim message-later semantics the platform cannot deliver.\n! Stance (#3164): retention is **orchestration only** \u2014 not mid-run constitution self-edit (managed AGENTS, pinned skills, policy).\n! Topology (#3155): retained children MUST obey nuclear-family A2A bounds (parent/sibling/child only).\n\u2297 Force a second full dispatch on a retain-capable host solely because a mid-scope gate exists \u2014 re-message the live child instead.\n\u2297 Invent retain / resume on hosts whose adapter marks one-shot only.\n\n## Phase overview\n\n| Phase | Goal | Depth |\n|-------|------|-------|\n| 0 Allocate | Queue cohort, readiness, approval | `core-phase-0.md` |\n| 1 Select | Confirm candidates, file-overlap | `core-phase-1-2.md` |\n| 2 Setup | Worktrees + prompt files | `core-phase-1-2.md` |\n| 3 Launch | Detect, preflight, **one** host spawn | `core-phase-3.md` + **one** `host-*.md` |\n| 4 Monitor | Heartbeats, takeover, no duplicate agents | `core-phase-4.md` (+ host notes) |\n| 5 Review | Greptile clean, gates, **next-phase tools** | `core-phase-5-6.md` |\n| 6 Close | Merge cascade, cohort sweep, cleanup | `core-phase-5-6.md` |\n\n! Follow phases in order. Depth files hold the operative MUST rules; this page is the dispatch card.\n\n## Effort estimate on dispatch (#1581)\n\n! When plan items carry optional `effort` (S/M/L/XL with time anchors in `vbrief/vbrief.md`), use them for sizing: S/M single-agent, L may need a dedicated agent, XL blocks dispatch until broken into S/M/L. Activate fails closed on XL. Depth: [`references/core-phase-0.md`](references/core-phase-0.md) Steps 2\u20133.\n! Plan-item effort is **post-planning** (confirms/corrects provisional intake estimates). It is **not** session-start ritual input; ceremony dial (#3214) starts rapid and escalates \u2014 do not block cold-start ritual on missing plan-item `effort`. Headless: no operator confirmation for size or stage transitions.\n\n## Critical anti-patterns (dispatch card)\n\n- \u2297 Load all host adapters \u201cjust in case\u201d (#2928)\n- \u2297 Parallel OpenClaw `sessions_spawn` on shared repo root without worktrees (#2929)\n- \u2297 Prose-only phase handoff after cohort complete (\u201cI will spawn\u2026\u201d) (#2934)\n- \u2297 Multi-sentence progress-only first response after leaf announce with zero tools / yield (#2943)\n- \u2297 N>2 near-identical assistant sentences with no tool_use / yield (FC14 / #3131 hard-stop)\n- \u2297 Treat thin DONE (no PR URL / merge evidence) as success (#2943)\n- \u2297 Rely on soft skill prose alone as the sole parent-hang mitigation (#3131)\n- \u2297 Second+ user-visible consolidate for the same child runId without new evidence (#3092)\n- \u2297 Assign overlapping files to multiple agents\n- \u2297 Dispatch or activate work that still has `plan.items[].effort: \"XL\"` without breakdown (#1581)\n- \u2297 Merge before Greptile exit condition (score > 3, no P0/P1)\n- \u2297 Skip Phase 0 approval before Phase 1\n- \u2297 Misclassify OpenClaw `sessions_spawn` as `grok-build` or `generic-terminal` (#2875)\n- \u2297 Misclassify Claude Code as `cursor-composer` / `generic-terminal` (#3134)\n- \u2297 Run multi-iteration repair/monitor loops without a failure stop or with silent continuation after the envelope is exhausted (#2442)\n- \u2297 Dual-stop/hard-stop halt without #3273 resume line, or unlimited residual auto-retry without new operator consent (#3273)\n- \u2297 Force a second full dispatch on a retain-capable host solely for a mid-scope gate, or invent retain on one-shot hosts (#3158)\n- \u2297 Use retained-child messaging for mid-run constitution self-edit (#3158 / #3164)\n\nFull anti-pattern list: [`references/core-ops.md`](references/core-ops.md).",
294
304
  "frontmatter_extra": null
295
305
  },
296
306
  {