@deftai/directive-content 0.93.0 → 0.94.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.
@@ -247,7 +247,7 @@
247
247
  ],
248
248
  "path": "skills/deft-directive-review-cycle/SKILL.md",
249
249
  "version": "0.1",
250
- "body": "# Deft Directive Review Cycle\n\nStructured workflow for responding to bot reviewer (Greptile) findings on a PR.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=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 — 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⊗ 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- ⊗ 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 — 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 — bare `task pr:watch` is not the consumer form.\n- ⊗ 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- ⊗ Freestyle main-session `gh pr view` / `sleep` poll + ad-hoc cron when `sessions_spawn` is available — 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`) — 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 — 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⊗ Use `commits/<sha>/statuses` to check for Greptile — that endpoint will always be empty.\n\n~ See `tools/greptile.md` for recommended dashboard and per-repo settings.\n\n## Phase 1 — 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 ≥75%)\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 — 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⊗ Commit or push Phase 1 audit fixes independently before gathering Phase 2 findings.\n\n## Phase 2 — Review/Fix Loop\n\n### Step 1: Fetch ALL bot comments\n\n! Retrieve findings using BOTH methods — each catches different comment categories:\n\n```\ngh pr view <number> --comments\n```\n\n! Use `do_not_summarize_output: true` — 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⊗ Report \"all comments resolved\" without verifying both sources.\n⊗ 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⊗ Declare the exit condition met based on a single fetch that returned no bot review — 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 — 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 — not silent redesign mid-babysit (PR #2871 / #2869 → #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 — 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- ⊗ Add related-issue `x-*/github-issue` refs to a brief that still needs `issue:emit` for its primary origin — emit will SKIP as already tracked.\n\n⊗ Expand active story scope past xBRIEF AC mid-babysit without follow-up or consented amend (#2881).\n⊗ Treat confidence-only holds as authorization to invent new subsystems in-tree.\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 — 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- ⊗ 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- ⊗ 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 — catching coverage gaps before CI does.\n\n⊗ 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⊗ Push any additional commits — including unrelated fixes, doc updates, or lessons — 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** — 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** — 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** — 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⊗ Treat bare `task pr:watch` / `task review-monitor:register` as the only prescribed consumer form — 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⊗ Pass go-task's bare `--` separator into `deft`/`directive` CLI forms (e.g. `deft pr:watch -- --help`) — 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 → no `task deft:…`). 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 — 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`, `spawn_subagent`, `start_agent`) — 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 — 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 > 3 + 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⊗ Fake a successful `pr:watch` or `review-monitor:*` gate when every dual-invoke probe failed.\n⊗ Block Approach 1 / parent yield on missing `review-monitor:*` after the dual-invoke probe — use the gh lease claim or parent-owned gh-only poll instead (#2878).\n⊗ Invent ad-hoc `sleep` / main-session poll / OpenClaw cron loops outside Approach 1–3 when the skill already names this fallback (#2878 / statusreport#153 recurrence).\n⊗ Skip Step 6 fail-closed fields because deterministic tasks are missing — 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 > 3, 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 — 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 — merge-ready is `pr:watch` CLEAN / the merge path only.\n\n⊗ Treat `pr:watch` TIMEOUT or long PENDING with `clean_gate_holdout=ci_failures` as \"Greptile still reviewing\" — 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⊗ Use `--skip-ci` / merge-with-pending because CI is capacity-stalled — the failover path is the unblock; skip-ci is an incident-only release escape hatch (#2652), not a runner-capacity remedy.\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`** — 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 — `INCOMPLETE_BUT_RATED` names the trap so the agent does not mistake a rating for a verdict.\n\n⊗ 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⊗ 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### 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`). This generalizes the Approach-1 sub-agent monitor rule to implementation and fix workers as well — foreground dispatch is reserved for short tasks. The parent receives completion via `DONE` / `BLOCKED` / `FAILED` per `templates/agent-prompt-preamble.md` §11.\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 — 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 — 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\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, and per #2876 for OpenClaw `sessions_spawn`). Probe the environment (tool set + env vars) to obtain the stable platform descriptor (`grok-build`, `warp-orchestrated`, `warp-manual`, `cursor-composer`, `cursor-cloud-agent`, `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, 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)** → 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`, or OpenClaw `sessions_spawn`)\n- **Tier 2 (no sub-agent primitive, but scheduler/timer/auto-reinvocation)** → Approach 2 (yield-between-polls) — includes OpenClaw `cron` / host scheduler **only when** `sessions_spawn` is unavailable (#2876)\n- **Tier 3 (interactive session, nothing else)** → 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) — 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 `openclaw` (`sessions_spawn` present), treat as **Tier 1 with the backgrounded `sessions_spawn` poller path** (#2876) — 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 — 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|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 — 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 — parent may yield after that claim succeeds — **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⊗ Require successful review-monitor register/verify on a consumer where dual-invoke probes failed — 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 — 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**Approach 1 (preferred -- sub-agent orchestration available per platform descriptor):**\n\n! **Background dispatch (#1880 / #2876):** Spawn the review-monitor sub-agent via the matching primitive IN THE BACKGROUND (Cursor: Task `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 — never block the parent OpenClaw/Cursor/Grok session for >~3 min of monitor ownership.\n\n! **Heartbeat contract for Cursor pollers (#1877 / #1166 / #2876):** OpenClaw sessions_spawn pollers share this contract. A Cursor `Task` 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 — 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), **or OpenClaw `sessions_spawn` (`openclaw`, #2876)** with a prompt that instructs it to poll for Greptile completion. For `spawn_subagent`, Cursor `Task`, 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 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 > 3, 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⊗ Use OpenClaw `cron` alone as Approach 1 when `sessions_spawn` is available — cron is Approach 2 scheduler fallback only (#2876).\n\n### Empty announce ≠ 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 ≠ done) until ground truth shows a terminal merge/close outcome **or** an explicit structured `BLOCKED` / `FAILED` handback.\n3. ⊗ Treat empty / unknown settle as `DONE`, `CLEAN`, merge-ready, or batch-complete.\n4. ⊗ 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) — 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### 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`, `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. ⊗ Spawn a second monitor while a prior owner is **running**.\n4. ⊗ 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 — 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 — do not parallel-fix.\n7. ⊗ 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⊗ Empty final assistant message from a review-monitor.\n⊗ 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⚠️ **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⊗ 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⊗ 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⊗ 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 > 3, 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` — 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) — 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) — 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 — do NOT rely on grepping truncated link text.\n\n⊗ 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 — 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 — 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** — 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** — 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** — 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 → 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 > 3** — the parsed `Confidence Score: X/5` is strictly greater than 3 (i.e. 4/5 or 5/5). A `confidence == 3`, an unparsed confidence, or an absent confidence is `unknown`.\n5. ! **No P0/P1 findings** — 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 — 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 — not the start of another loop. Go back to Step 2 one more time, re-evaluate this all-of, then stop.\n\n⊗ Exit the loop on a confidence number alone while the check run is non-terminal (`queued` / `in_progress` / `cancelled` / `timed_out` / `stale` / `action_required`) — a confidence score is NOT a verdict without a terminal check-run AND a HEAD-matching completion marker (#1259).\n⊗ Exit the loop against a reviewed SHA that lags the current HEAD — 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## 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 — a fresh `gh pr view <number> --comments`, a fresh `gh api repos/<owner>/<repo>/commits/<HEAD>/check-runs`, and a fresh HEAD-SHA read — 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⊗ 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 — merging on cached review state is forbidden (#1259).\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⊗ 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⊗ 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` — formally approve the PR (shows green \"Approved\" status)\n- `REQUEST_CHANGES` — block the PR with requested changes\n- `COMMENT` — review feedback without approving or blocking\n\n⊗ Use `add_issue_comment` for review notes — 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** — structured/programmatic operations (querying issues, creating PRs, bulk operations, filtering data)\n- **GitHub CLI (`gh`)** — 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 — 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## Anti-Patterns\n\n- ⊗ Ignore [`coding/review.md`](../../coding/review.md) while running this adapter — universal batch/severity/exit/post-merge rules live there\n- ⊗ Route PR shepherding to Cursor global `babysit` on Deft-managed repos when `.deft/core/` is installed -- use this review-cycle skill instead (#2261)\n- ⊗ 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- ⊗ Treat OpenClaw `cron` alone as Approach 1 — cron/timer is Approach 2 only if spawn is unavailable (#2876)\n- ⊗ Expand active story scope past xBRIEF AC mid-babysit without follow-up issue or consented brief amend (#2881)\n- ⊗ Treat confidence-only holds (0 P0/P1) as a mandate for unbounded redesign (#2881)\n- ⊗ Invent freestyle sleep/poll loops when dual-invoke probes fail for `pr:watch` — use the official gh-only fallback and fail-loud missing-task (#2878 / #2893)\n- ⊗ Treat bare `task pr:watch` as the only consumer gate form — probe `deft` then `task deft:` first (#2893)\n- ⊗ 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- ⊗ Push individual fix commits per finding\n- ⊗ Start fixing before analyzing ALL findings\n- ⊗ Rely on the bot to catch syntax errors in structured data files\n- ⊗ Re-trigger a bot review before the previous one has updated\n- ⊗ 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- ⊗ Use `add_issue_comment` for formal review submission\n- ⊗ Commit or push Phase 1 audit fixes independently — always batch with Phase 2 fixes\n- ⊗ Proceed to Phase 2 while any Phase 1 prerequisite is unmet\n- ⊗ Rely solely on `pulls/{number}/reviews` to detect whether Greptile has reviewed the latest commit — Greptile may update via an edited issue comment instead of a new review object\n- ⊗ Push additional commits while Greptile is reviewing the current head — each push re-triggers Greptile and resets the review clock\n- ⊗ 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- ⊗ 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- ⊗ Stop and ask the user whether to continue after pushing -- the review/fix loop MUST run autonomously to the exit condition\n- ⊗ Push fix commits without scanning changed lines for untested code paths — always check test coverage before pushing\n- ⊗ Push a fix commit that addresses fewer findings than the current Greptile review surfaces — if Greptile flags 3 issues, all 3 must be fixed in one commit before pushing\n- ⊗ Push after fixing a P1 without first checking whether the same Greptile review contains additional P0 or P1 findings\n- ⊗ Assume squash merge auto-closed referenced issues — always verify with `gh issue view` after merge (#167)\n- ⊗ 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- ⊗ Skip the second review source (MCP or `gh api` fallback) without probing for MCP capability and documenting the fallback used\n- ⊗ 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- ⊗ 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- ⊗ Activate Approach 3 (blocking `Start-Sleep` loop) without first warning the user that it will lock the conversation pane and receiving confirmation\n- ⊗ 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- ⊗ 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- ⊗ Treat empty/unknown review-monitor settle as DONE/CLEAN/merge-ready without same-turn ground truth (#3044 / FC04 residual)\n- ⊗ Spawn a second review-monitor while prior owner is running or last settle was empty/unknown without terminal ground truth (#3044)\n- ⊗ Accept empty review-monitor final message missing STATUS/HEAD/CHECKS/MERGE handback (#3044)\n",
250
+ "body": "# Deft Directive Review Cycle\n\nStructured workflow for responding to bot reviewer (Greptile) findings on a PR.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=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 — 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⊗ 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- ⊗ 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 — 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 — bare `task pr:watch` is not the consumer form.\n- ⊗ 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- ⊗ Freestyle main-session `gh pr view` / `sleep` poll + ad-hoc cron when `sessions_spawn` is available — 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`) — 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 — 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⊗ Use `commits/<sha>/statuses` to check for Greptile — that endpoint will always be empty.\n\n~ See `tools/greptile.md` for recommended dashboard and per-repo settings.\n\n## Phase 1 — 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 ≥75%)\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 — 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⊗ Commit or push Phase 1 audit fixes independently before gathering Phase 2 findings.\n\n## Phase 2 — Review/Fix Loop\n\n### Step 1: Fetch ALL bot comments\n\n! Retrieve findings using BOTH methods — each catches different comment categories:\n\n```\ngh pr view <number> --comments\n```\n\n! Use `do_not_summarize_output: true` — 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⊗ Report \"all comments resolved\" without verifying both sources.\n⊗ 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⊗ Declare the exit condition met based on a single fetch that returned no bot review — 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 — 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 — not silent redesign mid-babysit (PR #2871 / #2869 → #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 — 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- ⊗ Add related-issue `x-*/github-issue` refs to a brief that still needs `issue:emit` for its primary origin — emit will SKIP as already tracked.\n\n⊗ Expand active story scope past xBRIEF AC mid-babysit without follow-up or consented amend (#2881).\n⊗ Treat confidence-only holds as authorization to invent new subsystems in-tree.\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 — 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- ⊗ 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- ⊗ 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 — catching coverage gaps before CI does.\n\n⊗ 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⊗ Push any additional commits — including unrelated fixes, doc updates, or lessons — 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** — 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** — 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** — 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⊗ Treat bare `task pr:watch` / `task review-monitor:register` as the only prescribed consumer form — 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⊗ Pass go-task's bare `--` separator into `deft`/`directive` CLI forms (e.g. `deft pr:watch -- --help`) — 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 → no `task deft:…`). 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 — 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`, `spawn_subagent`, `start_agent`) — 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 — 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⊗ Fake a successful `pr:watch` or `review-monitor:*` gate when every dual-invoke probe failed.\n⊗ Block Approach 1 / parent yield on missing `review-monitor:*` after the dual-invoke probe — use the gh lease claim or parent-owned gh-only poll instead (#2878).\n⊗ Invent ad-hoc `sleep` / main-session poll / OpenClaw cron loops outside Approach 1–3 when the skill already names this fallback (#2878 / statusreport#153 recurrence).\n⊗ Skip Step 6 fail-closed fields because deterministic tasks are missing — 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 — 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 — merge-ready is `pr:watch` CLEAN / the merge path only.\n\n⊗ Treat `pr:watch` TIMEOUT or long PENDING with `clean_gate_holdout=ci_failures` as \"Greptile still reviewing\" — 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⊗ Use `--skip-ci` / merge-with-pending because CI is capacity-stalled — the failover path is the unblock; skip-ci is an incident-only release escape hatch (#2652), not a runner-capacity remedy.\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`** — 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 — `INCOMPLETE_BUT_RATED` names the trap so the agent does not mistake a rating for a verdict.\n\n⊗ 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⊗ 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 — all consumers / handoffs / preamble §11 / swarm finish messages):** **only**\n - `done` — 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>` — verifiable sticky lease, registered monitor id, or documented `parent-retained` ownership\n - `skipped:<reason>` — intentional skip (e.g. no-pr, operator cancel)\n - `n/a` — 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:…` 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 — 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⊗ 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⊗ Treat check-run **SUCCESS alone** as CLEAN or merge-ready while dual-source P0/P1 remain open.\n⊗ 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⊗ Solve Owner Continuity via host cron-as-Approach-1 or always-block-parent-until-merge — 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 → **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`). This generalizes the Approach-1 sub-agent monitor rule to implementation and fix workers as well — foreground dispatch is reserved for short tasks. The parent receives completion via `DONE` / `BLOCKED` / `FAILED` per `templates/agent-prompt-preamble.md` §11.\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 — 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 — 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\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, and per #2876 for OpenClaw `sessions_spawn`). Probe the environment (tool set + env vars) to obtain the stable platform descriptor (`grok-build`, `warp-orchestrated`, `warp-manual`, `cursor-composer`, `cursor-cloud-agent`, `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, 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)** → 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`, or OpenClaw `sessions_spawn`)\n- **Tier 2 (no sub-agent primitive, but scheduler/timer/auto-reinvocation)** → Approach 2 (yield-between-polls) — includes OpenClaw `cron` / host scheduler **only when** `sessions_spawn` is unavailable (#2876)\n- **Tier 3 (interactive session, nothing else)** → 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) — 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 `openclaw` (`sessions_spawn` present), treat as **Tier 1 with the backgrounded `sessions_spawn` poller path** (#2876) — 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 — 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|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 — 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 — parent may yield after that claim succeeds — **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⊗ Require successful review-monitor register/verify on a consumer where dual-invoke probes failed — 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 — 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**Approach 1 (preferred -- sub-agent orchestration available per platform descriptor):**\n\n! **Background dispatch (#1880 / #2876):** Spawn the review-monitor sub-agent via the matching primitive IN THE BACKGROUND (Cursor: Task `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 — never block the parent OpenClaw/Cursor/Grok session for >~3 min of monitor ownership.\n\n! **Heartbeat contract for Cursor pollers (#1877 / #1166 / #2876):** OpenClaw sessions_spawn pollers share this contract. A Cursor `Task` 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 — 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), **or OpenClaw `sessions_spawn` (`openclaw`, #2876)** with a prompt that instructs it to poll for Greptile completion. For `spawn_subagent`, Cursor `Task`, 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 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⊗ Use OpenClaw `cron` alone as Approach 1 when `sessions_spawn` is available — cron is Approach 2 scheduler fallback only (#2876).\n\n### Empty announce ≠ 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 ≠ done) until ground truth shows a terminal merge/close outcome **or** an explicit structured `BLOCKED` / `FAILED` handback.\n3. ⊗ Treat empty / unknown settle as `DONE`, `CLEAN`, merge-ready, or batch-complete.\n4. ⊗ 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) — 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 — use Empty announce ≠ 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` §11.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`, `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. ⊗ Spawn a second monitor while a prior owner is **running**.\n4. ⊗ 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 — 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 — do not parallel-fix.\n7. ⊗ 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⊗ Empty final assistant message from a review-monitor.\n⊗ 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⚠️ **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⊗ 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⊗ 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⊗ 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` — 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) — 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) — 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 — do NOT rely on grepping truncated link text.\n\n⊗ 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 — 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 — 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** — 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** — 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** — 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 → 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)** — 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 → **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** — 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 — 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 — not the start of another loop. Go back to Step 2 one more time, re-evaluate this all-of, then stop.\n\n⊗ Exit the loop on a confidence number alone while the check run is non-terminal (`queued` / `in_progress` / `cancelled` / `timed_out` / `stale` / `action_required`) — a confidence score is NOT a verdict without a terminal check-run AND a HEAD-matching completion marker (#1259).\n⊗ Exit the loop against a reviewed SHA that lags the current HEAD — 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## 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 — a fresh `gh pr view <number> --comments`, a fresh `gh api repos/<owner>/<repo>/commits/<HEAD>/check-runs`, and a fresh HEAD-SHA read — 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⊗ 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 — merging on cached review state is forbidden (#1259).\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⊗ 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⊗ 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` — formally approve the PR (shows green \"Approved\" status)\n- `REQUEST_CHANGES` — block the PR with requested changes\n- `COMMENT` — review feedback without approving or blocking\n\n⊗ Use `add_issue_comment` for review notes — 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** — structured/programmatic operations (querying issues, creating PRs, bulk operations, filtering data)\n- **GitHub CLI (`gh`)** — 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 — 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## Anti-Patterns\n\n- ⊗ End owning turn with 0 children, no sticky lease, and no finish after drive-to-merge / babysit / shepherd claim — silent hold (#3090)\n- ⊗ Emit freeform `review_cycle: started` / `pending` / `initiated` or L4 `status: pass` without `done` or verifiable `in_progress:<pr>#…` lease/parent-retained (#3090)\n- ⊗ Treat check-run SUCCESS alone as CLEAN / merge-ready while dual-source P0/P1 remain (#3090)\n- ⊗ Ignore [`coding/review.md`](../../coding/review.md) while running this adapter — universal batch/severity/exit/post-merge rules live there\n- ⊗ Route PR shepherding to Cursor global `babysit` on Deft-managed repos when `.deft/core/` is installed -- use this review-cycle skill instead (#2261)\n- ⊗ 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- ⊗ Treat OpenClaw `cron` alone as Approach 1 — cron/timer is Approach 2 only if spawn is unavailable (#2876)\n- ⊗ Expand active story scope past xBRIEF AC mid-babysit without follow-up issue or consented brief amend (#2881)\n- ⊗ Treat confidence-only holds (0 P0/P1) as a mandate for unbounded redesign (#2881)\n- ⊗ Invent freestyle sleep/poll loops when dual-invoke probes fail for `pr:watch` — use the official gh-only fallback and fail-loud missing-task (#2878 / #2893)\n- ⊗ Treat bare `task pr:watch` as the only consumer gate form — probe `deft` then `task deft:` first (#2893)\n- ⊗ 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- ⊗ Push individual fix commits per finding\n- ⊗ Start fixing before analyzing ALL findings\n- ⊗ Rely on the bot to catch syntax errors in structured data files\n- ⊗ Re-trigger a bot review before the previous one has updated\n- ⊗ 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- ⊗ Use `add_issue_comment` for formal review submission\n- ⊗ Commit or push Phase 1 audit fixes independently — always batch with Phase 2 fixes\n- ⊗ Proceed to Phase 2 while any Phase 1 prerequisite is unmet\n- ⊗ Rely solely on `pulls/{number}/reviews` to detect whether Greptile has reviewed the latest commit — Greptile may update via an edited issue comment instead of a new review object\n- ⊗ Push additional commits while Greptile is reviewing the current head — each push re-triggers Greptile and resets the review clock\n- ⊗ 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- ⊗ 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- ⊗ Stop and ask the user whether to continue after pushing -- the review/fix loop MUST run autonomously to the exit condition\n- ⊗ Push fix commits without scanning changed lines for untested code paths — always check test coverage before pushing\n- ⊗ Push a fix commit that addresses fewer findings than the current Greptile review surfaces — if Greptile flags 3 issues, all 3 must be fixed in one commit before pushing\n- ⊗ Push after fixing a P1 without first checking whether the same Greptile review contains additional P0 or P1 findings\n- ⊗ Assume squash merge auto-closed referenced issues — always verify with `gh issue view` after merge (#167)\n- ⊗ 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- ⊗ Skip the second review source (MCP or `gh api` fallback) without probing for MCP capability and documenting the fallback used\n- ⊗ 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- ⊗ 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- ⊗ Activate Approach 3 (blocking `Start-Sleep` loop) without first warning the user that it will lock the conversation pane and receiving confirmation\n- ⊗ 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- ⊗ 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- ⊗ Treat empty/unknown review-monitor settle as DONE/CLEAN/merge-ready without same-turn ground truth (#3044 / FC04 residual)\n- ⊗ Spawn a second review-monitor while prior owner is running or last settle was empty/unknown without terminal ground truth (#3044)\n- ⊗ Accept empty review-monitor final message missing STATUS/HEAD/CHECKS/MERGE handback (#3044)\n",
251
251
  "frontmatter_extra": null
252
252
  },
253
253
  {
@@ -263,7 +263,7 @@
263
263
  ],
264
264
  "path": "skills/deft-directive-setup/SKILL.md",
265
265
  "version": "0.1",
266
- "body": "# Deft Directive Setup\n\nAgent-driven alternative to `.deft/core/run bootstrap && .deft/core/run project && .deft/core/run spec`.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.\n\n## When to Use\n\n- User says \"set up deft\", \"configure deft\", or \"bootstrap my project\"\n- User asks to create USER.md, PROJECT-DEFINITION.xbrief.json, or a specification\n- User clones a deft-enabled repo for the first time with no config\n- User says \"revisit experimental rules\", \"toggle experimental meta\", \"enable SOUL\", \"disable morals\", or wants to change Experimental Rules after bootstrap (#46)\n\n## Opt-out flag (`.no-deft-directive`) (#2926)\n\n! Before Pre-Cutover Detection Guard, Phase 1, or any install/setup step, check the **project root** for `.no-deft-directive` (exact lowercase name; presence = flag; empty or short `#` comment OK).\n\n| Condition | Action |\n|-----------|--------|\n| Flag **present** | Stop. Tell the human: \"Directive disabled via `.no-deft-directive`\". ⊗ Offer install, session ritual, or setup interview. |\n| Flag **absent**, no Directive deposit (`.deft/core`) | ? Ask whether to use Directive. On **no** → create root `.no-deft-directive` (optional one-line rationale) and stop. On **yes** → continue setup and ⊗ create the flag. |\n| Operator says **stop using DD** | Create `.no-deft-directive`. ⊗ Auto-delete `.deft/` (explicit cleanup only). |\n| Operator says **start using DD** | Remove `.no-deft-directive` and ensure install (`directive init` / deposit). |\n\n! Flag is **root-only** (workspace root opened). Nested monorepo package roots are out of scope for v1.\n! Flag **wins locally** over trusted-org / product-signal force-on (v1).\n! Flag + deposit = inconsistent: warn loudly; doctor diagnoses; do not silently refresh. See `content/docs/no-deft-directive.md`.\n\n## Consumer-first default (#1813)\n\n! Assume the operator is **using Deft in their project** (consumer path). Proceed directly to the Pre-Cutover Detection Guard and Phase 1 — do NOT open with a contributor-vs-consumer fork.\n\n~ The overwhelming majority of setup sessions are consumer installs; contributor onboarding is a separate, opt-in path (see below).\n\n## Contributor / framework-maintainer path (secondary)\n\n? Only enter this branch when the user **explicitly** says they are working on Deft itself (framework source checkout, `deftai/directive` clone, or maintainer tooling).\n\nWhen that happens:\n\n1. ! Tell the user: \"Contributor setup lives in [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) and this repo's root [`AGENTS.md`](../../../AGENTS.md). Use the maintainer installer: `deft-install --yes --upgrade --maintainer --repo-root . --json`.\"\n2. ⊗ Continue the consumer USER.md / PROJECT-DEFINITION interview — the maintainer path does not use the first-session consumer flow.\n3. **Stop here** unless the user explicitly asks to continue with consumer setup anyway.\n\n## Pre-Cutover Detection Guard\n\n! Before proceeding with any setup phase, detect whether the project uses the pre-v0.20 document model and redirect to migration if so.\n\n### Detection Criteria\n\nA project is **pre-cutover** if ANY of the following are true. When in doubt, run `task verify:pre-cutover` (the deterministic helper).\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 (same one-release-cycle grace window).\n3. `xbrief/specification.xbrief.json` exists but the lifecycle folders (`xbrief/proposed/`, `xbrief/pending/`, `xbrief/active/`, `xbrief/completed/`, `xbrief/cancelled/`) do NOT exist\n\n### Action on Detection\n\n! If pre-cutover state is detected, **stop immediately** and display an actionable message pointing at the frozen-release migration path (#2068):\n\n> \"This project uses the pre-v0.20 document model. Current npm releases no longer ship in-product `task migrate:vbrief`. Follow UPGRADING.md § Frozen pre-v0.20 document-model migration: pin framework v0.59.0 (frozen Go installer or git tag), install Python 3.11+ and uv, run `task migrate:vbrief` once from that payload, then upgrade to current npm.\"\n\n! Include specific details about what was detected:\n\n- Missing lifecycle folders: \"Create lifecycle folders via the frozen-release migrator on v0.59.0, or manually add `xbrief/{proposed,pending,active,completed,cancelled}/` after migrating narratives\"\n- `SPECIFICATION.md` with real content: \"SPECIFICATION.md contains non-redirect content — migrate on pinned v0.59.0 before upgrading to current npm\"\n- `PROJECT.md` with real content: \"PROJECT.md contains non-redirect content — migrate on pinned v0.59.0 before upgrading to current npm\"\n- Missing `PROJECT-DEFINITION.xbrief.json`: \"Run `task project:render` after document-model migration completes\"\n\n### Preflight (optional diagnostic)\n\n~ Run `task migrate:preflight` to confirm pre-cutover state and print the frozen-release guidance. It does **not** run migration.\n\n⊗ Offer to run `task migrate:vbrief` from the current npm deposit — the migrator is not bundled on current releases (#2068).\n⊗ Proceed with setup phases when pre-cutover artifacts are detected — always redirect to the frozen migration path first.\n⊗ Silently ignore pre-cutover artifacts — the user must be informed with an actionable command to fix the state.\n\n### Greenfield Projects (No Migration Needed)\n\n! For new projects (no existing `SPECIFICATION.md`, `PROJECT.md`, or `xbrief/specification.xbrief.json`), the guard passes silently and setup proceeds normally.\n\n! Greenfield setup creates the full xBRIEF-centric structure from scratch:\n\n1. `./xbrief/` directory with all 5 lifecycle subdirectories: `proposed/`, `pending/`, `active/`, `completed/`, `cancelled/`\n2. `./xbrief/PROJECT-DEFINITION.xbrief.json` generated from Phase 2 interview results\n3. First scope xBRIEF created in `proposed/` or `pending/` depending on Phase 3 interview outcome\n\n~ This is already handled by Phase 2 Output Path (creates `./xbrief/` and lifecycle subfolders) and Phase 3 Output (creates scope xBRIEFs in lifecycle folders). The guard ensures migrating projects are redirected before reaching these phases.\n\n### Migration safety flags (frozen v0.59.0 release only)\n\nWhen guiding an operator through migration on the pinned release, mention the migrator safety affordances (#497, #506 D7):\n\n- **`task migrate:vbrief -- --dry-run` (preview)** on v0.59.0\n- **Dirty-tree guard** — migrator refuses when the working tree is dirty unless `--force`\n- **`task migrate:vbrief -- --rollback`** on v0.59.0 to restore `.premigrate.*` backups\n\n⊗ Offer in-product migration from a current npm deposit — use the frozen path (#2068).\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (Phase 1 depth question, Phase 2 project type / deployment / language / strategy / branching gates, Phase 3 onboarding question, end-of-phase transition prompts, post-interview confirmation 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 (re-asks original question, says `resume`/`continue`, or re-issues prior selection). Implicit resumption is forbidden. Fallback chat replies MUST map only to the displayed number or exact displayed option text; do not infer from alphabetic host affordances.\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- ! Create parent directories as needed when writing USER.md\n- ~ `$DEFT_PROJECT_PATH` overrides the default project config path (`./xbrief/PROJECT-DEFINITION.xbrief.json`) if set\n\n## Agent Behavior\n\n**Flow:**\n- ! Start asking immediately — everything you need is in THIS file\n- ⊗ Explore the codebase, read framework files, or gather context before asking\n- ? Read `deft/main.md` or language files LATER when generating output\n\n**Interaction:**\n- ~ Use structured question tools only when their visible option labels preserve the canonical numbers (for example, `1. Yes`) and their return value is the numeric selection or exact displayed option text.\n- ! Fall back to the numbered chat menu when the host UI may replace numbers with alphabetic affordances, unlabeled buttons, or any other non-canonical choice labels.\n- ⊗ Infer deterministic answers from host-added letters or shortcuts unless those letters were actually displayed in the canonical menu labels.\n\n**Defaults:**\n- ! Communicate that deft ships with best-in-class standards for 20+ languages\n- ! Frame setup as \"tell me your overrides\" — not \"configure everything\"\n- ~ \"Deft has solid opinions on how code should be written and tested — I just need a few things about you and your project.\"\n\n**Adapt to Technical Level:**\n- ! First question gauges whether user is technical or non-technical\n- ! Technical user: ask about languages, strategy, coverage directly — they'll have opinions\n- ! Non-technical user: skip jargon, use sensible defaults, ask about what they're building not how\n- ⊗ Ask non-technical users about coverage thresholds, strategies, or framework choices\n\n## Available Languages\n\nC, C++, C#, Dart, Delphi, Elixir, Go, Java, JavaScript, Julia, Kotlin,\nOffice.js (Excel JavaScript API), Python, R, Rust, SQL, Swift, TypeScript,\nVBA (Excel macros), VHDL, Visual Basic (.NET), Zig, 6502-DASM\n\n- ? Read `deft/languages/{name}.md` when generating output — not before asking\n\n## Available Strategies\n\n~ When presenting strategies to the user, always use this numbered list format (not a plain table).\n~ Always include the chaining note below the list.\n! Always show the FULL strategy list at every chaining gate — never remove a strategy because it was previously run.\n~ If a strategy has been run already, indicate it with a note e.g. `(run 1x)` but keep it selectable.\n\n1. **interview** ★ (recommended) — Structured interview with sizing gate: Light or Full path\n2. **yolo** — Auto-pilot interview — Johnbot picks all recommended options\n3. **map** — Analyze existing codebase conventions before adding features\n4. **discuss** — Front-load decisions and alignment before planning\n5. **probe** — Adversarially stress-test the plan; surface assumptions, edge cases, and risks before spec\n6. **research** — Investigate the domain before planning\n7. **speckit** — Five-phase spec-driven workflow for large/complex projects\n\n> 💡 Strategies can be chained — after one completes, you'll be asked if you want to run another.\n\n---\n\n## Phase 1 — User Preferences (USER.md)\n\n**Goal:** Personal preferences file with two sections:\n- **Personal** — always wins over everything (name, custom rules)\n- **Defaults** — fallback values that PROJECT-DEFINITION.xbrief.json can override (strategy, coverage)\n\n- ~ Skip if USER.md exists at the platform-appropriate path (see Platform Detection) and user doesn't want to overwrite\n- ⊗ Scan filesystem beyond checking that one path\n\n### USER.md Freshness Detection\n\n! When an existing USER.md is found (returning user), check its `deft_version` field before skipping Phase 1:\n\n1. ! If `deft_version` is **missing**: the USER.md predates versioning -- treat as stale\n2. ! If `deft_version` is present but **differs from the current framework version** (0.20.0): check whether any expected fields are missing from the USER.md\n3. ! If fields are missing: query the user for each missing field individually -- do NOT re-run the full Phase 1 interview\n4. ! After completing any field queries (even if none were needed), write the current `deft_version` (0.20.0) to USER.md\n5. ~ If `deft_version` matches the current version and all expected fields are present: USER.md is fresh — do **not** re-run Phase 1. ! Still offer the **Returning-user re-entry** menu below so the operator can revisit Experimental Rules or continue to Phase 2 without a full re-interview (#46).\n\nExpected USER.md fields: **Name**, **Custom Rules**, **Default Strategy**, and optionally **Coverage** and **Experimental Rules**.\n\n⊗ Re-run the full Phase 1 interview when only individual fields are missing from a stale USER.md -- query missing fields individually instead.\n\n### Returning-user re-entry (#46)\n\n! When USER.md already exists (fresh or after individual missing-field fill), present a deterministic numbered menu before assuming Phase 1 is \"done and silent\":\n\n> \"USER.md is in place. What next?\"\n> 1. Continue to Phase 2 (project configuration) ★ (recommended when project config is still missing)\n> 2. **Revisit experimental rules** — enable/disable SOUL / morals / code-field without hand-editing schema\n> 3. Not now (exit setup)\n> 4. Discuss\n> 5. Back\n\n- ! Final two numbered options MUST be `Discuss` and `Back` per [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md)\n- ! On option 2, enter **Revisit experimental rules** (next section) — not a full Phase 1 re-interview\n- ⊗ Silently skip past a complete USER.md with no re-entry offer when the operator entered setup (or asked to configure preferences)\n- ⊗ Invent a `deft config` / `task config:*` verb family for this slice — setup skill re-entry is the product surface (#46)\n\n### Interview Rules\n\n! This phase follows the deterministic interview loop defined in `skills/deft-directive-interview/SKILL.md`. The core rules (one question per turn, numbered options with stated default, explicit \"other\" escape, depth gate, default acceptance, confirmation gate, structured handoff) apply here. Key points repeated for emphasis:\n\n! **Each message you send MUST contain exactly ONE question.** This is the most\nimportant rule in this file. After the user answers, send the NEXT question in\na new message. Repeat until all questions for their track are answered.\n\n- ⊗ Include two or more questions in the same message under any circumstances\n- ⊗ List upcoming questions — only show the current one\n- ~ Provide numbered answer options with an \"other\" choice where appropriate\n- ! Mark which option is RECOMMENDED when showing choices\n- ~ Use structured question tools only when visible option labels preserve the canonical numbers and returns map to numeric selections or exact displayed option text.\n\n### Question Sequence\n\n**Step 0 — Opening (all users):**\nAsk: \"How deep do you want to go?\"\n 1. I'm technical — ask me everything\n 2. I have some opinions but keep it simple\n 3. Just pick good defaults — I care about the product, not the tools\n\nWait for answer. Then follow the track below.\n\n**Track 1 (technical) — 7 steps:**\n- Step 1: Ask their name\n- Step 2: Ask strategy preference (show Available Strategies numbered list from the Available Strategies section, with descriptions and recommended marker; fallback — projects can override)\n- Step 3: Ask coverage threshold (default 85%; fallback — projects can override)\n- Step 4: Ask for custom rules — if user has rules, collect them one per line (empty line to finish); if none, skip\n- Step 5a: Present SOUL.md and ask whether to include it (default: yes):\n > **SOUL.md** — Results-first agent persona (inspired by Winston Wolf). Enforces assess-before-acting,\n > finish-what-you-start, right-tool-for-the-job, and play-the-long-game. Keeps the AI decisive and\n > concise. Includes a named persona ('Vinston') — drop if you prefer to define your own agent personality.\n > Include SOUL.md? (Y/n)\n- Step 5b: Present morals.md and ask whether to include it (default: yes):\n > **morals.md** — Epistemic honesty rules. No presenting speculation as fact, label unverified claims,\n > self-correct when wrong. Foundational trust rules for any AI agent. Strongly recommended.\n > Include morals.md? (Y/n)\n- Step 5c: Present code-field.md and ask whether to include it (default: yes):\n > **code-field.md** — Pre-code assumption protocol. Requires stating assumptions and naming failure modes\n > before writing a single line. Fights the 'it compiles, ship it' instinct. Based on NeoVertex1 context-field.\n > Include code-field.md? (Y/n)\n\n**Track 2 (middle ground) — 2 steps:**\n- Step 1: Ask their name\n- Step 2: Ask for custom rules — if user has rules, collect them one per line (empty line to finish); if none, skip\n- Set defaults without asking: strategy = \"interview\", coverage = 85%, all meta-guidelines included\n\n**Track 3 (non-technical) — 2 steps:**\n- Step 1: Ask their name\n- Step 2: Ask what they're building (brief description — used for PROJECT-DEFINITION.xbrief.json later)\n- Set defaults: strategy = \"interview\", coverage = 85%, all meta-guidelines included\n\n### Output Path\n\nResolve using Platform Detection above. Write to the platform-appropriate path\n(or `$DEFT_USER_PATH` if set). Create parent directories as needed.\n\n### Template\n\n```markdown\n# User Preferences\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.\n\n**deft_version**: 0.20.0\n\n## Personal (always wins)\n\nSettings in this section have HIGHEST precedence — override all other deft rules,\nincluding PROJECT-DEFINITION.xbrief.json.\n\n**Name**: Address the user as: **{name}**\n\n**Custom Rules**:\n{custom rules or \"No custom rules defined yet.\"}\n\n## Defaults (fallback)\n\nSettings in this section are fallback defaults. PROJECT-DEFINITION.xbrief.json overrides these\nfor project-scoped settings (strategy, coverage).\n\n**Default Strategy**: [{strategy name}](../strategies/{strategy-file}.md)\n\n{If coverage != 85: \"**Coverage**: ! ≥{N}% test coverage\"}\n\n{If any experimental rules selected:\n\"## Experimental Rules\n\n{one line per selected rule, e.g.:\n- ! Use meta/SOUL.md for strategic context and purpose-driven guidance\n- ! Use meta/morals.md for ethical AI development principles\n- ~ Use meta/code-field.md for advanced architecture patterns}\"}\n\n---\n\n**Note**: Edit this file anytime to update your preferences.\n**See**: [../../main.md](../../../main.md) for framework defaults.\n```\n\n### Then\n\n- ! Emit a structured-tool question asking whether to continue to Phase 2 (project configuration) only when the host preserves numeric labels; otherwise emit the deterministic numbered menu in chat. Options: `1. Yes (continue)`, `2. Not now (exit setup)`, `3. Discuss`, `4. Back (revisit previous phase)`. The numeric labels MUST remain visible and be returned as numeric selections or exact displayed option text.\n- ⊗ Ask the phase-transition question as unnumbered conversational prose or through a structured UI that hides the canonical numeric labels -- it is a deterministic menu and MUST preserve visible numbers (#478, #1563).\n\n---\n\n## Revisit experimental rules (#46)\n\n**Goal:** Guided enable/disable of USER.md **Experimental Rules** entries that *reference* framework deposit meta files (`meta/SOUL.md`, `meta/morals.md`, `meta/code-field.md`). This is a post-bootstrap return path — not Phase 1 bootstrap, not a general preferences UI, and not an editor for framework meta file bodies.\n\n### When to enter\n\n- Returning-user re-entry option **Revisit experimental rules**\n- Direct user ask: \"revisit experimental rules\", \"toggle experimental meta\", \"turn on SOUL\", \"disable code-field\", etc.\n- USER.md exists and is complete enough to edit (Name present); missing non-meta fields still use Freshness Detection individual queries first\n\n### Out of scope\n\n- ⊗ General preferences UI / rewriting Personal or Defaults sections as part of this path\n- ⊗ Editing framework `meta/*.md` content (deposit owns SOUL / morals / code-field bodies; `directive update` refreshes deposit)\n- ⊗ Deposit layout changes\n- ⊗ Inventing a full `deft config` mega-surface or new `task config:*` verb family for this slice\n- ⊗ Re-building USER.md bootstrap / non-overwrite semantics\n- ⊗ Treating Experimental Rules lines as project-local copies of meta files — they are **references** only\n\n### Flow\n\n! **Each message MUST contain exactly ONE question** (same interview rule as Phase 1).\n\n1. ! Resolve USER.md via Platform Detection (`$DEFT_USER_PATH` → platform path). Read the file as **UTF-8**.\n2. ! Parse current Experimental Rules state (on/off) for the three paths:\n - `meta/SOUL.md`\n - `meta/morals.md`\n - `meta/code-field.md`\n - Detection: any line containing that path counts as **on** (custom wording still counts).\n3. ! Show a **current state** summary (table or short list), for example:\n\n | Entry | State | Role |\n |-------|-------|------|\n | SOUL.md | on/off | Results-first agent persona |\n | morals.md | on/off | Epistemic honesty |\n | code-field.md | on/off | Pre-code assumption protocol |\n\n4. ! Ask which entry to change with a deterministic numbered menu (one question). Options MUST include each of the three entries as toggle targets, plus **Done (save)** / **Done (discard)**, and final two options `Discuss` and `Back`:\n\n > \"Toggle which experimental meta entry? (current state shown above)\"\n > 1. SOUL.md — currently {on|off}\n > 2. morals.md — currently {on|off}\n > 3. code-field.md — currently {on|off}\n > 4. Done — save changes\n > 5. Done — discard changes\n > 6. Discuss\n > 7. Back\n\n5. ! When the user picks an entry (1–3), optionally show the short Phase 1 explainer (steps **5a–5c** copy below), then confirm the new on/off value with a Y/n or numbered keep/flip menu. Update the **in-memory** desired state; do not write yet. Return to the toggle menu (step 4) until Done.\n6. ! On **Done — save**: show a confirmation summary of the three final on/off values and require explicit affirmative (`yes` / `confirmed` / `approve`) before write — same Post-Interview Confirmation Gate strictness.\n7. ! On **Done — discard** or **Back** without save: leave USER.md unchanged and return to the Returning-user re-entry menu (or exit if invoked directly).\n\n### Explainers (reuse Phase 1 steps 5a–5c)\n\n- **SOUL.md** — Results-first agent persona (inspired by Winston Wolf). Enforces assess-before-acting, finish-what-you-start, right-tool-for-the-job, and play-the-long-game. Keeps the AI decisive and concise. Includes a named persona ('Vinston') — drop if you prefer to define your own agent personality.\n- **morals.md** — Epistemic honesty rules. No presenting speculation as fact, label unverified claims, self-correct when wrong. Foundational trust rules for any AI agent. Strongly recommended.\n- **code-field.md** — Pre-code assumption protocol. Requires stating assumptions and naming failure modes before writing a single line. Fights the 'it compiles, ship it' instinct. Based on NeoVertex1 context-field.\n\n### Safe write rules (non-clobber)\n\n! When persisting toggles to USER.md:\n\n1. ! Write **UTF-8** (no BOM). Create parent directories only if the resolved path's parent is missing — never relocate USER.md.\n2. ! Change **only** the `## Experimental Rules` section (add the section if enabling when absent; remove the section when all three are off and no custom bullets remain).\n3. ! Canonical enable lines (match Phase 1 template):\n - `- ! Use meta/SOUL.md for strategic context and purpose-driven guidance`\n - `- ! Use meta/morals.md for ethical AI development principles`\n - `- ~ Use meta/code-field.md for advanced architecture patterns`\n4. ! Disable = remove lines that mention that path. Preserve any **custom** non-meta bullets under Experimental Rules.\n5. ! **Personal** and **Defaults** section bodies MUST remain byte-identical to the pre-write file (non-clobber).\n6. ~ Prefer the pure helper `applyExperimentalRulesState` / `setExperimentalRule` from `@deftai/directive-core` `userConfig` (`packages/core/src/user-config/experimental-rules.ts`) when the package is importable (framework checkout, tests, or a thin local script). When editing by hand as an agent, apply the same rules: section-only edit, UTF-8, path-based match, canonical enable lines.\n7. ! After write, re-read USER.md and show the final on/off state to the user.\n\n⊗ Rewrite the whole USER.md from the Phase 1 template when only Experimental Rules changed\n⊗ Clobber or reformat **Personal** / **Defaults** content while toggling experimental meta\n⊗ Hand-edit framework `meta/SOUL.md`, `meta/morals.md`, or `meta/code-field.md` bodies as part of this path\n⊗ Invent `deft config` / `task config:experimental-*` for this product slice when setup re-entry suffices\n\n### Then\n\n- ! After a successful save (or discard), re-offer the Returning-user re-entry menu (Continue to Phase 2 / Revisit again / Exit / Discuss / Back) unless the user asked only for the toggle and is done.\n- ~ If Phase 2 is already complete, prefer Exit over Continue unless the user wants project reconfiguration.\n\n## Phase 2 — Project Configuration (PROJECT-DEFINITION.xbrief.json)\n\n**Goal:** Project-specific configuration — tech stack, type, quality standards — written as a xBRIEF file at `./xbrief/PROJECT-DEFINITION.xbrief.json`.\n\n! **Path Resolution Anchor**: Resolve ALL paths relative to the user's working directory (pwd) at skill entry -- never relative to the skill file location, AGENTS.md location, or any framework directory (e.g. `./deft/`). When deft is cloned as a subdirectory, the skill file lives inside the clone but all project artifacts (`./xbrief/PROJECT-DEFINITION.xbrief.json`, build files, etc.) must be resolved from the user's pwd.\n\n- ~ Skip if `./xbrief/PROJECT-DEFINITION.xbrief.json` exists (or `$DEFT_PROJECT_PATH` if set) and user doesn't want to replace\n- ⊗ Count `./deft/PROJECT-DEFINITION.xbrief.json` or `./deft/core/project.md` as the user's project config — those are framework-internal\n\n### Inference\n\n- ! Before asking, infer from codebase — look for `package.json`, `go.mod`, `requirements.txt`, `Cargo.toml`, `pyproject.toml`, `*.csproj`\n- ! Use inferences to pre-fill answers and confirm — don't ask blind\n- ⊗ Look inside `./deft/` for build files (`go.mod`, `package.json`, `pyproject.toml`, `Cargo.toml`, `*.csproj`, etc.) — those are framework-internal. Only inspect files at the project root and its non-`deft` subdirectories.\n- ⊗ Run git commands inside `./deft/` to determine project identity — that directory is the framework repo, not the user's project.\n- ~ If no build files are found at the project root, default the project name to the current directory name and ask for confirmation.\n\n### Track Detection\n\n! If Phase 1 was skipped (USER.md already existed), the user's track is unknown.\nBefore asking any Phase 2 questions, ask the depth question:\n\n> \"How deep do you want to go?\"\n> 1. I'm technical — ask me everything\n> 2. I have some opinions but keep it simple\n> 3. Just pick good defaults — I care about the product, not the tools\n\nWait for answer. Then follow the corresponding track in the Question Sequence below.\n\n⊗ Assume Track 1 (technical) because USER.md exists or contains strategy/coverage fields.\n⊗ Infer the track from USER.md content — always ask.\n\n### Defaults in Agentic Mode\n\n! When a question has a USER.md default, phrase it as:\n> \"{Field}: **{value}** from USER.md — keep this, or enter a different value?\"\n\n! Accept any affirmative response (\"keep\", \"yes\", \"same\", \"default\", ✓) as confirmation to use the default.\n⊗ Phrase defaults as \"press Enter to keep\" — there is no Enter in conversational mode.\n\n### Interview Rules (same as Phase 1)\n\n! **Each message MUST contain exactly ONE question.** The Phase 1 interview rules\napply here too. Do not combine questions. See `skills/deft-directive-interview/SKILL.md` for the canonical deterministic interview loop.\n\n### Question Sequence\n\n**Track 1 (technical) — 8 steps:**\n- Step 1: Ask project name (infer from build files or directory name, confirm)\n- Step 2: Ask project type (CLI, TUI, Desktop App, REST API, Web App, Library, other)\n- Step 3: Ask deployment platform:\n 1. Cross-platform (Linux / macOS / Windows)\n 2. Windows-native\n 3. macOS-native\n 4. Linux / Unix\n 5. Embedded / low-resource\n 6. Web / Cloud\n 7. Mobile (iOS / Android)\n 8. Other / not sure\n- Step 4: Ask languages — show a filtered shortlist (3–4 recommendations) based on project type + platform. If codebase markers exist (`go.mod`, `pyproject.toml`, etc.), skip and confirm: \"Detected {lang} — correct?\"\n - If user selects \"Other\": show remaining plausible languages for the type+platform context (Tier 2)\n - If still not found: free text input (Tier 3)\n - If entered language has no deft `languages/{lang}.md` standards file, warn: \"deft doesn't have a standards file for {lang} yet — general defaults will be used. Continue?\"\n- Step 5: Ask tech stack (frameworks, libraries)\n- Step 6: Ask strategy (default to USER.md Defaults; ask if this project needs different — show Available Strategies numbered list with descriptions and recommended marker)\n- Step 7: Ask coverage (default to USER.md Defaults; ask if this project needs different)\n- Step 8: Ask for project-specific rules (optional, same one-per-line format as Phase 1 custom rules)\n- Step 9: Ask branching preference (typed `plan.policy.allowDirectCommitsToMaster` flag per #746):\n\n ! Render this as a deterministic numbered menu. Default `1. Branch-based`. Final two options MUST be `Discuss` and `Back` per [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md):\n\n > \"Do you prefer branch-based workflow (create a feature branch for every change) or\n > trunk-based (commit directly to master)? Branch-based is the default and recommended\n > for teams; trunk-based is common for solo projects.\"\n > 1. Branch-based ★ (recommended -- default; enforces feature branches via the deft branch-protection policy)\n > 2. Trunk-based (direct commits to master) -- see capability-cost disclosure below\n > 3. Discuss\n > 4. Back\n\n ! **Capability-cost disclosure (#746):** When the user picks option 2 (trunk-based), the agent MUST present the capability-cost disclosure verbatim BEFORE writing the typed flag, then re-prompt for explicit confirmation:\n\n > \"Capability-cost disclosure -- enabling direct commits to the default branch turns OFF the deft branch-protection policy. The pre-commit + pre-push hooks will no longer block default-branch commits, `task verify:branch` will pass on the default branch, and the skill-level guards in deft-directive-{swarm,review-cycle,pre-pr,release} will not halt for default-branch work. The change is reversible (`task policy:enforce-branches`) and is recorded to meta/policy-changes.log for auditability. The CI sanity check (head_ref != base_ref) remains independent and will continue to flag master->master PRs. Are you sure?\"\n > 1. Yes, opt out -- write `plan.policy.allowDirectCommitsToMaster = true`\n > 2. No, keep branch-protection enforced -- write `plan.policy.allowDirectCommitsToMaster = false`\n > 3. Discuss\n > 4. Back\n\n ! Default to option 2 (enforce). Explicit affirmative on option 1 is required to opt out -- a broad `proceed` does NOT satisfy this gate. The same affirmative-only rule applies as in `/deft:change` (`yes`, `confirmed`, `approve`).\n\n ! Write the answer to `plan.policy.allowDirectCommitsToMaster` (typed boolean) on the PROJECT-DEFINITION xBRIEF. Default `false` (enforce branches) when the user picks option 2 OR omits the question entirely. Writing this typed surface is what the framework reads going forward; agents MUST NOT write the legacy free-form `Allow direct commits to master:` narrative key (#746 part A migrates the legacy narrative away).\n\n ! **Re-running the interview detects the existing flag (#746 part G2):** If `xbrief/PROJECT-DEFINITION.xbrief.json` already exists and has `plan.policy.allowDirectCommitsToMaster` set, the interview MUST surface the current value (e.g. \"Current setting: `allowDirectCommitsToMaster=false` (branch-protection ON)\") and ask whether to keep it or change it before re-prompting. Do not silently overwrite an existing typed value.\n\n ! **Slash-command alternatives (#746 part G2):** Once the project is set up, the typed flag can also be flipped via slash commands wrapping `task policy:*`:\n - `/deft:policy:show` -- display the current resolved policy and source\n - `/deft:policy:enforce-branches` -- set `allowDirectCommitsToMaster=false`\n - `/deft:policy:allow-direct-commits` -- set `allowDirectCommitsToMaster=true` (requires `--confirm` to apply)\n\n Each transition is recorded to `meta/policy-changes.log` for auditability.\n\n**Track 2 (middle ground) — 4 steps:**\n- Step 1: Ask project name (infer from build files or directory name, confirm)\n- Step 2: Ask project type (CLI, TUI, Desktop App, REST API, Web App, Library, other)\n- Step 3: Ask languages (show detected, confirm or adjust; if none detected, infer from type and ask)\n- Step 4: Ask strategy (default to USER.md Defaults; ask if this project needs different — show Available Strategies numbered list with descriptions and recommended marker)\n- Default coverage to USER.md Defaults without asking\n\n**Track 3 (non-technical) — 1 step:**\n- Step 1: Present summary of inferences: \"Based on your project: {name} ({type}), built with {stack}. Look right?\"\n- ⊗ Ask about strategy or coverage — use Phase 1 defaults\n\n### Output Path\n\n`./xbrief/PROJECT-DEFINITION.xbrief.json` (or `$DEFT_PROJECT_PATH` if set). Create `./xbrief/` directory and lifecycle subfolders (`proposed/`, `pending/`, `active/`, `completed/`, `cancelled/`) if they don't exist.\n\n### GitHub PR Template Scaffolding (#531)\n\n! Before writing `PROJECT-DEFINITION.xbrief.json`, offer to scaffold a default GitHub PR template so downstream skills (`deft-directive-refinement` Pre-Flight, `deft-directive-pre-pr`) can satisfy their `.github/PULL_REQUEST_TEMPLATE.md` checks without blocking.\n\n1. ! Ask the user with a deterministic numbered menu: \"Create a default GitHub PR template at `.github/PULL_REQUEST_TEMPLATE.md`?\" Options: `1. Yes`, `2. No`, `3. Discuss`, `4. Back`. Use a structured question tool only if those numeric labels remain visible and are returned as numeric selections or exact displayed option text.\n2. ! If the user accepts AND `.github/PULL_REQUEST_TEMPLATE.md` does NOT already exist: copy `templates/PULL_REQUEST_TEMPLATE.md` (shipped with deft) to `./.github/PULL_REQUEST_TEMPLATE.md` in the consumer project. Create `.github/` if it does not exist.\n3. ! If the file already exists, do NOT overwrite it — report that it is present and continue.\n4. ~ If the user declines, note that `deft-directive-refinement` Pre-Flight will offer to scaffold later when needed.\n\n⊗ Overwrite an existing `.github/PULL_REQUEST_TEMPLATE.md` without explicit user approval.\n\n### Headless Coverage Warning — display-bound GUI entry points (#1027)\n\n! The trigger is a **display-bound GUI event loop** (pygame, tkinter, PyQt/PySide, Kivy, Electron) that cannot run without a real display — typically a **Desktop App** project type, or a TUI that embeds such a GUI. Terminal-UI frameworks (textual, urwid, blessed, ncurses) run in the terminal and DO support headless testing (e.g. textual's `App.run_async()` + `Pilot`), so a standard TUI is NOT in scope — do not omit its coverage. The concrete commands below assume a **Python** GUI stack (pygame/tkinter); the same \"omit the un-runnable loop, test the logic\" principle applies to non-Python desktop stacks (Electron/JS, .NET/WPF, Qt/C++) using that language's own headless-test and coverage-exclusion tooling. When the Phase 2 project type resolves to a display-bound GUI project, warn the user BEFORE writing `PROJECT-DEFINITION.xbrief.json` (adapt the wording to the project's language):\n\n> \"Heads up: pygame/tkinter event loops can't be tested headlessly, so the display-bound entry point (e.g. `src/ui.py`) reports near-zero coverage and drags the overall percentage below the 85% threshold. I recommend excluding the UI entry point from coverage measurement and keeping it thin — push testable logic (state, scoring, input handling) into separate modules.\"\n\n! When scaffolding or advising on `pyproject.toml` for a display-bound GUI project, add the display-bound entry point to `[tool.coverage.run] omit` so `task check` measures logic modules only:\n\n```toml\n[tool.coverage.run]\nomit = [\n \"*/tests/*\",\n \"*/venv/*\",\n \"*/.venv/*\",\n \"src/ui.py\", # display-bound pygame/tkinter event loop -- cannot run headlessly (#1027)\n]\n```\n\n- ! Keep the omit narrow — exclude only the event-loop shell, never a module that also holds business logic. If logic and the loop are mixed, recommend refactoring the logic into a separate, fully-tested module first.\n- ~ For a Python project, point the user at `languages/python.md` (the `Headless GUI / event-loop testing` section under Patterns) for the headless-test pattern (`SDL_VIDEODRIVER=dummy`) and the full coverage-omit rationale; for a non-Python GUI stack, apply the same principle with that language's headless-test and coverage-exclusion tooling.\n- ⊗ Apply the omit to a headless-capable terminal-UI project (textual/urwid/blessed/ncurses) — those frameworks test headlessly, so omitting them hides measurable coverage, the opposite of the intended effect.\n- ⊗ Silently accept the default 85% coverage gate for a display-bound GUI project without surfacing the headless blind spot — the agent reports an inflated per-session coverage that collapses when the full `src/` is measured (the 2026-05-10 tic-tac-toe desktop-UI swarm recurrence).\n\n### Template\n\n! The output MUST conform to the canonical xBRIEF v0.8 schema (`xbrief/schemas/xbrief-core-0.8.schema.json`, strict `const: \"0.8\"`). See [`../../conventions/references.md`](../../conventions/references.md). Write-path default is **0.8 only** (#2971); legacy 0.6 remains read-accepted until `deft migrate:xbrief`.\n\n```json\n{\n \"xBRIEFInfo\": {\n \"version\": \"0.8\",\n \"author\": \"agent:deft-directive-setup\",\n \"description\": \"Project identity gestalt\",\n \"created\": \"{ISO-8601 timestamp}\"\n },\n \"plan\": {\n \"title\": \"{Project Name}\",\n \"status\": \"running\",\n \"narratives\": {\n \"Overview\": \"{Brief project description}\",\n \"TechStack\": \"{project type} using {languages} — {tech stack details}\",\n \"Strategy\": \"Use {strategy name} for this project\",\n \"Quality\": \"Run task check before every commit. Achieve >= {coverage}% coverage overall + per-module. Store secrets in secrets/ dir.\",\n \"ProjectRules\": \"{Any rules the user specified, or 'No project-specific rules defined.'}\",\n \"Branching\": \"{If trunk-based: 'Allow direct commits to master: true', else omit or 'Branch-based workflow (default)'}\",\n \"DeftVersion\": \"0.20.0\"\n },\n \"items\": []\n }\n}\n```\n\n- ! All `narratives` values MUST be plain strings — never objects or arrays\n- ! `items` starts empty — populated as scope xBRIEFs are created in lifecycle folders\n\n### Then\n\n- ! Emit a structured-tool question asking whether to continue to Phase 3 (specification) only when the host preserves numeric labels; otherwise emit the deterministic numbered menu in chat. Options: `1. Yes (continue)`, `2. Not now (exit setup)`, `3. Discuss`, `4. Back (revisit previous phase)`. The numeric labels MUST remain visible and be returned as numeric selections or exact displayed option text.\n- ⊗ Ask the phase-transition question as unnumbered conversational prose or through a structured UI that hides the canonical numeric labels -- it is a deterministic menu and MUST preserve visible numbers (#478, #1563).\n\n### Follow-up: triage onboarding (#1143)\n\n- ~ After Phase 2 writes `PROJECT-DEFINITION.xbrief.json`, recommend `task triage:welcome` to the user as the single chained command for picking up the v0.27 triage surface. The N3 ritual (#1143) is the consolidating onboarding step for the #1119 governance swarm verbs (`task triage:bootstrap` / `task triage:scope` / `plan.policy.wipCap` writes / `task scope:demote --batch` relief / `task triage:summary`); without it consumers must learn each verb individually from the v0.27 release notes.\n- ~ `task triage:welcome` is idempotent and detection-bound -- each phase emits an informational stderr line and skips when its precondition is already satisfied, so a re-run after a partial completion resumes cleanly. The destructive phases (subscription / `wipCap` writes, optional WIP-relief invocation) are gated by numbered-menu prompts per [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md). See [`../../UPGRADING.md`](../../UPGRADING.md) `## From v0.26.x -> v0.27` for the full walkthrough.\n### Consumer AGENTS always-pin recommendations (#2508)\n\n! After Phase 2 completes (or when closing a greenfield bootstrap), tell the consumer that process-critical directive skills should be named in their project's AGENTS.md **unmanaged header** when false-negative risk matters — full tier definitions: [`../../docs/skill-pin-policy.md`](../../docs/skill-pin-policy.md).\n~ Recommend the default consumer pin set for lifecycle work: `deft-directive-build` (implementation), `deft-directive-pre-pr` (before PR), `deft-directive-review-cycle` (bot review loop), and `deft-directive-swarm` when they plan parallel agents. Each is referenced by skill id + `.deft/core/.agents/skills/<id>/SKILL.md` path — not by pasting skill bodies.\n⊗ Recommend pinning entire `languages/`, `deployments/`, or other framework doc packs into AGENTS.md (#2508 anti-pattern).\n\n---\n\n## Phase 3 — Specification\n\n**Goal:** Generate an implementable spec using the strategy chosen in Phase 2, producing scope xBRIEFs in `xbrief/proposed/` and PROJECT-DEFINITION narratives for human approval — greenfield v0.20 does not create `specification.xbrief.json`.\n\n! **Path Resolution Anchor**: Same rule as Phase 2 -- resolve ALL paths relative to the user's pwd at skill entry, never relative to the skill file, AGENTS.md, or any framework directory.\n\n- ~ Skip if user already has scope xBRIEFs in `./xbrief/` they're happy with\n- ! Check `./xbrief/specification.xbrief.json` or `./xbrief/proposed/` for existing scope xBRIEFs\n- ⊗ Count ANY file inside `./deft/` as the project's spec — those are framework-internal\n (e.g. `deft/PROJECT.md`, `deft/specs/`, `deft/templates/`, `deft/core/project.md`\n are all part of the framework, NOT the user's project)\n\n### Onboarding Question\n\n! Before proceeding with the strategy gate, ask the onboarding question. Use the same add-scope / update / replace vocabulary as the Chaining Gate in [strategies/interview.md](../../strategies/interview.md#chaining-gate).\n\n**Brownfield detector** (same as Chaining Gate): `PROJECT-DEFINITION` exists (`./xbrief/` or legacy `./vbrief/`) **OR** any lifecycle folder (`proposed/`, `pending/`, `active/`, `completed/`, `cancelled/`) has scope records.\n\n> \"How should we treat this project's specification?\"\n> 1. **Add scope to this project** [default when brownfield] — load existing identity; skip greenfield \"what are we building?\"; emit one proposed scope; Preparatory Guard on write\n> 2. **Update project definition** — delta interview → Spec-Generating Guard → merge narratives into existing PROJECT-DEFINITION\n> 3. **Replace specification (scrap)** — only after explicit affirmative (`yes` / `confirmed`); then full new-spec path\n> 4. **Starting a new project specification** [default when greenfield] — proceed to the Strategy Gate below\n> 5. **Discuss** — explore these options before choosing\n> 6. **Back** — return to the previous setup question\n\n- ! Default based on repo state via the brownfield detector above (brownfield → Add scope; greenfield → Starting new)\n- ! Final two numbered options MUST be `Discuss` and `Back` per [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md)\n- ! If **Add scope**: skip the full interview, create a new scope xBRIEF in `./xbrief/proposed/` with the user's description, apply Preparatory Guard on write, then surface the Lifecycle Bridge + End-of-Phase-3 Export Prompt + handoff sections below (do not dead-end after the write)\n- ! If **Update project definition**: run a delta interview; apply Spec-Generating Guard against `./xbrief/PROJECT-DEFINITION.xbrief.json` (or legacy `./vbrief/PROJECT-DEFINITION.vbrief.json` if that is the existing identity); merge narratives (do not wholesale replace unless the user confirmed scrap)\n- ! If **Replace specification (scrap)**: require explicit `yes`/`confirmed`, then proceed to the Strategy Gate as a greenfield-style full path\n- ! If **Starting new**: proceed to the Strategy Gate below\n- ⊗ Treat brownfield repos as \"Starting new\" by default\n- ⊗ Accept vague confirmation (`proceed`, `ok`) for Replace/scrap\n- ⊗ Exit immediately after Add-scope write without the lifecycle bridge / export / handoff guidance\n\n### ⚠️ MANDATORY: Strategy Gate — Do This First\n\n! **STOP.** You MUST determine the correct strategy before doing anything else.\n\n1. ! Open `./xbrief/PROJECT-DEFINITION.xbrief.json` (the file written in Phase 2)\n2. ! Find the `narratives.Strategy` value\n3. ! Extract the strategy name from the narrative\n\n**Dispatch:**\n\n- **interview** (or default) → Continue to the Sizing Gate below ✅\n- **anything else** (discuss, yolo, speckit, research, brownfield, map, etc.) →\n 1. ! Read `deft/strategies/{strategy-name}.md` **right now, in this same turn**\n 2. ! Begin the strategy's workflow immediately — ask its first question\n 3. ! **STOP reading this section** — do NOT use the interview process below\n\n- ⊗ Default to interview without reading PROJECT-DEFINITION.xbrief.json\n- ⊗ Continue reading below when PROJECT-DEFINITION.xbrief.json specifies a non-interview strategy\n- ⊗ Assume interview because the sections below describe the interview process\n- ⊗ Fabricate justification for using interview when the user chose a different strategy\n- ⊗ Announce the strategy choice and then stop — you must immediately read the file and start\n\n---\n\n*⬇️ Everything below applies ONLY to the interview strategy. If your strategy is anything else, STOP — follow your strategy file instead.*\n\n### Sizing Gate (interview and yolo strategies only)\n\n! After hearing what the user wants to build and their feature list, determine\nproject complexity per [strategies/interview.md](../../strategies/interview.md#sizing-gate).\n\n- ! Check `PROJECT-DEFINITION.xbrief.json` narratives for `Light` or `Full` — if declared, use that path\n- ! If not declared, propose a size and **ask the user to confirm in a dedicated message**\n- ! **Wait for the user's response** before asking any interview questions\n- ⊗ Combine the sizing proposal with the first interview question\n- ⊗ Proceed to interview questions before the user has confirmed the path\n\n**Light** (small/medium): Interview → `specification.xbrief.json` with slim narratives (Overview + Architecture) → scope xBRIEFs in `xbrief/proposed/`.\n**Full** (large/complex): Interview → rich narratives in `specification.xbrief.json` (user approval) → scope xBRIEFs with traceability.\n\n### Interview Process (interview strategy)\n\nPer [strategies/interview.md](../../strategies/interview.md#interview-rules-shared-by-both-paths):\n\n- ! Ask what to build and features first\n- ! Ask **ONE** focused, non-trivial question per step\n- ~ Provide numbered options with an \"other\" choice\n- ! Mark which option is RECOMMENDED\n- ⊗ Ask multiple questions at once\n- ⊗ Make assumptions without clarifying\n- ~ Use structured question tools for interview questions only when they preserve visible numeric option labels and return numeric selections or exact displayed option text; otherwise render the numbered menu in chat.\n\n**Question Areas:**\n- ! Missing decisions (language, framework, deployment)\n- ! Edge cases (errors, boundaries, failure modes)\n- ! Implementation details (architecture, patterns, libraries)\n- ! Requirements (performance, security, scalability)\n- ! UX/constraints (users, timeline, compatibility)\n- ! Tradeoffs (simplicity vs features, speed vs safety)\n\n**Non-Technical Users:**\n- ~ Adjust vocabulary: \"How do you want to store data?\" not \"What database engine?\"\n- ~ \"Will other apps talk to this?\" not \"REST or GraphQL?\"\n\n**Completion:**\n- ! Continue until little ambiguity remains\n- ! Spec must be comprehensive enough to implement\n\n### Output — Light Path\n\n1. ! Write `./xbrief/specification.xbrief.json` with `\"xBRIEFInfo\": { \"version\": \"0.8\" }`, `status: draft`, and slim narratives:\n - `Overview`: Brief project summary\n - `Architecture`: System design description\n2. ! Create scope xBRIEFs in `./xbrief/proposed/` for each identified work item\n - Each scope xBRIEF follows the `YYYY-MM-DD-descriptive-slug.xbrief.json` filename convention (slug rules in [`../../conventions/vbrief-filenames.md`](../../conventions/vbrief-filenames.md))\n - Each MUST use `\"xBRIEFInfo\": { \"version\": \"0.8\" }`\n - Each MUST include embedded Requirements (FR-N, NFR-N) in its `narrative`\n - Each task SHOULD reference which FR/NFR it implements via `narrative.Traces`\n - When the scope originates from a GitHub issue, include a `references` entry in the canonical form (see [`../../conventions/references.md`](../../conventions/references.md)):\n ```json\n \"references\": [\n {\n \"uri\": \"https://github.com/{owner}/{repo}/issues/{N}\",\n \"type\": \"x-xbrief/github-issue\",\n \"title\": \"Issue #{N}: {issue title}\"\n }\n ]\n ```\n3. ! Summarize decisions, ask user to review the xBRIEF narratives\n4. ! On approval, update `specification.xbrief.json` status to `approved`\n- ⊗ Create a separate PRD.md on the Light path\n- ⊗ Generate an authoritative PRD.md — if needed, users run `task prd:render`\n\n! The xBRIEF files MUST conform to `xbrief/schemas/xbrief-core-0.8.schema.json` (v0.8):\n\n- ! All `narratives` and `narrative` values MUST be plain strings — never objects or arrays\n- ! Nested children within a PlanItem use `items` (preferred field); `subItems` is the deprecated legacy alias kept for backward compatibility only\n- ⊗ Mix `items` and `subItems` on the same PlanItem — pick one (prefer `items`)\n- ⊗ Emit `\"version\": \"0.6\"` on any new write path — current engine write-default is `0.8` only (#2971)\n\n### Output — Full Path\n\n1. ! Write rich narratives to `./xbrief/specification.xbrief.json` with `\"xBRIEFInfo\": { \"version\": \"0.8\" }`, `plan.status: draft`, and these narrative keys:\n - `ProblemStatement`: What problem this project solves\n - `Goals`: High-level project goals\n - `UserStories`: User stories in standard format\n - `Requirements`: Structured requirements (FR-N: ..., NFR-N: ...)\n - `SuccessMetrics`: Measurable success criteria\n - `Architecture`: System design and technical architecture\n - `Overview`: Brief project summary\n2. ! **Human approval gate**: Present the xBRIEF draft narratives to the user for review — reviewing the `specification.xbrief.json` narratives IS the approval step (replaces the former PRD.md review). The user may request changes before approving.\n3. ! On approval, update `status` to `approved` and proceed to downstream generation\n4. ! Create scope xBRIEFs in `./xbrief/proposed/` with traceability to requirement IDs from the narratives\n- ! Scope xBRIEFs MUST trace tasks back to requirement IDs (FR-1, NFR-1) from the `Requirements` narrative\n- ⊗ Generate an authoritative PRD.md — if needed, users run `task prd:render`\n\n**Spec Structure (both paths):**\n- ! Overview, Architecture\n- ! Implementation Plan: scope xBRIEFs in `xbrief/proposed/` with phases and dependencies\n- ! Explicit dependency mapping between scopes (via xBRIEF `edges` or `references`)\n- ~ Scopes designed for parallel work by multiple agents\n- ! Testing Strategy and Deployment captured in narratives\n- ⊗ Write code — specification only\n\n### Lifecycle Bridge to Downstream Skills (#1025)\n\n! Scope xBRIEFs created by Phase 3 (both Light and Full paths) AND by the Onboarding Question \"Add scope to this project\" branch land in `xbrief/proposed/` with `plan.status: proposed`. This is the canonical deposit point per the deft lifecycle (`proposed -> pending -> active -> completed`). The #810 implementation-intent gate (`task xbrief:preflight`) and the deft-directive-swarm Phase 0 Step 1 preflight BOTH require candidate xBRIEFs to live in `xbrief/active/` with `plan.status == \"running\"` before any agent can dispatch against them; setup deliberately stops at `proposed/` because the lifecycle commitment (promote + activate) belongs to the downstream skill, not the setup interview.\n\n! Surface this bridge to the user in the Phase 3 → next-skill handoff so they are not surprised by a wholesale preflight rejection downstream:\n\n - **If the next step is `skills/deft-directive-swarm/SKILL.md`**: the swarm skill's Phase 0 Step 0.5 (Lifecycle Bridge -- Promote and Activate Proposed Scope xBRIEFs) is the canonical bridge. The monitor will scan `xbrief/proposed/` and `xbrief/pending/`, present in-scope candidates, and run `task scope:promote -- <path>` then `task scope:activate -- <path>` on explicit user approval. No manual operator action is required ahead of the swarm invocation.\n - **If the next step is `skills/deft-directive-refinement/SKILL.md`**: the refinement skill's Phase 4 (Promote/Demote) owns the same `task scope:promote` / `task scope:activate` surface and runs the bridge as part of the refinement loop. The refinement skill MAY leave xBRIEFs in `pending/` deliberately when they are queued for prioritisation rather than immediate dispatch.\n - **If the user wants to invoke an implementation agent directly via `skills/deft-directive-build/SKILL.md` or `start_agent`**: the bridge MUST be run manually before dispatch -- `task scope:promote -- xbrief/proposed/<file>` then `task scope:activate -- xbrief/pending/<file>`. Both commands are idempotent and exit 0 on no-op. The #810 preflight gate (`task xbrief:preflight -- <active-path>`) will exit 0 only after the activate step.\n\n⊗ Auto-run `task scope:promote` or `task scope:activate` from the setup skill on the Phase 3 outputs. The lifecycle commitment belongs to the user (\"I am ready to swarm/build on this scope\"), not the setup interview; silent promotion would clear the #810 implementation-intent gate without explicit user authorisation and bypass the deterministic-questions contract that protects every other Phase 3 transition.\n\n⊗ Drop the user at the end of Phase 3 with scope xBRIEFs in `xbrief/proposed/` and no forward pointer to the bridge. Without this section the user discovers the gap at runtime when the swarm Phase 0 Step 1 preflight rejects every candidate (`Invalid transition: 'activate' requires file in pending/`), as in the originating 2026-05-10 first-session consumer tic-tac-toe swarm (issue #1025).\n\n### End-of-Phase-3 Export Prompt (project:export-spec)\n\n! After scope xBRIEFs are written to `xbrief/proposed/` and PROJECT-DEFINITION is populated, but BEFORE handing off to `deft-directive-build` (or advancing speckit Phase 3 → Phase 4), ask the user whether to generate human-readable exports. Greenfield v0.20 projects export via `task project:export-spec` (not legacy `task spec:render`). This replaces the invisible skip-if-absent behavior of `task check` (#398), closes the greenfield gap (#433), and is the Phase 3 → Phase 4 transition gate required by [strategies/speckit.md Post-Phase 3 Transition Gate](../../strategies/speckit.md#post-phase-3-transition-gate-export-for-review) (#432 / #2013).\n\n1. ! Prompt: \"Your scope xBRIEFs are ready. Generate a stakeholder-facing spec export and/or `PRD.md` now? (recommended for stakeholder review)\"\n 1. Yes — export spec (+ PRD if selected)\n 2. Spec export only (`SPECIFICATION.md`)\n 3. `PRD.md` only\n 4. Skip — I'll export later with `task project:export-spec` / `task prd:render`\n2. ! Run the selected export command(s):\n - `task project:export-spec` → writes `SPECIFICATION.md` from PROJECT-DEFINITION + lifecycle scopes (greenfield default; stakeholder audience)\n - `task project:export-spec -- --audience=internal` → same export but includes proposed scopes under `## Scope outlook` (use for setup/speckit internal handoff when proposed scopes need visibility)\n - `task prd:render` → writes `PRD.md` (optional stakeholder review)\n - Legacy `task spec:render` — migrated trees only (when `xbrief/specification.xbrief.json` exists); do NOT use on greenfield v0.20 projects\n3. ! If the user picked a speckit-strategy project: export is **mandatory** at this boundary — invoke `task project:export-spec` (with `--audience=internal` when proposed scopes exist) even if the user declined the prompt, because speckit Phase 3 → Phase 4 is gated on **export succeeded** (exit 0), not on `specification.xbrief.json` approval.\n4. ! Confirm to the user which files were written and remind them that direct edits to `SPECIFICATION.md` / `PRD.md` are overwritten on the next export — edit xBRIEF narratives in `xbrief/proposed/` and PROJECT-DEFINITION instead.\n5. ~ If the user skipped export and is NOT on a speckit strategy, no-op and continue.\n\n⊗ Advance a speckit project to Phase 4 without a successful `task project:export-spec` at this gate — export must succeed (exit 0) for the Phase 3 transition criterion.\n⊗ Silently skip the prompt — greenfield users who never open a PR will miss the exports without it.\n⊗ Invoke legacy `task spec:render` on a greenfield v0.20 project — use `task project:export-spec` instead (#2013).\n\n### Handoff to deft-directive-build\n\n- ! Emit a structured-tool question asking whether to continue to the build phase only when the host preserves numeric labels; otherwise emit the deterministic numbered menu in chat. Options: `1. Yes (continue)`, `2. Not now (exit setup)`, `3. Discuss`, `4. Back (revisit previous phase)`. The numeric labels MUST remain visible and be returned as numeric selections or exact displayed option text.\n- ~ If platform supports skill invocation and the user picks Yes, invoke `skills/deft-directive-build/SKILL.md`\n- ⊗ Leave user with a dead end -- always offer the next step via the structured-tool phase-transition question\n- ⊗ Ask the handoff-to-build question as unnumbered conversational prose or through a structured UI that hides the canonical numeric labels -- it is a deterministic menu and MUST preserve visible numbers (#478, #1563).\n\n## Warp Auto-Approve Warning\n\n! **Recommended Warp setting**: Before running deft-directive-setup, ensure Warp's AI autonomy is set to **\"Always ask\"** in **AI -> Profile Settings**. When set to a higher autonomy level (e.g. \"Auto-run\"), Warp may silently self-answer interview questions without user input, producing garbage USER.md/PROJECT-DEFINITION.xbrief.json with no error or warning. The post-interview confirmation gate (below) is the last line of defense, but prevention is better than detection.\n\n## Post-Interview Confirmation Gate\n\n! After completing ALL interview questions for any phase (Phase 1, Phase 2, or Phase 3), but BEFORE writing any files:\n\n1. ! Display a **summary of all captured values** in a clearly formatted list -- include every field that will be written to the output file (e.g. name, strategy, coverage, languages, project type, custom rules, etc.)\n2. ! Ask the user for explicit confirmation: \"These are the values I captured. Write files? (yes/no)\"\n3. ! Accept only explicit affirmative responses (`yes`, `confirmed`, `approve`) -- reject vague responses (`proceed`, `do it`, `go ahead`) the same way `/deft:change` does\n4. ! If the user says `no`: re-display the values and ask which ones to correct, then re-confirm before writing\n5. ! If any value appears to be auto-generated filler (e.g. repeated default text, placeholder strings, or values that echo the question prompt), warn the user explicitly: \"Some values look like they may have been auto-filled rather than provided by you. Please review carefully.\"\n\n⊗ Write USER.md, PROJECT-DEFINITION.xbrief.json, specification.xbrief.json, or any other deft-directive-setup artifact without first displaying captured values and receiving explicit user confirmation.\n⊗ Treat a broad \"proceed\" or \"continue\" as confirmation to write files -- the user must explicitly confirm the displayed values.\n\n? **Yolo strategy carve-out**: When the user's chosen strategy is `yolo` (auto-pilot), the confirmation gate still applies but the agent (Johnbot) may self-confirm on the user's behalf by displaying the summary and immediately proceeding -- the user has already opted into auto-pilot by selecting yolo. The summary must still be displayed so the user can interrupt if values look wrong.\n\n## Anti-Patterns\n\n- ! When deft-directive-setup generates or updates USER.md or PROJECT-DEFINITION.xbrief.json, the `deft_version` field MUST be set to the current framework version\n- ⊗ Generate a USER.md or PROJECT-DEFINITION.xbrief.json without including the `deft_version` field\n- ⊗ Explore codebase before Phase 1 questions\n- ⊗ Read framework files before first question\n- ⊗ Batch multiple questions into one message — ask one at a time, interview style\n- ⊗ Ask jargon-heavy questions to non-technical users\n- ⊗ Ask about things inferable from codebase (Phase 2+)\n- ⊗ Skip phases without asking\n- ⊗ Generate files without confirming content\n- ⊗ Present choices through a host UI that replaces the canonical numbers with alphabetic affordances or unlabeled buttons\n- ⊗ Resolve paths relative to the skill file, AGENTS.md, or framework directory instead of the user's pwd at skill entry\n- ⊗ Generate an authoritative PRD.md — PRD.md is a read-only export via `task prd:render`, never a source of truth\n- ⊗ Skip the Returning-user re-entry / Revisit experimental rules path when USER.md exists and the operator entered setup to change experimental meta (#46)\n- ⊗ Clobber Personal or Defaults while toggling Experimental Rules (#46)\n- ⊗ Invent a full `deft config` verb family for experimental meta when setup re-entry suffices (#46)\n",
266
+ "body": "# Deft Directive Setup\n\nAgent-driven alternative to `.deft/core/run bootstrap && .deft/core/run project && .deft/core/run spec`.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.\n\n## When to Use\n\n- User says \"set up deft\", \"configure deft\", or \"bootstrap my project\"\n- User asks to create USER.md, PROJECT-DEFINITION.xbrief.json, or a specification\n- User clones a deft-enabled repo for the first time with no config\n- User says \"revisit experimental rules\", \"toggle experimental meta\", \"enable SOUL\", \"disable morals\", or wants to change Experimental Rules after bootstrap (#46)\n\n## Opt-out flag (`.no-deft-directive`) (#2926)\n\n! Before Pre-Cutover Detection Guard, Phase 1, or any install/setup step, check the **project root** for `.no-deft-directive` (exact lowercase name; presence = flag; empty or short `#` comment OK).\n\n| Condition | Action |\n|-----------|--------|\n| Flag **present** | Stop. Tell the human: \"Directive disabled via `.no-deft-directive`\". ⊗ Offer install, session ritual, or setup interview. |\n| Flag **absent**, no Directive deposit (`.deft/core`) | ? Ask whether to use Directive. On **no** → create root `.no-deft-directive` (optional one-line rationale) and stop. On **yes** → continue setup and ⊗ create the flag. |\n| Operator says **stop using DD** | Create `.no-deft-directive`. ⊗ Auto-delete `.deft/` (explicit cleanup only). |\n| Operator says **start using DD** | Remove `.no-deft-directive` and ensure install (`directive init` / deposit). |\n\n! Flag is **root-only** (workspace root opened). Nested monorepo package roots are out of scope for v1.\n! Flag **wins locally** over trusted-org / product-signal force-on (v1).\n! Flag + deposit = inconsistent: warn loudly; doctor diagnoses; do not silently refresh. See `content/docs/no-deft-directive.md`.\n\n## Consumer-first default (#1813)\n\n! Assume the operator is **using Deft in their project** (consumer path). Proceed directly to the Pre-Cutover Detection Guard and Phase 1 — do NOT open with a contributor-vs-consumer fork.\n\n~ The overwhelming majority of setup sessions are consumer installs; contributor onboarding is a separate, opt-in path (see below).\n\n## Contributor / framework-maintainer path (secondary)\n\n? Only enter this branch when the user **explicitly** says they are working on Deft itself (framework source checkout, `deftai/directive` clone, or maintainer tooling).\n\nWhen that happens:\n\n1. ! Tell the user: \"Contributor setup lives in [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) and this repo's root [`AGENTS.md`](../../../AGENTS.md). Use the maintainer installer: `deft-install --yes --upgrade --maintainer --repo-root . --json`.\"\n2. ⊗ Continue the consumer USER.md / PROJECT-DEFINITION interview — the maintainer path does not use the first-session consumer flow.\n3. **Stop here** unless the user explicitly asks to continue with consumer setup anyway.\n\n## Pre-Cutover Detection Guard\n\n! Before proceeding with any setup phase, detect whether the project uses the pre-v0.20 document model and redirect to migration if so.\n\n### Detection Criteria\n\nA project is **pre-cutover** if ANY of the following are true. When in doubt, run `task verify:pre-cutover` (the deterministic helper).\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 (same one-release-cycle grace window).\n3. `xbrief/specification.xbrief.json` exists but the lifecycle folders (`xbrief/proposed/`, `xbrief/pending/`, `xbrief/active/`, `xbrief/completed/`, `xbrief/cancelled/`) do NOT exist\n\n### Action on Detection\n\n! If pre-cutover state is detected, **stop immediately** and display an actionable message pointing at the frozen-release migration path (#2068):\n\n> \"This project uses the pre-v0.20 document model. Current npm releases no longer ship in-product `task migrate:vbrief`. Follow UPGRADING.md § Frozen pre-v0.20 document-model migration: pin framework v0.59.0 (frozen Go installer or git tag), install Python 3.11+ and uv, run `task migrate:vbrief` once from that payload, then upgrade to current npm.\"\n\n! Include specific details about what was detected:\n\n- Missing lifecycle folders: \"Create lifecycle folders via the frozen-release migrator on v0.59.0, or manually add `xbrief/{proposed,pending,active,completed,cancelled}/` after migrating narratives\"\n- `SPECIFICATION.md` with real content: \"SPECIFICATION.md contains non-redirect content — migrate on pinned v0.59.0 before upgrading to current npm\"\n- `PROJECT.md` with real content: \"PROJECT.md contains non-redirect content — migrate on pinned v0.59.0 before upgrading to current npm\"\n- Missing `PROJECT-DEFINITION.xbrief.json`: \"Run `task project:render` after document-model migration completes\"\n\n### Preflight (optional diagnostic)\n\n~ Run `task migrate:preflight` to confirm pre-cutover state and print the frozen-release guidance. It does **not** run migration.\n\n⊗ Offer to run `task migrate:vbrief` from the current npm deposit — the migrator is not bundled on current releases (#2068).\n⊗ Proceed with setup phases when pre-cutover artifacts are detected — always redirect to the frozen migration path first.\n⊗ Silently ignore pre-cutover artifacts — the user must be informed with an actionable command to fix the state.\n\n### Greenfield Projects (No Migration Needed)\n\n! For new projects (no existing `SPECIFICATION.md`, `PROJECT.md`, or `xbrief/specification.xbrief.json`), the guard passes silently and setup proceeds normally.\n\n! Greenfield setup creates the full xBRIEF-centric structure from scratch:\n\n1. `./xbrief/` directory with all 5 lifecycle subdirectories: `proposed/`, `pending/`, `active/`, `completed/`, `cancelled/`\n2. `./xbrief/PROJECT-DEFINITION.xbrief.json` generated from Phase 2 interview results\n3. First scope xBRIEF created in `proposed/` or `pending/` depending on Phase 3 interview outcome\n\n~ This is already handled by Phase 2 Output Path (creates `./xbrief/` and lifecycle subfolders) and Phase 3 Output (creates scope xBRIEFs in lifecycle folders). The guard ensures migrating projects are redirected before reaching these phases.\n\n### Migration safety flags (frozen v0.59.0 release only)\n\nWhen guiding an operator through migration on the pinned release, mention the migrator safety affordances (#497, #506 D7):\n\n- **`task migrate:vbrief -- --dry-run` (preview)** on v0.59.0\n- **Dirty-tree guard** — migrator refuses when the working tree is dirty unless `--force`\n- **`task migrate:vbrief -- --rollback`** on v0.59.0 to restore `.premigrate.*` backups\n\n⊗ Offer in-product migration from a current npm deposit — use the frozen path (#2068).\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (Phase 1 depth question, Phase 2 project type / deployment / language / strategy / branching gates, Phase 3 onboarding question, end-of-phase transition prompts, post-interview confirmation 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 (re-asks original question, says `resume`/`continue`, or re-issues prior selection). Implicit resumption is forbidden. Fallback chat replies MUST map only to the displayed number or exact displayed option text; do not infer from alphabetic host affordances.\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- ! Create parent directories as needed when writing USER.md\n- ~ `$DEFT_PROJECT_PATH` overrides the default project config path (`./xbrief/PROJECT-DEFINITION.xbrief.json`) if set\n\n## Agent Behavior\n\n**Flow:**\n- ! Start asking immediately — everything you need is in THIS file\n- ⊗ Explore the codebase, read framework files, or gather context before asking\n- ? Read `deft/main.md` or language files LATER when generating output\n\n**Interaction:**\n- ~ Use structured question tools only when their visible option labels preserve the canonical numbers (for example, `1. Yes`) and their return value is the numeric selection or exact displayed option text.\n- ! Fall back to the numbered chat menu when the host UI may replace numbers with alphabetic affordances, unlabeled buttons, or any other non-canonical choice labels.\n- ⊗ Infer deterministic answers from host-added letters or shortcuts unless those letters were actually displayed in the canonical menu labels.\n\n**Defaults:**\n- ! Communicate that deft ships with best-in-class standards for 20+ languages\n- ! Frame setup as \"tell me your overrides\" — not \"configure everything\"\n- ~ \"Deft has solid opinions on how code should be written and tested — I just need a few things about you and your project.\"\n\n**Adapt to Technical Level:**\n- ! First question gauges whether user is technical or non-technical\n- ! Technical user: ask about languages, strategy, coverage directly — they'll have opinions\n- ! Non-technical user: skip jargon, use sensible defaults, ask about what they're building not how\n- ⊗ Ask non-technical users about coverage thresholds, strategies, or framework choices\n\n## Available Languages\n\nC, C++, C#, Dart, Delphi, Elixir, Go, Java, JavaScript, Julia, Kotlin,\nOffice.js (Excel JavaScript API), Python, R, Rust, SQL, Swift, TypeScript,\nVBA (Excel macros), VHDL, Visual Basic (.NET), Zig, 6502-DASM\n\n- ? Read `deft/languages/{name}.md` when generating output — not before asking\n\n## Available Strategies\n\n~ When presenting strategies to the user, always use this numbered list format (not a plain table).\n~ Always include the chaining note below the list.\n! Always show the FULL strategy list at every chaining gate — never remove a strategy because it was previously run.\n~ If a strategy has been run already, indicate it with a note e.g. `(run 1x)` but keep it selectable.\n\n1. **interview** ★ (recommended) — Structured interview with sizing gate: Light or Full path\n2. **yolo** — Auto-pilot interview — Johnbot picks all recommended options\n3. **map** — Analyze existing codebase conventions before adding features\n4. **discuss** — Front-load decisions and alignment before planning\n5. **probe** — Adversarially stress-test the plan; surface assumptions, edge cases, and risks before spec\n6. **research** — Investigate the domain before planning\n7. **speckit** — Five-phase spec-driven workflow for large/complex projects\n\n> 💡 Strategies can be chained — after one completes, you'll be asked if you want to run another.\n\n---\n\n## Phase 1 — User Preferences (USER.md)\n\n**Goal:** Personal preferences file with two sections:\n- **Personal** — always wins over everything (name, custom rules)\n- **Defaults** — fallback values that PROJECT-DEFINITION.xbrief.json can override (strategy, coverage)\n\n- ~ Skip if USER.md exists at the platform-appropriate path (see Platform Detection) and user doesn't want to overwrite\n- ⊗ Scan filesystem beyond checking that one path\n\n### USER.md Freshness Detection\n\n! When an existing USER.md is found (returning user), check its `deft_version` field before skipping Phase 1:\n\n1. ! If `deft_version` is **missing**: the USER.md predates versioning -- treat as stale\n2. ! If `deft_version` is present but **differs from the current framework version** (0.20.0): check whether any expected fields are missing from the USER.md\n3. ! If fields are missing: query the user for each missing field individually -- do NOT re-run the full Phase 1 interview\n4. ! After completing any field queries (even if none were needed), write the current `deft_version` (0.20.0) to USER.md\n5. ~ If `deft_version` matches the current version and all expected fields are present: USER.md is fresh — do **not** re-run Phase 1. ! Still offer the **Returning-user re-entry** menu below so the operator can revisit Experimental Rules or continue to Phase 2 without a full re-interview (#46).\n\nExpected USER.md fields: **Name**, **Custom Rules**, **Default Strategy**, and optionally **Coverage** and **Experimental Rules**.\n\n⊗ Re-run the full Phase 1 interview when only individual fields are missing from a stale USER.md -- query missing fields individually instead.\n\n### Returning-user re-entry (#46)\n\n! When USER.md already exists (fresh or after individual missing-field fill), present a deterministic numbered menu before assuming Phase 1 is \"done and silent\":\n\n> \"USER.md is in place. What next?\"\n> 1. Continue to Phase 2 (project configuration) ★ (recommended when project config is still missing)\n> 2. **Revisit experimental rules** — enable/disable SOUL / morals / code-field without hand-editing schema\n> 3. Not now (exit setup)\n> 4. Discuss\n> 5. Back\n\n- ! Final two numbered options MUST be `Discuss` and `Back` per [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md)\n- ! On option 2, enter **Revisit experimental rules** (next section) — not a full Phase 1 re-interview\n- ⊗ Silently skip past a complete USER.md with no re-entry offer when the operator entered setup (or asked to configure preferences)\n- ⊗ Invent a `deft config` / `task config:*` verb family for this slice — setup skill re-entry is the product surface (#46)\n\n### Interview Rules\n\n! This phase follows the deterministic interview loop defined in `skills/deft-directive-interview/SKILL.md`. The core rules (one question per turn, numbered options with stated default, explicit \"other\" escape, depth gate, default acceptance, confirmation gate, structured handoff) apply here. Key points repeated for emphasis:\n\n! **Each message you send MUST contain exactly ONE question.** This is the most\nimportant rule in this file. After the user answers, send the NEXT question in\na new message. Repeat until all questions for their track are answered.\n\n- ⊗ Include two or more questions in the same message under any circumstances\n- ⊗ List upcoming questions — only show the current one\n- ~ Provide numbered answer options with an \"other\" choice where appropriate\n- ! Mark which option is RECOMMENDED when showing choices\n- ~ Use structured question tools only when visible option labels preserve the canonical numbers and returns map to numeric selections or exact displayed option text.\n\n### Question Sequence\n\n**Step 0 — Opening (all users):**\nAsk: \"How deep do you want to go?\"\n 1. I'm technical — ask me everything\n 2. I have some opinions but keep it simple\n 3. Just pick good defaults — I care about the product, not the tools\n\nWait for answer. Then follow the track below.\n\n**Track 1 (technical) — 7 steps:**\n- Step 1: Ask their name\n- Step 2: Ask strategy preference (show Available Strategies numbered list from the Available Strategies section, with descriptions and recommended marker; fallback — projects can override)\n- Step 3: Ask coverage threshold (default 85%; fallback — projects can override)\n- Step 4: Ask for custom rules — if user has rules, collect them one per line (empty line to finish); if none, skip\n- Step 5a: Present SOUL.md and ask whether to include it (default: yes):\n > **SOUL.md** — Results-first agent persona (inspired by Winston Wolf). Enforces assess-before-acting,\n > finish-what-you-start, right-tool-for-the-job, and play-the-long-game. Keeps the AI decisive and\n > concise. Includes a named persona ('Vinston') — drop if you prefer to define your own agent personality.\n > Include SOUL.md? (Y/n)\n- Step 5b: Present morals.md and ask whether to include it (default: yes):\n > **morals.md** — Epistemic honesty rules. No presenting speculation as fact, label unverified claims,\n > self-correct when wrong. Foundational trust rules for any AI agent. Strongly recommended.\n > Include morals.md? (Y/n)\n- Step 5c: Present code-field.md and ask whether to include it (default: yes):\n > **code-field.md** — Pre-code assumption protocol. Requires stating assumptions and naming failure modes\n > before writing a single line. Fights the 'it compiles, ship it' instinct. Based on NeoVertex1 context-field.\n > Include code-field.md? (Y/n)\n\n**Track 2 (middle ground) — 2 steps:**\n- Step 1: Ask their name\n- Step 2: Ask for custom rules — if user has rules, collect them one per line (empty line to finish); if none, skip\n- Set defaults without asking: strategy = \"interview\", coverage = 85%, all meta-guidelines included\n\n**Track 3 (non-technical) — 2 steps:**\n- Step 1: Ask their name\n- Step 2: Ask what they're building (brief description — used for PROJECT-DEFINITION.xbrief.json later)\n- Set defaults: strategy = \"interview\", coverage = 85%, all meta-guidelines included\n\n### Output Path\n\nResolve using Platform Detection above. Write to the platform-appropriate path\n(or `$DEFT_USER_PATH` if set). Create parent directories as needed.\n\n### Template\n\n```markdown\n# User Preferences\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.\n\n**deft_version**: 0.20.0\n\n## Personal (always wins)\n\nSettings in this section have HIGHEST precedence — override all other deft rules,\nincluding PROJECT-DEFINITION.xbrief.json.\n\n**Name**: Address the user as: **{name}**\n\n**Custom Rules**:\n{custom rules or \"No custom rules defined yet.\"}\n\n## Defaults (fallback)\n\nSettings in this section are fallback defaults. PROJECT-DEFINITION.xbrief.json overrides these\nfor project-scoped settings (strategy, coverage).\n\n**Default Strategy**: [{strategy name}](../strategies/{strategy-file}.md)\n\n{If coverage != 85: \"**Coverage**: ! ≥{N}% test coverage\"}\n\n{If any experimental rules selected:\n\"## Experimental Rules\n\n{one line per selected rule, e.g.:\n- ! Use meta/SOUL.md for strategic context and purpose-driven guidance\n- ! Use meta/morals.md for ethical AI development principles\n- ~ Use meta/code-field.md for advanced architecture patterns}\"}\n\n---\n\n**Note**: Edit this file anytime to update your preferences.\n**See**: [../../main.md](../../../main.md) for framework defaults.\n```\n\n### Then\n\n- ! Emit a structured-tool question asking whether to continue to Phase 2 (project configuration) only when the host preserves numeric labels; otherwise emit the deterministic numbered menu in chat. Options: `1. Yes (continue)`, `2. Not now (exit setup)`, `3. Discuss`, `4. Back (revisit previous phase)`. The numeric labels MUST remain visible and be returned as numeric selections or exact displayed option text.\n- ⊗ Ask the phase-transition question as unnumbered conversational prose or through a structured UI that hides the canonical numeric labels -- it is a deterministic menu and MUST preserve visible numbers (#478, #1563).\n\n---\n\n## Revisit experimental rules (#46)\n\n**Goal:** Guided enable/disable of USER.md **Experimental Rules** entries that *reference* framework deposit meta files (`meta/SOUL.md`, `meta/morals.md`, `meta/code-field.md`). This is a post-bootstrap return path — not Phase 1 bootstrap, not a general preferences UI, and not an editor for framework meta file bodies.\n\n### When to enter\n\n- Returning-user re-entry option **Revisit experimental rules**\n- Direct user ask: \"revisit experimental rules\", \"toggle experimental meta\", \"turn on SOUL\", \"disable code-field\", etc.\n- USER.md exists and is complete enough to edit (Name present); missing non-meta fields still use Freshness Detection individual queries first\n\n### Out of scope\n\n- ⊗ General preferences UI / rewriting Personal or Defaults sections as part of this path\n- ⊗ Editing framework `meta/*.md` content (deposit owns SOUL / morals / code-field bodies; `directive update` refreshes deposit)\n- ⊗ Deposit layout changes\n- ⊗ Inventing a full `deft config` mega-surface or new `task config:*` verb family for this slice\n- ⊗ Re-building USER.md bootstrap / non-overwrite semantics\n- ⊗ Treating Experimental Rules lines as project-local copies of meta files — they are **references** only\n\n### Flow\n\n! **Each message MUST contain exactly ONE question** (same interview rule as Phase 1).\n\n1. ! Resolve USER.md via Platform Detection (`$DEFT_USER_PATH` → platform path). Read the file as **UTF-8**.\n2. ! Parse current Experimental Rules state (on/off) for the three paths:\n - `meta/SOUL.md`\n - `meta/morals.md`\n - `meta/code-field.md`\n - Detection: any line containing that path counts as **on** (custom wording still counts).\n3. ! Show a **current state** summary (table or short list), for example:\n\n | Entry | State | Role |\n |-------|-------|------|\n | SOUL.md | on/off | Results-first agent persona |\n | morals.md | on/off | Epistemic honesty |\n | code-field.md | on/off | Pre-code assumption protocol |\n\n4. ! Ask which entry to change with a deterministic numbered menu (one question). Options MUST include each of the three entries as toggle targets, plus **Done (save)** / **Done (discard)**, and final two options `Discuss` and `Back`:\n\n > \"Toggle which experimental meta entry? (current state shown above)\"\n > 1. SOUL.md — currently {on|off}\n > 2. morals.md — currently {on|off}\n > 3. code-field.md — currently {on|off}\n > 4. Done — save changes\n > 5. Done — discard changes\n > 6. Discuss\n > 7. Back\n\n5. ! When the user picks an entry (1–3), optionally show the short Phase 1 explainer (steps **5a–5c** copy below), then confirm the new on/off value with a Y/n or numbered keep/flip menu. Update the **in-memory** desired state; do not write yet. Return to the toggle menu (step 4) until Done.\n6. ! On **Done — save**: show a confirmation summary of the three final on/off values and require explicit affirmative (`yes` / `confirmed` / `approve`) before write — same Post-Interview Confirmation Gate strictness.\n7. ! On **Done — discard** or **Back** without save: leave USER.md unchanged and return to the Returning-user re-entry menu (or exit if invoked directly).\n\n### Explainers (reuse Phase 1 steps 5a–5c)\n\n- **SOUL.md** — Results-first agent persona (inspired by Winston Wolf). Enforces assess-before-acting, finish-what-you-start, right-tool-for-the-job, and play-the-long-game. Keeps the AI decisive and concise. Includes a named persona ('Vinston') — drop if you prefer to define your own agent personality.\n- **morals.md** — Epistemic honesty rules. No presenting speculation as fact, label unverified claims, self-correct when wrong. Foundational trust rules for any AI agent. Strongly recommended.\n- **code-field.md** — Pre-code assumption protocol. Requires stating assumptions and naming failure modes before writing a single line. Fights the 'it compiles, ship it' instinct. Based on NeoVertex1 context-field.\n\n### Safe write rules (non-clobber)\n\n! When persisting toggles to USER.md:\n\n1. ! Write **UTF-8** (no BOM). Create parent directories only if the resolved path's parent is missing — never relocate USER.md.\n2. ! Change **only** the `## Experimental Rules` section (add the section if enabling when absent; remove the section when all three are off and no custom bullets remain).\n3. ! Canonical enable lines (match Phase 1 template):\n - `- ! Use meta/SOUL.md for strategic context and purpose-driven guidance`\n - `- ! Use meta/morals.md for ethical AI development principles`\n - `- ~ Use meta/code-field.md for advanced architecture patterns`\n4. ! Disable = remove lines that mention that path. Preserve any **custom** non-meta bullets under Experimental Rules.\n5. ! **Personal** and **Defaults** section bodies MUST remain byte-identical to the pre-write file (non-clobber).\n6. ~ Prefer the pure helper `applyExperimentalRulesState` / `setExperimentalRule` from `@deftai/directive-core` `userConfig` (`packages/core/src/user-config/experimental-rules.ts`) when the package is importable (framework checkout, tests, or a thin local script). When editing by hand as an agent, apply the same rules: section-only edit, UTF-8, path-based match, canonical enable lines.\n7. ! After write, re-read USER.md and show the final on/off state to the user.\n\n⊗ Rewrite the whole USER.md from the Phase 1 template when only Experimental Rules changed\n⊗ Clobber or reformat **Personal** / **Defaults** content while toggling experimental meta\n⊗ Hand-edit framework `meta/SOUL.md`, `meta/morals.md`, or `meta/code-field.md` bodies as part of this path\n⊗ Invent `deft config` / `task config:experimental-*` for this product slice when setup re-entry suffices\n\n### Then\n\n- ! After a successful save (or discard), re-offer the Returning-user re-entry menu (Continue to Phase 2 / Revisit again / Exit / Discuss / Back) unless the user asked only for the toggle and is done.\n- ~ If Phase 2 is already complete, prefer Exit over Continue unless the user wants project reconfiguration.\n\n## Phase 2 — Project Configuration (PROJECT-DEFINITION.xbrief.json)\n\n**Goal:** Project-specific configuration — tech stack, type, quality standards — written as a xBRIEF file at `./xbrief/PROJECT-DEFINITION.xbrief.json`.\n\n! **Path Resolution Anchor**: Resolve ALL paths relative to the user's working directory (pwd) at skill entry -- never relative to the skill file location, AGENTS.md location, or any framework directory (e.g. `./deft/`). When deft is cloned as a subdirectory, the skill file lives inside the clone but all project artifacts (`./xbrief/PROJECT-DEFINITION.xbrief.json`, build files, etc.) must be resolved from the user's pwd.\n\n- ~ Skip if `./xbrief/PROJECT-DEFINITION.xbrief.json` exists (or `$DEFT_PROJECT_PATH` if set) and user doesn't want to replace\n- ⊗ Count `./deft/PROJECT-DEFINITION.xbrief.json` or `./deft/core/project.md` as the user's project config — those are framework-internal\n\n### Inference\n\n- ! Before asking, infer from codebase — look for `package.json`, `go.mod`, `requirements.txt`, `Cargo.toml`, `pyproject.toml`, `*.csproj`\n- ! Use inferences to pre-fill answers and confirm — don't ask blind\n- ⊗ Look inside `./deft/` for build files (`go.mod`, `package.json`, `pyproject.toml`, `Cargo.toml`, `*.csproj`, etc.) — those are framework-internal. Only inspect files at the project root and its non-`deft` subdirectories.\n- ⊗ Run git commands inside `./deft/` to determine project identity — that directory is the framework repo, not the user's project.\n- ~ If no build files are found at the project root, default the project name to the current directory name and ask for confirmation.\n\n### Track Detection\n\n! If Phase 1 was skipped (USER.md already existed), the user's track is unknown.\nBefore asking any Phase 2 questions, ask the depth question:\n\n> \"How deep do you want to go?\"\n> 1. I'm technical — ask me everything\n> 2. I have some opinions but keep it simple\n> 3. Just pick good defaults — I care about the product, not the tools\n\nWait for answer. Then follow the corresponding track in the Question Sequence below.\n\n⊗ Assume Track 1 (technical) because USER.md exists or contains strategy/coverage fields.\n⊗ Infer the track from USER.md content — always ask.\n\n### Defaults in Agentic Mode\n\n! When a question has a USER.md default, phrase it as:\n> \"{Field}: **{value}** from USER.md — keep this, or enter a different value?\"\n\n! Accept any affirmative response (\"keep\", \"yes\", \"same\", \"default\", ✓) as confirmation to use the default.\n⊗ Phrase defaults as \"press Enter to keep\" — there is no Enter in conversational mode.\n\n### Interview Rules (same as Phase 1)\n\n! **Each message MUST contain exactly ONE question.** The Phase 1 interview rules\napply here too. Do not combine questions. See `skills/deft-directive-interview/SKILL.md` for the canonical deterministic interview loop.\n\n### Question Sequence\n\n**Track 1 (technical) — 8 steps:**\n- Step 1: Ask project name (infer from build files or directory name, confirm)\n- Step 2: Ask project type (CLI, TUI, Desktop App, REST API, Web App, Library, other)\n- Step 3: Ask deployment platform:\n 1. Cross-platform (Linux / macOS / Windows)\n 2. Windows-native\n 3. macOS-native\n 4. Linux / Unix\n 5. Embedded / low-resource\n 6. Web / Cloud\n 7. Mobile (iOS / Android)\n 8. Other / not sure\n- Step 4: Ask languages — show a filtered shortlist (3–4 recommendations) based on project type + platform. If codebase markers exist (`go.mod`, `pyproject.toml`, etc.), skip and confirm: \"Detected {lang} — correct?\"\n - If user selects \"Other\": show remaining plausible languages for the type+platform context (Tier 2)\n - If still not found: free text input (Tier 3)\n - If entered language has no deft `languages/{lang}.md` standards file, warn: \"deft doesn't have a standards file for {lang} yet — general defaults will be used. Continue?\"\n- Step 5: Ask tech stack (frameworks, libraries)\n- Step 6: Ask strategy (default to USER.md Defaults; ask if this project needs different — show Available Strategies numbered list with descriptions and recommended marker)\n- Step 7: Ask coverage (default to USER.md Defaults; ask if this project needs different)\n- Step 8: Ask for project-specific rules (optional, same one-per-line format as Phase 1 custom rules)\n- Step 9: Ask branching preference (typed `plan.policy.allowDirectCommitsToMaster` flag per #746):\n\n ! Render this as a deterministic numbered menu. Default `1. Branch-based`. Final two options MUST be `Discuss` and `Back` per [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md):\n\n > \"Do you prefer branch-based workflow (create a feature branch for every change) or\n > trunk-based (commit directly to master)? Branch-based is the default and recommended\n > for teams; trunk-based is common for solo projects.\"\n > 1. Branch-based ★ (recommended -- default; enforces feature branches via the deft branch-protection policy)\n > 2. Trunk-based (direct commits to master) -- see capability-cost disclosure below\n > 3. Discuss\n > 4. Back\n\n ! **Capability-cost disclosure (#746):** When the user picks option 2 (trunk-based), the agent MUST present the capability-cost disclosure verbatim BEFORE writing the typed flag, then re-prompt for explicit confirmation:\n\n > \"Capability-cost disclosure -- enabling direct commits to the default branch turns OFF the deft branch-protection policy. The pre-commit + pre-push hooks will no longer block default-branch commits, `task verify:branch` will pass on the default branch, and the skill-level guards in deft-directive-{swarm,review-cycle,pre-pr,release} will not halt for default-branch work. The change is reversible (`task policy:enforce-branches`) and is recorded to meta/policy-changes.log for auditability. The CI sanity check (head_ref != base_ref) remains independent and will continue to flag master->master PRs. Are you sure?\"\n > 1. Yes, opt out -- write `plan.policy.allowDirectCommitsToMaster = true`\n > 2. No, keep branch-protection enforced -- write `plan.policy.allowDirectCommitsToMaster = false`\n > 3. Discuss\n > 4. Back\n\n ! Default to option 2 (enforce). Explicit affirmative on option 1 is required to opt out -- a broad `proceed` does NOT satisfy this gate. The same affirmative-only rule applies as in `/deft:change` (`yes`, `confirmed`, `approve`).\n\n ! Write the answer to `plan.policy.allowDirectCommitsToMaster` (typed boolean) on the PROJECT-DEFINITION xBRIEF. Default `false` (enforce branches) when the user picks option 2 OR omits the question entirely. Writing this typed surface is what the framework reads going forward; agents MUST NOT write the legacy free-form `Allow direct commits to master:` narrative key (#746 part A migrates the legacy narrative away).\n\n ! **Re-running the interview detects the existing flag (#746 part G2):** If `xbrief/PROJECT-DEFINITION.xbrief.json` already exists and has `plan.policy.allowDirectCommitsToMaster` set, the interview MUST surface the current value (e.g. \"Current setting: `allowDirectCommitsToMaster=false` (branch-protection ON)\") and ask whether to keep it or change it before re-prompting. Do not silently overwrite an existing typed value.\n\n ! **Slash-command alternatives (#746 part G2):** Once the project is set up, the typed flag can also be flipped via slash commands wrapping `task policy:*`:\n - `/deft:policy:show` -- display the current resolved policy and source\n - `/deft:policy:enforce-branches` -- set `allowDirectCommitsToMaster=false`\n - `/deft:policy:allow-direct-commits` -- set `allowDirectCommitsToMaster=true` (requires `--confirm` to apply)\n\n Each transition is recorded to `meta/policy-changes.log` for auditability.\n\n**Track 2 (middle ground) — 4 steps:**\n- Step 1: Ask project name (infer from build files or directory name, confirm)\n- Step 2: Ask project type (CLI, TUI, Desktop App, REST API, Web App, Library, other)\n- Step 3: Ask languages (show detected, confirm or adjust; if none detected, infer from type and ask)\n- Step 4: Ask strategy (default to USER.md Defaults; ask if this project needs different — show Available Strategies numbered list with descriptions and recommended marker)\n- Default coverage to USER.md Defaults without asking\n\n**Track 3 (non-technical) — 1 step:**\n- Step 1: Present summary of inferences: \"Based on your project: {name} ({type}), built with {stack}. Look right?\"\n- ⊗ Ask about strategy or coverage — use Phase 1 defaults\n\n### Output Path\n\n`./xbrief/PROJECT-DEFINITION.xbrief.json` (or `$DEFT_PROJECT_PATH` if set). Create `./xbrief/` directory and lifecycle subfolders (`proposed/`, `pending/`, `active/`, `completed/`, `cancelled/`) if they don't exist.\n\n### GitHub PR Template Scaffolding (#531)\n\n! Before writing `PROJECT-DEFINITION.xbrief.json`, offer to scaffold a default GitHub PR template so downstream skills (`deft-directive-refinement` Pre-Flight, `deft-directive-pre-pr`) can satisfy their `.github/PULL_REQUEST_TEMPLATE.md` checks without blocking.\n\n1. ! Ask the user with a deterministic numbered menu: \"Create a default GitHub PR template at `.github/PULL_REQUEST_TEMPLATE.md`?\" Options: `1. Yes`, `2. No`, `3. Discuss`, `4. Back`. Use a structured question tool only if those numeric labels remain visible and are returned as numeric selections or exact displayed option text.\n2. ! If the user accepts AND `.github/PULL_REQUEST_TEMPLATE.md` does NOT already exist: copy `templates/PULL_REQUEST_TEMPLATE.md` (shipped with deft) to `./.github/PULL_REQUEST_TEMPLATE.md` in the consumer project. Create `.github/` if it does not exist.\n3. ! If the file already exists, do NOT overwrite it — report that it is present and continue.\n4. ~ If the user declines, note that `deft-directive-refinement` Pre-Flight will offer to scaffold later when needed.\n\n⊗ Overwrite an existing `.github/PULL_REQUEST_TEMPLATE.md` without explicit user approval.\n\n### Headless Coverage Warning — display-bound GUI entry points (#1027)\n\n! The trigger is a **display-bound GUI event loop** (pygame, tkinter, PyQt/PySide, Kivy, Electron) that cannot run without a real display — typically a **Desktop App** project type, or a TUI that embeds such a GUI. Terminal-UI frameworks (textual, urwid, blessed, ncurses) run in the terminal and DO support headless testing (e.g. textual's `App.run_async()` + `Pilot`), so a standard TUI is NOT in scope — do not omit its coverage. The concrete commands below assume a **Python** GUI stack (pygame/tkinter); the same \"omit the un-runnable loop, test the logic\" principle applies to non-Python desktop stacks (Electron/JS, .NET/WPF, Qt/C++) using that language's own headless-test and coverage-exclusion tooling. When the Phase 2 project type resolves to a display-bound GUI project, warn the user BEFORE writing `PROJECT-DEFINITION.xbrief.json` (adapt the wording to the project's language):\n\n> \"Heads up: pygame/tkinter event loops can't be tested headlessly, so the display-bound entry point (e.g. `src/ui.py`) reports near-zero coverage and drags the overall percentage below the 85% threshold. I recommend excluding the UI entry point from coverage measurement and keeping it thin — push testable logic (state, scoring, input handling) into separate modules.\"\n\n! When scaffolding or advising on `pyproject.toml` for a display-bound GUI project, add the display-bound entry point to `[tool.coverage.run] omit` so `task check` measures logic modules only:\n\n```toml\n[tool.coverage.run]\nomit = [\n \"*/tests/*\",\n \"*/venv/*\",\n \"*/.venv/*\",\n \"src/ui.py\", # display-bound pygame/tkinter event loop -- cannot run headlessly (#1027)\n]\n```\n\n- ! Keep the omit narrow — exclude only the event-loop shell, never a module that also holds business logic. If logic and the loop are mixed, recommend refactoring the logic into a separate, fully-tested module first.\n- ~ For a Python project, point the user at `languages/python.md` (the `Headless GUI / event-loop testing` section under Patterns) for the headless-test pattern (`SDL_VIDEODRIVER=dummy`) and the full coverage-omit rationale; for a non-Python GUI stack, apply the same principle with that language's headless-test and coverage-exclusion tooling.\n- ⊗ Apply the omit to a headless-capable terminal-UI project (textual/urwid/blessed/ncurses) — those frameworks test headlessly, so omitting them hides measurable coverage, the opposite of the intended effect.\n- ⊗ Silently accept the default 85% coverage gate for a display-bound GUI project without surfacing the headless blind spot — the agent reports an inflated per-session coverage that collapses when the full `src/` is measured (the 2026-05-10 tic-tac-toe desktop-UI swarm recurrence).\n\n### Template\n\n! The output MUST conform to the canonical xBRIEF v0.8 schema (`xbrief/schemas/xbrief-core-0.8.schema.json`, strict `const: \"0.8\"`). See [`../../conventions/references.md`](../../conventions/references.md). Write-path default is **0.8 only** (#2971); legacy 0.6 remains read-accepted until `deft migrate:xbrief`.\n\n```json\n{\n \"xBRIEFInfo\": {\n \"version\": \"0.8\",\n \"author\": \"agent:deft-directive-setup\",\n \"description\": \"Project identity gestalt\",\n \"created\": \"{ISO-8601 timestamp}\"\n },\n \"plan\": {\n \"title\": \"{Project Name}\",\n \"status\": \"running\",\n \"narratives\": {\n \"Overview\": \"{Brief project description}\",\n \"TechStack\": \"{project type} using {languages} — {tech stack details}\",\n \"Strategy\": \"Use {strategy name} for this project\",\n \"Quality\": \"Run task check before every commit. Achieve >= {coverage}% coverage overall + per-module. Store secrets in secrets/ dir.\",\n \"ProjectRules\": \"{Any rules the user specified, or 'No project-specific rules defined.'}\",\n \"Branching\": \"{If trunk-based: 'Allow direct commits to master: true', else omit or 'Branch-based workflow (default)'}\",\n \"DeftVersion\": \"0.20.0\"\n },\n \"items\": []\n }\n}\n```\n\n- ! All `narratives` values MUST be plain strings — never objects or arrays\n- ! `items` starts empty — populated as scope xBRIEFs are created in lifecycle folders\n\n### Then\n\n- ! Emit a structured-tool question asking whether to continue to Phase 3 (specification) only when the host preserves numeric labels; otherwise emit the deterministic numbered menu in chat. Options: `1. Yes (continue)`, `2. Not now (exit setup)`, `3. Discuss`, `4. Back (revisit previous phase)`. The numeric labels MUST remain visible and be returned as numeric selections or exact displayed option text.\n- ⊗ Ask the phase-transition question as unnumbered conversational prose or through a structured UI that hides the canonical numeric labels -- it is a deterministic menu and MUST preserve visible numbers (#478, #1563).\n\n### Follow-up: triage onboarding (#1143)\n\n- ~ After Phase 2 writes `PROJECT-DEFINITION.xbrief.json`, recommend `task triage:welcome` to the user as the single chained command for picking up the v0.27 triage surface. The N3 ritual (#1143) is the consolidating onboarding step for the #1119 governance swarm verbs (`task triage:bootstrap` / `task triage:scope` / `plan.policy.wipCap` writes / `task scope:demote --batch` relief / `task triage:summary`); without it consumers must learn each verb individually from the v0.27 release notes.\n- ~ `task triage:welcome` is idempotent and detection-bound -- each phase emits an informational stderr line and skips when its precondition is already satisfied, so a re-run after a partial completion resumes cleanly. The destructive phases (subscription / `wipCap` writes, optional WIP-relief invocation) are gated by numbered-menu prompts per [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md). See [`../../UPGRADING.md`](../../UPGRADING.md) `## From v0.26.x -> v0.27` for the full walkthrough.\n### Consumer AGENTS always-pin recommendations (#2508)\n\n! After Phase 2 completes (or when closing a greenfield bootstrap), tell the consumer that process-critical directive skills should be named in their project's AGENTS.md **unmanaged header** when false-negative risk matters — full tier definitions: [`../../docs/skill-pin-policy.md`](../../docs/skill-pin-policy.md).\n~ Recommend the default consumer pin set for lifecycle work: `deft-directive-build` (implementation), `deft-directive-pre-pr` (before PR), `deft-directive-review-cycle` (bot review loop), and `deft-directive-swarm` when they plan parallel agents. Each is referenced by skill id + `.deft/core/.agents/skills/<id>/SKILL.md` path — not by pasting skill bodies.\n⊗ Recommend pinning entire `languages/`, `deployments/`, or other framework doc packs into AGENTS.md (#2508 anti-pattern).\n\n---\n\n## Phase 3 — Specification\n\n**Goal:** Generate an implementable spec using the strategy chosen in Phase 2, producing scope xBRIEFs in `xbrief/proposed/` and PROJECT-DEFINITION narratives for human approval — greenfield v0.20 does not create `specification.xbrief.json`.\n\n! **Path Resolution Anchor**: Same rule as Phase 2 -- resolve ALL paths relative to the user's pwd at skill entry, never relative to the skill file, AGENTS.md, or any framework directory.\n\n- ~ Skip if user already has scope xBRIEFs in `./xbrief/` they're happy with\n- ! Check `./xbrief/specification.xbrief.json` or `./xbrief/proposed/` for existing scope xBRIEFs\n- ⊗ Count ANY file inside `./deft/` as the project's spec — those are framework-internal\n (e.g. `deft/PROJECT.md`, `deft/specs/`, `deft/templates/`, `deft/core/project.md`\n are all part of the framework, NOT the user's project)\n\n### Onboarding Question\n\n! Before proceeding with the strategy gate, ask the onboarding question. Use the same add-scope / update / replace vocabulary as the Chaining Gate in [strategies/interview.md](../../strategies/interview.md#chaining-gate).\n\n**Brownfield detector** (same as Chaining Gate): `PROJECT-DEFINITION` exists (`./xbrief/` or legacy `./vbrief/`) **OR** any lifecycle folder (`proposed/`, `pending/`, `active/`, `completed/`, `cancelled/`) has scope records.\n\n> \"How should we treat this project's specification?\"\n> 1. **Add scope to this project** [default when brownfield] — load existing identity; skip greenfield \"what are we building?\"; emit one proposed scope; Preparatory Guard on write\n> 2. **Update project definition** — delta interview → Spec-Generating Guard → merge narratives into existing PROJECT-DEFINITION\n> 3. **Replace specification (scrap)** — only after explicit affirmative (`yes` / `confirmed`); then full new-spec path\n> 4. **Starting a new project specification** [default when greenfield] — proceed to the Strategy Gate below\n> 5. **Discuss** — explore these options before choosing\n> 6. **Back** — return to the previous setup question\n\n- ! Default based on repo state via the brownfield detector above (brownfield → Add scope; greenfield → Starting new)\n- ! Final two numbered options MUST be `Discuss` and `Back` per [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md)\n- ! If **Add scope**: skip the full interview, create a new scope xBRIEF in `./xbrief/proposed/` with the user's description, apply Preparatory Guard on write, then surface the Lifecycle Bridge + End-of-Phase-3 Export Prompt + handoff sections below (do not dead-end after the write)\n- ! If **Update project definition**: run a delta interview; apply Spec-Generating Guard against `./xbrief/PROJECT-DEFINITION.xbrief.json` (or legacy `./vbrief/PROJECT-DEFINITION.vbrief.json` if that is the existing identity); merge narratives (do not wholesale replace unless the user confirmed scrap)\n- ! If **Replace specification (scrap)**: require explicit `yes`/`confirmed`, then proceed to the Strategy Gate as a greenfield-style full path\n- ! If **Starting new**: proceed to the Strategy Gate below\n- ⊗ Treat brownfield repos as \"Starting new\" by default\n- ⊗ Accept vague confirmation (`proceed`, `ok`) for Replace/scrap\n- ⊗ Exit immediately after Add-scope write without the lifecycle bridge / export / handoff guidance\n\n### ⚠️ MANDATORY: Strategy Gate — Do This First\n\n! **STOP.** You MUST determine the correct strategy before doing anything else.\n\n1. ! Open `./xbrief/PROJECT-DEFINITION.xbrief.json` (the file written in Phase 2)\n2. ! Find the `narratives.Strategy` value\n3. ! Extract the strategy name from the narrative\n\n**Dispatch:**\n\n- **interview** (or default) → Continue to the Sizing Gate below ✅\n- **anything else** (discuss, yolo, speckit, research, brownfield, map, etc.) →\n 1. ! Read `deft/strategies/{strategy-name}.md` **right now, in this same turn**\n 2. ! Begin the strategy's workflow immediately — ask its first question\n 3. ! For `research`, the first question is the strategy's Scope Confirmation Gate (#1273); ask it and wait before any autonomous research begins.\n 4. ! For `research`, after the research artifact is written, surface the strategy's Then: Chaining Gate and wait for a user selection; do NOT create scope xBRIEFs from research output unless the user later chooses a spec-generating path; do NOT fall through to the interview output path after research.\n 5. ! **STOP reading this section** — do NOT use the interview process below\n\n- ⊗ Default to interview without reading PROJECT-DEFINITION.xbrief.json\n- ⊗ Continue reading below when PROJECT-DEFINITION.xbrief.json specifies a non-interview strategy\n- ⊗ Assume interview because the sections below describe the interview process\n- ⊗ Fabricate justification for using interview when the user chose a different strategy\n- ⊗ Announce the strategy choice and then stop — you must immediately read the file and start\n\n---\n\n*⬇️ Everything below applies ONLY to the interview strategy. If your strategy is anything else, STOP — follow your strategy file instead.*\n\n### Sizing Gate (interview and yolo strategies only)\n\n! After hearing what the user wants to build and their feature list, determine\nproject complexity per [strategies/interview.md](../../strategies/interview.md#sizing-gate).\n\n- ! Check `PROJECT-DEFINITION.xbrief.json` narratives for `Light` or `Full` — if declared, use that path\n- ! If not declared, propose a size and **ask the user to confirm in a dedicated message**\n- ! **Wait for the user's response** before asking any interview questions\n- ⊗ Combine the sizing proposal with the first interview question\n- ⊗ Proceed to interview questions before the user has confirmed the path\n\n**Light** (small/medium): Interview → `specification.xbrief.json` with slim narratives (Overview + Architecture) → scope xBRIEFs in `xbrief/proposed/`.\n**Full** (large/complex): Interview → rich narratives in `specification.xbrief.json` (user approval) → scope xBRIEFs with traceability.\n\n### Interview Process (interview strategy)\n\nPer [strategies/interview.md](../../strategies/interview.md#interview-rules-shared-by-both-paths):\n\n- ! Ask what to build and features first\n- ! Ask **ONE** focused, non-trivial question per step\n- ~ Provide numbered options with an \"other\" choice\n- ! Mark which option is RECOMMENDED\n- ⊗ Ask multiple questions at once\n- ⊗ Make assumptions without clarifying\n- ~ Use structured question tools for interview questions only when they preserve visible numeric option labels and return numeric selections or exact displayed option text; otherwise render the numbered menu in chat.\n\n**Question Areas:**\n- ! Missing decisions (language, framework, deployment)\n- ! Edge cases (errors, boundaries, failure modes)\n- ! Implementation details (architecture, patterns, libraries)\n- ! Requirements (performance, security, scalability)\n- ! UX/constraints (users, timeline, compatibility)\n- ! Tradeoffs (simplicity vs features, speed vs safety)\n\n**Non-Technical Users:**\n- ~ Adjust vocabulary: \"How do you want to store data?\" not \"What database engine?\"\n- ~ \"Will other apps talk to this?\" not \"REST or GraphQL?\"\n\n**Completion:**\n- ! Continue until little ambiguity remains\n- ! Spec must be comprehensive enough to implement\n\n### Output — Light Path\n\n1. ! Write `./xbrief/specification.xbrief.json` with `\"xBRIEFInfo\": { \"version\": \"0.8\" }`, `status: draft`, and slim narratives:\n - `Overview`: Brief project summary\n - `Architecture`: System design description\n2. ! Create scope xBRIEFs in `./xbrief/proposed/` for each identified work item\n - Each scope xBRIEF follows the `YYYY-MM-DD-descriptive-slug.xbrief.json` filename convention (slug rules in [`../../conventions/vbrief-filenames.md`](../../conventions/vbrief-filenames.md))\n - Each MUST use `\"xBRIEFInfo\": { \"version\": \"0.8\" }`\n - Each MUST include embedded Requirements (FR-N, NFR-N) in its `narrative`\n - Each task SHOULD reference which FR/NFR it implements via `narrative.Traces`\n - When the scope originates from a GitHub issue, include a `references` entry in the canonical form (see [`../../conventions/references.md`](../../conventions/references.md)):\n ```json\n \"references\": [\n {\n \"uri\": \"https://github.com/{owner}/{repo}/issues/{N}\",\n \"type\": \"x-xbrief/github-issue\",\n \"title\": \"Issue #{N}: {issue title}\"\n }\n ]\n ```\n3. ! Summarize decisions, ask user to review the xBRIEF narratives\n4. ! On approval, update `specification.xbrief.json` status to `approved`\n- ⊗ Create a separate PRD.md on the Light path\n- ⊗ Generate an authoritative PRD.md — if needed, users run `task prd:render`\n\n! The xBRIEF files MUST conform to `xbrief/schemas/xbrief-core-0.8.schema.json` (v0.8):\n\n- ! All `narratives` and `narrative` values MUST be plain strings — never objects or arrays\n- ! Nested children within a PlanItem use `items` (preferred field); `subItems` is the deprecated legacy alias kept for backward compatibility only\n- ⊗ Mix `items` and `subItems` on the same PlanItem — pick one (prefer `items`)\n- ⊗ Emit `\"version\": \"0.6\"` on any new write path — current engine write-default is `0.8` only (#2971)\n\n### Output — Full Path\n\n1. ! Write rich narratives to `./xbrief/specification.xbrief.json` with `\"xBRIEFInfo\": { \"version\": \"0.8\" }`, `plan.status: draft`, and these narrative keys:\n - `ProblemStatement`: What problem this project solves\n - `Goals`: High-level project goals\n - `UserStories`: User stories in standard format\n - `Requirements`: Structured requirements (FR-N: ..., NFR-N: ...)\n - `SuccessMetrics`: Measurable success criteria\n - `Architecture`: System design and technical architecture\n - `Overview`: Brief project summary\n2. ! **Human approval gate**: Present the xBRIEF draft narratives to the user for review — reviewing the `specification.xbrief.json` narratives IS the approval step (replaces the former PRD.md review). The user may request changes before approving.\n3. ! On approval, update `status` to `approved` and proceed to downstream generation\n4. ! Create scope xBRIEFs in `./xbrief/proposed/` with traceability to requirement IDs from the narratives\n- ! Scope xBRIEFs MUST trace tasks back to requirement IDs (FR-1, NFR-1) from the `Requirements` narrative\n- ⊗ Generate an authoritative PRD.md — if needed, users run `task prd:render`\n\n**Spec Structure (both paths):**\n- ! Overview, Architecture\n- ! Implementation Plan: scope xBRIEFs in `xbrief/proposed/` with phases and dependencies\n- ! Explicit dependency mapping MUST use the field consumers actually read for the scope shape:\n - **Story-shaped scopes** (`plan.metadata.kind = \"story\"` or scopes intended for swarm allocation / decompose): sequential/blocked work MUST set `plan.metadata.swarm.depends_on` to an array of **resolvable story identifiers**. Swarm readiness, decompose, and queue traversal read **only** this field for story ordering — not `plan.metadata.dependencies` alone. ! Each `depends_on` entry MUST equal the blocking scope's `plan.id` when that field is set; otherwise the blocking artifact's **filename stem** (basename with `.xbrief.json` / `.vbrief.json` stripped — the same stem readiness uses as `story_id`). ⊗ Use rendered titles, free-form prose, date-only prefixes, or unstripped full filenames — those do not resolve and leave the generated scope blocked.\n - **Phase/epic or cross-scope roadmap batches**: MAY also set plan-level `plan.metadata.dependencies` for roadmap/export readers.\n - `edges` / `references` may supplement documentation but **do not** replace `plan.metadata.swarm.depends_on` for sequential story scopes.\n- ! When multiple scopes are produced in one Phase 3 pass, encode machine-readable dependency ordering before finishing the write: independent scopes use empty `plan.metadata.swarm.depends_on` (`[]`); sequential/blocked story scopes use non-empty `plan.metadata.swarm.depends_on`. Optionally mirror the same DAG in `plan.metadata.dependencies` for roadmap views.\n- ~ Scopes designed for parallel work by multiple agents\n- ⊗ Deposit sequential story-shaped scopes with only `plan.metadata.dependencies` / `edges` / `references` and missing `plan.metadata.swarm.depends_on` — orchestration will treat them as independent or reject readiness.\n- ⊗ Deposit multiple generated scope xBRIEFs with no dependency metadata and rely on filenames or human prose for ordering.\n- ! Testing Strategy and Deployment captured in narratives\n- ⊗ Write code — specification only\n\n### Lifecycle Bridge to Downstream Skills (#1025)\n\n! Scope xBRIEFs created by Phase 3 (both Light and Full paths) AND by the Onboarding Question \"Add scope to this project\" branch land in `xbrief/proposed/` with `plan.status: proposed`. This is the canonical deposit point per the deft lifecycle (`proposed -> pending -> active -> completed`). The #810 implementation-intent gate (`task xbrief:preflight`) and the deft-directive-swarm Phase 0 Step 1 preflight BOTH require candidate xBRIEFs to live in `xbrief/active/` with `plan.status == \"running\"` before any agent can dispatch against them; setup deliberately stops at `proposed/` because the lifecycle commitment (promote + activate) belongs to the downstream skill, not the setup interview.\n\n! Surface this bridge to the user in the Phase 3 → next-skill handoff so they are not surprised by a wholesale preflight rejection downstream:\n\n - **If the next step is `skills/deft-directive-swarm/SKILL.md`**: the swarm skill's Phase 0 Step 0.5 (Lifecycle Bridge -- Promote and Activate Proposed Scope xBRIEFs) is the canonical bridge. The monitor will scan `xbrief/proposed/` and `xbrief/pending/`, present in-scope candidates, and run `task scope:promote -- <path>` then `task scope:activate -- <path>` on explicit user approval. No manual operator action is required ahead of the swarm invocation.\n - **If the next step is `skills/deft-directive-refinement/SKILL.md`**: the refinement skill's Phase 4 (Promote/Demote) owns the same `task scope:promote` / `task scope:activate` surface and runs the bridge as part of the refinement loop. The refinement skill MAY leave xBRIEFs in `pending/` deliberately when they are queued for prioritisation rather than immediate dispatch.\n - **If the user wants to invoke an implementation agent directly via `skills/deft-directive-build/SKILL.md` or `start_agent`**: the bridge MUST be run manually before dispatch -- `task scope:promote -- xbrief/proposed/<file>` then `task scope:activate -- xbrief/pending/<file>`. Both commands are idempotent and exit 0 on no-op. The #810 preflight gate (`task xbrief:preflight -- <active-path>`) will exit 0 only after the activate step.\n\n⊗ Auto-run `task scope:promote` or `task scope:activate` from the setup skill on the Phase 3 outputs. The lifecycle commitment belongs to the user (\"I am ready to swarm/build on this scope\"), not the setup interview; silent promotion would clear the #810 implementation-intent gate without explicit user authorisation and bypass the deterministic-questions contract that protects every other Phase 3 transition.\n\n⊗ Drop the user at the end of Phase 3 with scope xBRIEFs in `xbrief/proposed/` and no forward pointer to the bridge. Without this section the user discovers the gap at runtime when the swarm Phase 0 Step 1 preflight rejects every candidate (`Invalid transition: 'activate' requires file in pending/`), as in the originating 2026-05-10 first-session consumer tic-tac-toe swarm (issue #1025).\n\n### End-of-Phase-3 Export Prompt (project:export-spec)\n\n! After scope xBRIEFs are written to `xbrief/proposed/` and PROJECT-DEFINITION is populated, but BEFORE handing off to `deft-directive-build` (or advancing speckit Phase 3 → Phase 4), ask the user whether to generate human-readable exports. Greenfield v0.20 projects export via `task project:export-spec` (not legacy `task spec:render`). This replaces the invisible skip-if-absent behavior of `task check` (#398), closes the greenfield gap (#433), and is the Phase 3 → Phase 4 transition gate required by [strategies/speckit.md Post-Phase 3 Transition Gate](../../strategies/speckit.md#post-phase-3-transition-gate-export-for-review) (#432 / #2013).\n\n1. ! Prompt: \"Your scope xBRIEFs are ready. Generate a stakeholder-facing spec export and/or `PRD.md` now? (recommended for stakeholder review)\"\n 1. Yes — export spec (+ PRD if selected)\n 2. Spec export only (`SPECIFICATION.md`)\n 3. `PRD.md` only\n 4. Skip — I'll export later with `task project:export-spec` / `task prd:render`\n2. ! Run the selected export command(s):\n - `task project:export-spec` → writes `SPECIFICATION.md` from PROJECT-DEFINITION + lifecycle scopes (greenfield default; stakeholder audience)\n - `task project:export-spec -- --audience=internal` → same export but includes proposed scopes under `## Scope outlook` (use for setup/speckit internal handoff when proposed scopes need visibility)\n - `task prd:render` → writes `PRD.md` (optional stakeholder review)\n - Legacy `task spec:render` — migrated trees only (when `xbrief/specification.xbrief.json` exists); do NOT use on greenfield v0.20 projects\n3. ! If the user picked a speckit-strategy project: export is **mandatory** at this boundary — invoke `task project:export-spec` (with `--audience=internal` when proposed scopes exist) even if the user declined the prompt, because speckit Phase 3 → Phase 4 is gated on **export succeeded** (exit 0), not on `specification.xbrief.json` approval.\n4. ! Confirm to the user which files were written and remind them that direct edits to `SPECIFICATION.md` / `PRD.md` are overwritten on the next export — edit xBRIEF narratives in `xbrief/proposed/` and PROJECT-DEFINITION instead.\n5. ~ If the user skipped export and is NOT on a speckit strategy, no-op and continue.\n\n⊗ Advance a speckit project to Phase 4 without a successful `task project:export-spec` at this gate — export must succeed (exit 0) for the Phase 3 transition criterion.\n⊗ Silently skip the prompt — greenfield users who never open a PR will miss the exports without it.\n⊗ Invoke legacy `task spec:render` on a greenfield v0.20 project — use `task project:export-spec` instead (#2013).\n\n### Handoff to deft-directive-build\n\n- ! Emit a structured-tool question asking whether to continue to the build phase only when the host preserves numeric labels; otherwise emit the deterministic numbered menu in chat. Options: `1. Yes (continue)`, `2. Not now (exit setup)`, `3. Discuss`, `4. Back (revisit previous phase)`. The numeric labels MUST remain visible and be returned as numeric selections or exact displayed option text.\n- ~ If platform supports skill invocation and the user picks Yes, invoke `skills/deft-directive-build/SKILL.md`\n- ⊗ Leave user with a dead end -- always offer the next step via the structured-tool phase-transition question\n- ⊗ Ask the handoff-to-build question as unnumbered conversational prose or through a structured UI that hides the canonical numeric labels -- it is a deterministic menu and MUST preserve visible numbers (#478, #1563).\n\n## Warp Auto-Approve Warning\n\n! **Recommended Warp setting**: Before running deft-directive-setup, ensure Warp's AI autonomy is set to **\"Always ask\"** in **AI -> Profile Settings**. When set to a higher autonomy level (e.g. \"Auto-run\"), Warp may silently self-answer interview questions without user input, producing garbage USER.md/PROJECT-DEFINITION.xbrief.json with no error or warning. The post-interview confirmation gate (below) is the last line of defense, but prevention is better than detection.\n\n## Post-Interview Confirmation Gate\n\n! After completing ALL interview questions for any phase (Phase 1, Phase 2, or Phase 3), but BEFORE writing any files:\n\n1. ! Display a **summary of all captured values** in a clearly formatted list -- include every field that will be written to the output file (e.g. name, strategy, coverage, languages, project type, custom rules, etc.)\n2. ! Ask the user for explicit confirmation: \"These are the values I captured. Write files? (yes/no)\"\n3. ! Accept only explicit affirmative responses (`yes`, `confirmed`, `approve`) -- reject vague responses (`proceed`, `do it`, `go ahead`) the same way `/deft:change` does\n4. ! If the user says `no`: re-display the values and ask which ones to correct, then re-confirm before writing\n5. ! If any value appears to be auto-generated filler (e.g. repeated default text, placeholder strings, or values that echo the question prompt), warn the user explicitly: \"Some values look like they may have been auto-filled rather than provided by you. Please review carefully.\"\n\n⊗ Write USER.md, PROJECT-DEFINITION.xbrief.json, specification.xbrief.json, or any other deft-directive-setup artifact without first displaying captured values and receiving explicit user confirmation.\n⊗ Treat a broad \"proceed\" or \"continue\" as confirmation to write files -- the user must explicitly confirm the displayed values.\n\n? **Yolo strategy carve-out**: When the user's chosen strategy is `yolo` (auto-pilot), the confirmation gate still applies but the agent (Johnbot) may self-confirm on the user's behalf by displaying the summary and immediately proceeding -- the user has already opted into auto-pilot by selecting yolo. The summary must still be displayed so the user can interrupt if values look wrong.\n\n## Anti-Patterns\n\n- ! When deft-directive-setup generates or updates USER.md or PROJECT-DEFINITION.xbrief.json, the `deft_version` field MUST be set to the current framework version\n- ⊗ Generate a USER.md or PROJECT-DEFINITION.xbrief.json without including the `deft_version` field\n- ⊗ Explore codebase before Phase 1 questions\n- ⊗ Read framework files before first question\n- ⊗ Batch multiple questions into one message — ask one at a time, interview style\n- ⊗ Ask jargon-heavy questions to non-technical users\n- ⊗ Ask about things inferable from codebase (Phase 2+)\n- ⊗ Skip phases without asking\n- ⊗ Generate files without confirming content\n- ⊗ Present choices through a host UI that replaces the canonical numbers with alphabetic affordances or unlabeled buttons\n- ⊗ Resolve paths relative to the skill file, AGENTS.md, or framework directory instead of the user's pwd at skill entry\n- ⊗ Generate an authoritative PRD.md — PRD.md is a read-only export via `task prd:render`, never a source of truth\n- ⊗ Skip the Returning-user re-entry / Revisit experimental rules path when USER.md exists and the operator entered setup to change experimental meta (#46)\n- ⊗ Clobber Personal or Defaults while toggling Experimental Rules (#46)\n- ⊗ Invent a full `deft config` verb family for experimental meta when setup re-entry suffices (#46)\n",
267
267
  "frontmatter_extra": null
268
268
  },
269
269
  {
@@ -276,7 +276,7 @@
276
276
  ],
277
277
  "path": "skills/deft-directive-swarm/SKILL.md",
278
278
  "version": "0.1",
279
- "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, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.\n\n**⚠️ 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 — 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) → 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 → 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| `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 — Allocate | [`references/core-phase-0.md`](references/core-phase-0.md) |\n| Phase 1–2 — Select + Setup | [`references/core-phase-1-2.md`](references/core-phase-1-2.md) |\n| Phase 3 — Launch (neutral + detect detail) | [`references/core-phase-3.md`](references/core-phase-3.md) |\n| Phase 4 — Monitor | [`references/core-phase-4.md`](references/core-phase-4.md) |\n| Phase 5–6 — 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⊗ Load all host adapters “just in case.” Unused host wiring stays out of context (#2928).\n≉ Paste full host manuals into this thin SKILL — 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⊗ 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⊗ End the turn with only narrative “I will spawn…” / “review next” and zero tools (#2934).\n~ Keep a small phase-state note: `cohort_id → phase → next_action|terminal`.\n\n### Parent-monitor after leaf announce (#2943)\n\n! After any leaf completion event (`subagent_announce` / parent-push / host completion notify), the parent’s **first response** MUST be **tool-first** or **yield**:\n- tool-first ground-truth batch (`gh` / `git` / worktree or file status), **or**\n- host yield (`sessions_yield` on OpenClaw, or equivalent).\n\n! **Thin DONE = failed leaf:** completion without PR URL / merge evidence is **failed** (re-dispatch or take over) — not success. Prefer structured fields when present (`prUrl`, `mergeStatus`, `emptyDiff`).\n\n⊗ Multi-sentence progress-only first response after announce with zero tools / yield (#2943 text-repetition hang).\n⊗ Treat thin DONE (no PR URL / merge evidence) as success (#2943).\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** — Warp orchestrated.\n2. ! **Probe for Warp environment** — `WARP_*` without `start_agent` → warp-manual.\n3. ! **Probe for the Cursor `Task` tool** — Tier 1; descriptor `cursor-composer` / `cursor-cloud-agent` (#1877).\n4. ! **Probe for the OpenClaw `sessions_spawn` tool** — Tier 1; descriptor `openclaw` (#2875). Do NOT misclassify as `grok-build` or `generic-terminal`.\n5. ! **Probe for `spawn_subagent` tool** — descriptor `grok-build`.\n6. ! **Select launch path automatically** — load the matching host adapter (route table). No static A/B/C menu.\n7. ! **Return a stable platform descriptor** for Phase 4/6: `warp-orchestrated`, `warp-manual`, `cursor-composer`, `cursor-cloud-agent`, `openclaw`, `grok-build`, or `generic-terminal`.\n8. ? **Cloud escape hatch** — `oz agent run-cloud` only on explicit user request (host-generic).\n\n⊗ Present static launch options instead of detecting capabilities at runtime.\n⊗ Offer Warp-specific launch paths when not inside Warp.\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## Critical anti-patterns (dispatch card)\n\n- ⊗ Load all host adapters “just in case” (#2928)\n- ⊗ Parallel OpenClaw `sessions_spawn` on shared repo root without worktrees (#2929)\n- ⊗ Prose-only phase handoff after cohort complete (“I will spawn…”) (#2934)\n- ⊗ Multi-sentence progress-only first response after leaf announce with zero tools / yield (#2943)\n- ⊗ Treat thin DONE (no PR URL / merge evidence) as success (#2943)\n- ⊗ Assign overlapping files to multiple agents\n- ⊗ Merge before Greptile exit condition (score > 3, no P0/P1)\n- ⊗ Skip Phase 0 approval before Phase 1\n- ⊗ Misclassify OpenClaw `sessions_spawn` as `grok-build` or `generic-terminal` (#2875)\n\nFull anti-pattern list: [`references/core-ops.md`](references/core-ops.md).\n",
279
+ "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, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.\n\n**⚠️ 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 — 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) → 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 → 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| `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 — Allocate | [`references/core-phase-0.md`](references/core-phase-0.md) |\n| Phase 1–2 — Select + Setup | [`references/core-phase-1-2.md`](references/core-phase-1-2.md) |\n| Phase 3 — Launch (neutral + detect detail) | [`references/core-phase-3.md`](references/core-phase-3.md) |\n| Phase 4 — Monitor | [`references/core-phase-4.md`](references/core-phase-4.md) |\n| Phase 5–6 — 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⊗ Load all host adapters “just in case.” Unused host wiring stays out of context (#2928).\n≉ Paste full host manuals into this thin SKILL — 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⊗ 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⊗ End the turn with only narrative “I will spawn…” / “review next” and zero tools (#2934).\n~ Keep a small phase-state note: `cohort_id → phase → next_action|terminal`.\n\n### Parent-monitor after leaf announce (#2943)\n\n! After any leaf completion event (`subagent_announce` / parent-push / host completion notify), the parent’s **first response** MUST be **tool-first** or **yield**:\n- tool-first ground-truth batch (`gh` / `git` / worktree or file status), **or**\n- host yield (`sessions_yield` on OpenClaw, or equivalent).\n\n! **Thin DONE = failed leaf:** completion without PR URL / merge evidence is **failed** (re-dispatch or take over) — not success. Prefer structured fields when present (`prUrl`, `mergeStatus`, `emptyDiff`).\n\n⊗ Multi-sentence progress-only first response after announce with zero tools / yield (#2943 text-repetition hang).\n⊗ Treat thin DONE (no PR URL / merge evidence) as success (#2943).\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` §11.5. Depth: `references/core-phase-5-6.md`. Orthogonal to empty settle ≠ done (#3044).\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** — Warp orchestrated.\n2. ! **Probe for Warp environment** — `WARP_*` without `start_agent` → warp-manual.\n3. ! **Probe for the Cursor `Task` tool** — Tier 1; descriptor `cursor-composer` / `cursor-cloud-agent` (#1877).\n4. ! **Probe for the OpenClaw `sessions_spawn` tool** — Tier 1; descriptor `openclaw` (#2875). Do NOT misclassify as `grok-build` or `generic-terminal`.\n5. ! **Probe for `spawn_subagent` tool** — descriptor `grok-build`.\n6. ! **Select launch path automatically** — load the matching host adapter (route table). No static A/B/C menu.\n7. ! **Return a stable platform descriptor** for Phase 4/6: `warp-orchestrated`, `warp-manual`, `cursor-composer`, `cursor-cloud-agent`, `openclaw`, `grok-build`, or `generic-terminal`.\n8. ? **Cloud escape hatch** — `oz agent run-cloud` only on explicit user request (host-generic).\n\n⊗ Present static launch options instead of detecting capabilities at runtime.\n⊗ Offer Warp-specific launch paths when not inside Warp.\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## Critical anti-patterns (dispatch card)\n\n- ⊗ Load all host adapters “just in case” (#2928)\n- ⊗ Parallel OpenClaw `sessions_spawn` on shared repo root without worktrees (#2929)\n- ⊗ Prose-only phase handoff after cohort complete (“I will spawn…”) (#2934)\n- ⊗ Multi-sentence progress-only first response after leaf announce with zero tools / yield (#2943)\n- ⊗ Treat thin DONE (no PR URL / merge evidence) as success (#2943)\n- ⊗ Second+ user-visible consolidate for the same child runId without new evidence (#3092)\n- ⊗ Assign overlapping files to multiple agents\n- ⊗ Merge before Greptile exit condition (score > 3, no P0/P1)\n- ⊗ Skip Phase 0 approval before Phase 1\n- ⊗ Misclassify OpenClaw `sessions_spawn` as `grok-build` or `generic-terminal` (#2875)\n\nFull anti-pattern list: [`references/core-ops.md`](references/core-ops.md).\n",
280
280
  "frontmatter_extra": null
281
281
  },
282
282
  {