@deftai/directive-content 0.95.0 → 0.96.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.
@@ -205,7 +205,7 @@
205
205
  ],
206
206
  "path": "skills/deft-directive-refinement/SKILL.md",
207
207
  "version": "0.1",
208
- "body": "# Deft Directive Refinement\n\nConversational refinement session -- ingest, evaluate, reconcile, and prioritize scope xBRIEFs with the user.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.\n\n**Upstream pass**: refinement begins with a triage pass -- see [`../deft-directive-triage/SKILL.md`](../deft-directive-triage/SKILL.md) (D6 / #1130) for the canonical cache-hygiene + \"what's next?\" queue playbook before continuing into the refinement flow below.\n\n**See also**: [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md) (canonical numbered-menu rule used by every Phase 0 / Phase 2-5 gate below) | `task cache:fetch-all` / `task cache:get` (Tier 1 unified content cache, #883 Story 2) | `task triage:bootstrap` / `task triage:accept` / `task triage:reject` / `task triage:defer` / `task triage:needs-ac` / `task triage:mark-duplicate` / `task triage:bulk-*` / `task triage:refresh-active` (Phase 0 action surface, #845 + #883 Story 3 rebind).\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 ingestion, origin freshness checks, and completion lifecycle all depend on `gh`.\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (Phase 0 Triage action menu, Phase 2 Evaluate per-item accept/reject, Phase 3 Reconcile flagged-item walk, Phase 4 Promote/Demote lifecycle gates, Phase 5 Prioritize reorder gates) 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 \"refinement\", \"reprioritize\", \"refine\", \"roadmap refresh\", or \"refresh roadmap\" (legacy v0.19 terms -- deft-directive-refinement is the current skill name)\n- User says \"triage\", \"action menu\", \"work the cache\", or \"pre-ingest\" -- first-class Phase 0 direct triggers introduced under #845; they route to Phase 0 (Triage), not the general refinement entry\n- New issues have accumulated since the last refinement session\n- Periodic maintenance pass (e.g. weekly or after a batch of user feedback)\n- User wants to review and organize the backlog\n\n! **Entry point (#1141, supersedes #845 / #883 action-menu).** Phase 0 -- Triage-first consultation is the canonical entry point for any refinement session. Phase 0 consults `task triage:summary` (D2 / #1122) and `task triage:queue --state=accept` (D11 / #1128) and pulls the `[RESUME]`-tagged slice (D3 / #1123) FIRST. Refinement does NOT itself triage cached candidates -- that work belongs to [`../deft-directive-triage/SKILL.md`](../deft-directive-triage/SKILL.md) (D6 / #1130). Phase 0 ! MUST chain into Phase 1 -- Ingest on completion (or surface the empty-cache fallback prompt when the cache has not yet been bootstrapped -- see Phase 0a below). Phase 1+ semantics are unchanged.\n\n## Prerequisites\n\n- ! `xbrief/` directory exists with lifecycle folders (`proposed/`, `pending/`, `active/`, `completed/`, `cancelled/`)\n- ! GitHub CLI (`gh`) is authenticated and can access the repo\n- ~ `PROJECT-DEFINITION.xbrief.json` exists (run `task project:render` if missing)\n\n## Session Model\n\nRefinement is a **conversational loop**, not a batch job. The user directs the flow:\n\n- \"Triage\" / \"action menu\" / \"work the cache\" / \"pre-ingest\" -> Phase 0 (Triage-first consultation, #1141) -- refinement consults the cache; the canonical decision-making playbook is `../deft-directive-triage/SKILL.md` (D6 / #1130)\n- \"Pull in issues\" / \"ingest\" -> Phase 0 ALWAYS runs first to consult `task triage:summary` + `task triage:queue --state=accept`; Phase 1 follows on the cohort Phase 0b produces (#1141)\n- \"Show proposed\" / \"evaluate\" -> Phase 2 (Evaluate)\n- \"Check origins\" / \"reconcile\" -> Phase 3 (Reconcile)\n- \"Accept these\" / \"reject that\" / \"promote\" / \"demote\" -> Phase 4 (Promote/Demote)\n- \"Reprioritize\" / \"reorder pending\" -> Phase 5 (Prioritize)\n- \"Close out\" / \"scope is done\" / \"completion\" -> Phase 6 (Completion Lifecycle)\n- \"Done\" / \"exit\" -> Exit\n\nThe agent may suggest the next phase, but the user decides. Phases can be entered in any order and repeated.\n\n## Branch Setup (Preflight)\n\n! Before making any changes, ensure you are working on a feature branch. This preflight runs before Phase 0 and again before Phase 1 if Phase 0 is auto-skipped.\n\n1. ! Check if the working tree has uncommitted changes that would conflict -- stop and ask the user to resolve them first\n2. ! Create or switch to a refinement branch (e.g. `refinement/YYYY-MM-DD`) if not already on one\n3. ! Confirm the branch and working directory to the user before proceeding\n\n## Phase 0 -- Triage-first consultation (cache-first, #1141)\n\n! Phase 0 is a thin consumer of the canonical triage cache: refinement consults `task triage:summary` (D2 / #1122) and `task triage:queue` (D11 / #1128) BEFORE walking any `xbrief/` lifecycle folder. The dedicated triage playbook lives at [`../deft-directive-triage/SKILL.md`](../deft-directive-triage/SKILL.md) (D6 / #1130) -- refinement does NOT itself triage cached candidates; it consumes the queue's `accept` and `[RESUME]` slices and turns them into scope xBRIEFs.\n\n! Phase 0 runs three sub-phases in canonical order: **Phase 0a -- Triage gate** -> **Phase 0b -- Cache-first ingestion** -> **Phase 0c -- Resume conditions**. Each sub-phase MUST run before the next, and Phase 0 MUST chain into Phase 1 -- Ingest on completion. Numbered prompts in Phase 0 ! MUST follow [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md) (`Discuss` / `Back` as the final two numbered options; Discuss-pause semantic applies verbatim).\n\n**See also (#883 Story 2):** the unified cache (`task cache:fetch-all --source=github-issue --repo OWNER/NAME`) is the sole content-mirroring surface in v0.26.0+. Tier 1 reads MUST go through `task cache:get -- github-issue OWNER/NAME/<N>`. The legacy \"Three-Tier Inventory Model\" + action-menu walk that lived here pre-#1141 has moved out of refinement and into `../deft-directive-triage/SKILL.md` (D6 / #1130); refinement now consumes the post-decision queue rather than producing decisions.\n\n### Phase 0a -- Triage gate (`task triage:summary`)\n\n1. ! Invoke `task triage:summary` (D2 / #1122) and capture the one-liner.\n2. ! **Empty-cache backward-compat fallback.** If the one-liner is the documented empty-cache prompt (`[triage] cache empty -- run task triage:bootstrap`), the agent ! MUST emit the verbatim recovery message to stderr BEFORE any folder scan:\n\n ```\n triage cache empty -- run `task triage:welcome` (N3 / #1143) to onboard, or `task triage:bootstrap` to seed the cache directly; refinement Phase 0 cannot consult the queue against an empty cache. Falling back to a legacy `xbrief/proposed/` folder scan only if you opt in.\n ```\n\n Then prompt the user `Fall back to legacy folder-scan against xbrief/proposed/ for this session? [y/N]` (default `N`). On `N`, exit refinement with the canonical `deft-directive-refinement complete -- exiting skill.` confirmation and the chaining instruction `Run task triage:welcome (N3 / #1143) to onboard, then re-enter refinement.`. On `y`, chain into Phase 1 against `xbrief/proposed/` as the legacy fallback. ! MUST NOT silently proceed without surfacing the breadcrumb to `task triage:welcome` -- a fresh post-upgrade install needs that pointer to find the canonical onboarding ritual.\n\n3. ! **Outstanding-work gate.** If the cache is populated AND any of `untriaged`, `stale-defer (resume condition met)`, or `in-flight` is non-zero, surface the one-liner verbatim to the user with the canonical recommendation:\n\n ```\n triage cache has outstanding work -- recommend running `skills/deft-directive-triage/SKILL.md` (D6 / #1130) first. Proceed to refinement anyway? [y/N]\n ```\n\n ~ Default is `N`: deferring to the triage skill is the documented happy path because refinement consumes `accept`-decisioned candidates and an untriaged backlog means there are fewer `accept` rows than there could be. On `N`, exit with the canonical confirmation phrasing and the chaining instruction `Run skills/deft-directive-triage/SKILL.md to clear the backlog, then re-enter refinement.`. On `y`, proceed to Phase 0b.\n\n4. ? When all counts are zero (cache populated, no outstanding work), proceed to Phase 0b without prompting.\n\n⊗ Skip Phase 0a -- refinement on top of an untriaged cache wastes the operator's time on items the triage skill would have rejected, deferred, or marked needs-AC.\n⊗ Bypass the empty-cache fallback prompt -- a silent proceed against an empty cache surfaces a misleading \"no candidates\" state and hides the upgrade-onboarding path from the operator.\n\n### Phase 0b -- Cache-first ingestion (`task triage:queue --state=accept`)\n\n1. ! Pull the ingestion candidate list via `task triage:queue --state=accept` (D11 / #1128). Each row is a cached issue whose latest audit-log decision is `accept` -- the canonical \"ready to become a scope xBRIEF\" cohort. ! MUST NOT enumerate `xbrief/proposed/` independently of the queue; the folder participates only via the join described in step 2.\n2. ! Join the queue against `xbrief/proposed/` (and the rest of the lifecycle folders) by `references[].uri`: queue rows whose issue is already represented by an existing xBRIEF surface as \"already tracked\"; queue rows with no matching xBRIEF are \"new accept candidates\". Items already in `xbrief/proposed/` continue to participate -- they are joined against the cache rather than enumerated separately.\n3. ~ When the join surfaces zero new candidates (every `accept` row already has a xBRIEF), Phase 0b is a clean no-op; chain straight into Phase 0c.\n4. ! For each new candidate, fall through to Phase 1 -- Ingest, which delegates the actual scope-xBRIEF write to `task issue:ingest`. The intended single-verb form is `task scope:promote --from-issue=<N>` (#1136 / D18); until D18 lands, refinement chains the existing `task issue:ingest` + `task scope:promote` pair.\n\n <!-- TODO(#1136 / D18): when `task scope:promote --from-issue=<N>` ships, refinement Phase 0b consumes it directly instead of chaining `task issue:ingest` + `task scope:promote`. -->\n\n⊗ Walk `xbrief/proposed/` directly as the primary ingestion surface -- the cache is the authoritative \"what is ready to refine?\" surface; the folder is the destination, not the source of truth.\n⊗ Drop items that exist in `xbrief/proposed/` but lack a matching cache row -- those are reconciled later (Phase 3 / origin reconciliation), not silently discarded.\n\n### Phase 0c -- Resume conditions (`[RESUME]`-tagged items first)\n\n1. ! Before walking new untriaged candidates from Phase 0b, process every `[RESUME]`-tagged row in the queue. `[RESUME]` rows surface from D3 (#1123) when a prior `defer` audit entry's `resume-on` condition fires (atomics: `ref:closed:#N`, `ref:merged:#N`, `date:>=YYYY-MM-DD`, `pending-count:>=N|<=N`, composed by a single top-level `AND` or `OR`).\n2. ! Stale-defer (resume-eligible) items take priority over fresh untriaged when both are present in the same Phase 0 pass -- the operator made a forward-dated decision on the deferred item and the framework is honouring it. Treat the `[RESUME]` slice as the FIRST class of candidates surfaced to the user.\n3. ~ The exact precedence in `task triage:queue` is `[ORPHAN]` -> `[RESUME]` -> `[URGENT]` -> untriaged -> other (per D11 + D13 / #1132 grouping). Refinement consumes this order verbatim and surfaces `[RESUME]` candidates first; `[ORPHAN]` rows are out-of-scope for refinement (they are handled by the triage skill's audit phase).\n\n⊗ Treat `[RESUME]` rows as \"leftover\" -- they are the highest-priority class refinement is meant to process, because the operator already decided to revisit them when the condition fired.\n\n### Pre-Phase-1 handoff\n\n1. ! Surface a one-line session summary: `{resume_eligible} resume-eligible, {new_accept} new accept candidate(s), {already_tracked} already tracked in xbrief/`.\n2. ! Chain into Phase 1 -- Ingest, which now operates on the cohort produced by Phase 0b's join (`[RESUME]` rows first, then new accept candidates).\n3. ? If the user opts out of Phase 1 (e.g. \"that's it for today\"), exit via the Phase 0 mid-session exit surface below -- ! MUST NOT route to the `### EXIT` block under `## PR & Review Cycle` because that block is the post-PR-creation exit path and references a `PR #{N}` that does not yet exist at this point in the flow.\n\n#### Phase 0 mid-session exit surface\n\n! When the user opts out of Phase 1 after completing (or partially completing) Phase 0, perform exactly these steps -- ! MUST NOT mention any PR number, since none has been created yet:\n\n1. ! Surface the outstanding-work tally: `{resume_eligible} resume-eligible candidate(s) still pending, {new_accept} accept candidate(s) not yet ingested -- these will resurface on the next Phase 0 entry.`\n2. ! Note the audit-log location verbatim using double-backtick fencing so the inner path renders correctly: ``Audit log preserved at `xbrief/.eval/candidates.jsonl`; queue state is reproducible via `task triage:queue --state=accept`.``\n3. ! Confirm skill exit with the canonical phrasing: `deft-directive-refinement complete -- exiting skill.`\n4. ! Provide the Phase-0-appropriate chaining instruction: ``Resume with `task triage:queue --state=accept` to inspect the queue, or re-enter the refinement skill when ready to continue.`` Do NOT reference a PR, a review cycle, or a monitor agent.\n\n⊗ Skip Phase 1 silently after Phase 0 -- always render the chaining decision so the user knows the entry point shifted.\n⊗ Mutate `xbrief/proposed/` directly during Phase 0 -- only `task issue:ingest` (called from Phase 1) is allowed to write there; Phase 0 is read-only against the cache.\n⊗ Route Phase 0 mid-session opt-out to the post-PR `### EXIT` block under `## PR & Review Cycle` -- that block surfaces a non-existent `PR #{N}` and confuses the user.\n\n## Phase 1 -- Ingest\n\n! Scan external sources for new work items and create proposed scope xBRIEFs.\n\n! **Pre-filing master-diff check (#1102).** When a refinement pass FILES a new GitHub issue that proposes ADDING a file or directory (rather than ingesting an existing issue), first run the pre-filing existence check from [`../deft-directive-gh-slice/SKILL.md`](../deft-directive-gh-slice/SKILL.md) Step 5 -- `git ls-tree origin/master -- <path>` (or `gh api repos/{owner}/{repo}/contents/{path}`) -- so a stale \"add file X\" issue is never opened against state that already exists on master (the #1099 -> #1100 close-and-refile recurrence).\n\n### Step 1: Gather Sources\n\n1. ? Scan non-GitHub sources (Jira, direct user requests, etc.) manually if applicable — those ingest paths are not yet task-wrapped\n2. ! GitHub issues are ingested via the task wrapper documented in Step 3 — the task fetches open issues itself, so no separate `gh issue list` call is needed\n\n### Step 2: Deduplicate via References (Dry-Run Preview)\n\n1. ? Run `task issue:ingest -- --all --dry-run` to preview which issues the ingest task would create scope xBRIEFs for. The task deduplicates candidates against `references` entries in existing xBRIEFs (across all lifecycle folders) so already-tracked issues are skipped automatically.\n2. ! Present the user with the list of new-vs-already-tracked items the dry-run reports: \"{N} new items found, {M} already tracked\"\n3. ! Wait for user approval before proceeding to ingest\n\n### Step 3: Ingest Approved Items\n\n! Delegate ingest to `task issue:ingest` — the task is the canonical implementation of scope-xBRIEF creation. Skills MUST NOT reinvent the slug rules, reference shape, or deduplication logic inline (see #537 for background).\n\n- **Single issue**: `task issue:ingest -- <N>` — creates `xbrief/proposed/YYYY-MM-DD-<slug>.xbrief.json` with origin `references`, canonical slug from `scripts/slug_normalize.py` (see [`../../conventions/vbrief-filenames.md`](../../conventions/vbrief-filenames.md)), and schema-conformant shape.\n- **Batch**: `task issue:ingest -- --all [--label <L>] [--status <S>]` — ingests every open issue matching the filters, skipping duplicates by `references.uri` match.\n- **Preview**: add `--dry-run` to either form to preview without writing files.\n\nThe task emits xBRIEFs conforming to the canonical v0.6 schema (`xbrief/schemas/xbrief-core.schema.json`) with origin references in the form documented in [`../../conventions/references.md`](../../conventions/references.md):\n\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```\n\n- ! New scope xBRIEFs MUST target `\"xBRIEFInfo\": { \"version\": \"0.6\" }` (the task handles this automatically)\n- ! `plan.status` starts at `\"proposed\"`; the task sets this\n- ! Conform to `xbrief/schemas/xbrief-core.schema.json` (v0.6) -- the task validates before writing\n- ~ After ingest, review the generated xBRIEFs with the user before promoting any of them to `pending/`\n\n⊗ Hand-author scope xBRIEFs inside the skill when the ingest task exists — duplicating the narrative logic is how #534 (non-conformant references) and #537 (drift between skill and task) arise\n⊗ Write references with `url`/`id`/bare `github-issue` types — use the schema-conformant `{uri, type, title}` shape above\n⊗ Ingest an item that already has a matching xBRIEF reference -- `task issue:ingest` handles deduplication; skills MUST NOT duplicate that logic inline\n\n## Phase 2 -- Evaluate\n\n! List proposed items for interactive user review.\n\n### Step 1: List Proposed Items\n\n1. ! Read all xBRIEFs in `xbrief/proposed/`\n2. ! Present each item with:\n - Title and filename\n - Origin link(s) from `references`\n - Summary from `narratives` (if populated)\n - Labels/category (if available from origin)\n3. ! Sort by creation date (oldest first) or as user prefers\n\n### Step 2: Interactive Review\n\n! For each proposed item (or batch, as user directs):\n\n- ! Present the item and wait for user decision\n- ~ The user may: accept (promote to pending), reject (cancel), defer (keep in proposed), or request more detail\n- ! Do not proceed to the next item until the user responds\n- ? The user may batch-accept or batch-reject multiple items at once\n\n⊗ Auto-accept or auto-reject proposed items without user review\n\n## Phase 3 -- Reconcile (RFC D12)\n\n! Check if linked origins have changed since the xBRIEF was last touched. Delegate the scan to `task reconcile:issues` and walk the user through flagged items for approval (see #537 for why the skill is a thin wrapper over the task).\n\n### Step 1: Run the Reconciler\n\n```\ntask reconcile:issues\n```\n\nThe task scans every xBRIEF with a GitHub-backed reference (whether the reference uses the legacy `github-issue` bare type or the canonical `x-xbrief/github-issue` shape), fetches each linked issue, compares timestamps and state, and reports items in four buckets:\n\n- **Linked & current** — origin has not changed since the xBRIEF was last updated (no action)\n- **Stale** — origin `updatedAt` is newer than the xBRIEF (propose an update)\n- **Externally closed** — origin issue is `CLOSED` (propose cancellation or reconcile if intentional divergence)\n- **Unlinked** — xBRIEF has no GitHub reference (flag for review)\n\n### Step 2: Walk Flagged Items with the User\n\n1. ! For each **stale** item the task surfaces, show the user the diff between the current xBRIEF and the refreshed origin. Propose edits; ! wait for explicit user approval before writing anything.\n2. ! For each **externally closed** item, ask the user whether to `task scope:cancel <file>` it or preserve intentional divergence.\n3. ! For each **unlinked** item, ask whether to attach an origin reference or leave the xBRIEF as-is.\n\n### Step 3: Apply User-Approved Updates\n\n- ! Agent proposes edits; ! user approves each change\n- ! Never auto-update xBRIEFs — intentional divergence (xBRIEF refined beyond original issue scope) must be preserved\n- ! For approved updates, update the xBRIEF content and `xBRIEFInfo.updated` timestamp; prefer the task commands (`task scope:cancel`, `task scope:block`, etc.) over hand-editing where they apply\n\n⊗ Replace the task invocation with a hand-written `gh issue view` loop — the task is the canonical implementation; skills MUST NOT duplicate it (#537)\n⊗ Auto-update xBRIEFs based on origin changes without user approval\n⊗ Overwrite intentional divergence -- if a xBRIEF has been refined beyond the original issue, preserve the refinement\n\n### Origin sync after material xBRIEF edits (#2540)\n\n! When this refinement pass **materially updates** an origin-linked scope xBRIEF (AC, `plan.status`, or `plan.items` statuses/titles), run `task issue:sync-from-xbrief -- <path>` to post a sync comment on the linked GitHub issue so the human-facing tracker stays current. Use `--dry-run` to preview the comment without posting.\n\n! If sync is intentionally skipped (offline, issue frozen, divergence is deliberate), document the skip reason in the session notes or PR body — do not silently leave the origin stale.\n\n⊗ Materially edit an origin-linked xBRIEF without running `issue:sync-from-xbrief` or documenting why it was skipped\n\n## Phase 4 -- Promote/Demote\n\n! Move xBRIEFs between lifecycle folders using deterministic task commands. The status values below align with the canonical v0.6 Status enum (`draft | proposed | approved | pending | running | completed | blocked | failed | cancelled`) — note that `failed` is also a valid terminal transition for active work that could not complete.\n\n### Available Commands\n\n- `task scope:promote <file>` -- proposed/ -> pending/ (status: pending)\n- `task scope:activate <file>` -- pending/ -> active/ (status: running)\n- `task scope:complete <file>` -- active/ -> completed/ (status: completed)\n- `task scope:cancel <file>` -- any -> cancelled/ (status: cancelled)\n- `task scope:restore <file>` -- cancelled/ -> proposed/ (status: proposed)\n- `task scope:block <file>` -- stays in active/ (status: blocked)\n- `task scope:unblock <file>` -- stays in active/ (status: running)\n- `task scope:fail <file>` (v0.6+) -- active/ -> completed/ (status: failed) — record a failure terminal state when a scope cannot complete but should not be cancelled\n- `task scope:undo <decision_id>` (D15 / #1134) -- reverse a single scope-lifecycle audit entry (`demote` -> re-promote, `cancel` -> restore-from-cancelled-to-prior-folder, `restore` -> re-cancel); terminal actions (`complete` / `fail`) are REFUSED -- use `git revert` or hand-edit\n- `task scope:undo --batch-id=<uuid>` (D15 / #1134) -- reverse every audit entry tagged with the batch_id (e.g. the cohort produced by `task scope:demote --batch`); idempotent on already-undone entries; the undo cohort is itself reversible via the `undo_batch_id` minted on the new entries. Optional `--dry-run` previews without writing.\n- `task scope:undo --latest` (D15 / #1134) -- reverse the most-recent reversible audit entry (`demote` / `cancel` / `restore` / `undo`) not already undone; convenience form used by the N6 / #1146 smoketest contract.\n\n### Workflow\n\n1. ! Execute transitions using the task commands above -- they handle `plan.status` updates, `plan.updated` timestamps, and file moves atomically\n2. ! Derived-artifact renders (`task roadmap:render`, `task project:render`) happen after a **batch** of promotions/demotions, not after each individual item. During high-volume triage (e.g. dozens of accept/reject decisions in one session), defer both renders until the end of the batch -- the source of truth is the lifecycle folder contents under `xbrief/`, so ROADMAP.md and PROJECT-DEFINITION.xbrief.json can be refreshed once per batch without losing correctness.\n3. ! `task roadmap:render` regenerates ROADMAP.md from the updated lifecycle folder contents. Call it once per batch (typically at the end of Phase 4, before handing back to the user or transitioning to Phase 5), not after every single promote/demote.\n4. ! `task project:render` refreshes the PROJECT-DEFINITION items registry. Call it **once per refinement pass** -- usually at the end of the session alongside the final roadmap render -- unless the user explicitly needs an intermediate registry refresh. It is not a per-edit tax.\n5. ! Before the user is shown the final backlog state (end of Phase 4, end of Phase 5, or session exit), both `task roadmap:render` AND `task project:render` MUST have been run at least once so ROADMAP.md and PROJECT-DEFINITION.xbrief.json reflect the current lifecycle folder truth. This preserves correctness while allowing N promotions/demotions to share one render checkpoint.\n6. ! Mark rejected items as `cancelled` via `task scope:cancel` (never delete xBRIEFs)\n\n~ Operationally: a large refinement session can ingest/evaluate/promote multiple issues and close out with **one** final render checkpoint, rather than N repetitive renders after every individual item.\n\n⊗ Rerender derived artifacts (`task roadmap:render`, `task project:render`) after every single accept/reject/promote/demote during high-volume triage -- batch the lifecycle edits and render once at the end of the batch\n⊗ Move xBRIEFs between folders manually (cp/mv) -- always use `task scope:*` commands\n⊗ Delete xBRIEFs -- use `task scope:cancel` to preserve history\n\n## Phase 5 -- Prioritize\n\n! Reorder and organize the pending backlog.\n\n1. ! List all xBRIEFs in `xbrief/pending/` with titles, origins, and any phase/dependency metadata\n2. ~ Help the user set phases and dependencies:\n - Group related items into phases (via xBRIEF `items` hierarchy or `tags`)\n - Identify dependencies between items (via `edges` in xBRIEF schema)\n3. ! `task roadmap:render` is the **checkpoint** before showing the reordered backlog to the user -- not a per-edit tax. Run it ONCE at the end of the reorder pass to regenerate ROADMAP.md from the updated pending/ contents. Do not invoke it after each individual reorder action.\n4. ~ Present the regenerated roadmap summary to the user for confirmation\n\n## Phase 6 -- Completion Lifecycle\n\n! On scope completion, update origins to close the loop.\n\n### When a Scope Completes\n\n1. ! Read the completed xBRIEF's `references` array\n2. ! For each GitHub-issue reference (either the legacy bare `github-issue` type or the canonical `x-xbrief/github-issue` shape):\n - Close the issue with a comment linking to the implementing PR:\n ```\n gh issue close {N} --comment \"Completed via PR #{PR} -- scope xBRIEF: {filename}\"\n ```\n - The issue number is extracted from the reference `uri` (e.g. `https://github.com/o/r/issues/{N}`)\n3. ? For other reference types (`x-xbrief/jira-ticket`, `x-xbrief/user-request`, `x-xbrief/github-pr`, etc.), follow the appropriate update mechanism\n4. ! Update PROJECT-DEFINITION via `task project:render`\n\n⊗ Complete a scope without updating its origins\n~ Completion lifecycle can be triggered during refinement or as a standalone action after a PR merge\n\n! When the refinement session files a new umbrella issue (or surfaces one whose current-shape comment is missing), file the umbrella then file its `## Current shape (as of pass-N)` comment per `## Umbrella current-shape convention` in `AGENTS.md` (#1152) -- the edit-in-place comment is the canonical surface every subsequent design pass updates.\n\n! Before reporting an umbrella or epic's current status to the operator (what is done, what blocks, wave order), fetch `repos/<owner>/<repo>/issues/<N>/comments` via REST, read the `## Current shape (as of pass-N)` comment and any linked context/`LockedDecisions` xBRIEF — never conclude status from the issue body alone (claim-cites-state-surface, #2066).\n\n~ Issue-label hygiene for any umbrella or child issue this skill files: before creating issues, inspect the target repo's existing labels with `gh label list` or the labels API; choose one or more suitable existing labels when practical, or explicitly note that no label was applied. This is a recommendation, not a gate -- do not block issue creation solely because no label fits, and do not invent ad hoc labels outside the repo's existing label set.\n\n! When a refinement pass produces a slicing event (rare but possible -- e.g. a design pass on an existing umbrella files N additional Wave-N child issues), record the cohort in `xbrief/.eval/slices.jsonl` via `scripts/slice_record.py::write_slice(...)` with `actor=\"skill:refinement\"` immediately after the children are filed (#1132 / D13). Same call shape as `skills/deft-directive-gh-slice/SKILL.md` Step 6. The cohort record is what makes `task triage:audit --orphans` able to detect Wave-2+ children whose umbrella closes prematurely; without it the production-side drift this surface guards against re-fires. Skip when the pass produced no new child cohort (e.g. a pure re-prioritization).\n\n\n! When the umbrella + children were filed by hand (legacy `gh issue create` / `issue_write` MCP / prior pass-N runs that pre-date this skill's slicing phase), use the canonical retro verb `task slice:record-existing` (#1147 / N7) -- it wraps the same `slice_record.write_slice` helper with `actor=\"manual:operator\"`, takes `--umbrella=N --children=A,B,C [--wave-N=...]` flags, validates each issue via the N5 / #1145 `scm.call` shim, and is idempotent on a matching umbrella + child set (re-run is a no-op; `--force` writes a second record for legitimate multi-session slicing). Companion `task slice:list` enumerates persisted slices for verification. The backfill verb is the canonical retro path for cohorts D13's writer never saw.\n\n## CHANGELOG Convention\n\n- ! Write ONE batch `CHANGELOG.md` entry at the END of the full refinement session -- not one entry per xBRIEF created or promoted. The batch entry summarizes all changes made during the session.\n- ⊗ Add a CHANGELOG entry after each individual action during refinement -- wait until the full session is complete and write a single summary entry.\n\n## PR & Review Cycle\n\nAfter all refinement work is complete:\n\n1. ! Ask the user: \"Ready to commit and create a PR?\"\n2. ! Wait for explicit user confirmation before proceeding.\n\n### Pre-Flight (before pushing)\n\n! Run all pre-flight checks BEFORE committing and pushing:\n\n1. ! Verify `CHANGELOG.md` has an `[Unreleased]` entry covering the refinement changes\n2. ! Run `task check` -- all checks must pass\n3. ! Verify `.github/PULL_REQUEST_TEMPLATE.md` checklist is satisfiable for this PR. If the file is **missing**, do NOT block — copy the canonical template from `templates/PULL_REQUEST_TEMPLATE.md` (ship-with-deft) to `.github/PULL_REQUEST_TEMPLATE.md` in the consumer project, then proceed with pre-flight (#531). If the file exists but contains unsatisfiable checklist items for this PR, call them out to the user before pushing.\n4. ! **Mandatory file review**: Re-read ALL modified files before committing. Explicitly check for:\n - Encoding errors (em-dashes corrupted to replacement characters, BOM artifacts)\n - Unintended duplication (accidental double xBRIEFs or duplicate entries)\n - Structural issues (malformed xBRIEF JSON, broken references)\n - Semantic accuracy (verify that counts and claims in CHANGELOG entries match the actual data)\n\n### Commit, Push, and Create PR\n\n1. ! Commit with a descriptive message: `docs(xbrief): refinement session -- {summary}`\n2. ! Push the branch to origin\n3. ! Create a PR targeting the appropriate base branch\n\n### Review Cycle Handoff\n\n! After the PR is created, automatically sequence into `skills/deft-directive-review-cycle/SKILL.md`.\n\n- ! Inform the user: \"PR #{N} created -- starting review cycle.\"\n- ! Follow the full review cycle skill from Phase 1 (Deft Process Audit) onward.\n\n### EXIT\n\n! When the review cycle completes (exit condition met) or the PR is ready for human review:\n\n1. ! Explicitly confirm skill exit: \"deft-directive-refinement complete -- exiting skill.\"\n2. ! Provide chaining instructions to the user/agent:\n - If review cycle is complete and PR is approved: \"PR #{N} is ready for human merge review.\"\n - If review cycle is still in progress: \"Review cycle handed off to deft-review-cycle. Monitor PR #{N} for Greptile findings.\"\n - If returning to a monitor agent: \"Returning control to monitor agent -- refinement PR #{N} created and review cycle initiated.\"\n3. ! Do NOT continue into adjacent work after this point -- the skill boundary is an exit condition.\n\n## Anti-Patterns\n\n- ⊗ Bypass Phase 0 by walking `xbrief/proposed/` or `gh issue list` directly -- `task triage:queue --state=accept` (D11 / #1128) is the canonical ingestion-candidate surface (#1141)\n- ⊗ Skip Phase 0a's `task triage:summary` invocation -- the triage-gate decision (run the triage skill first vs proceed) depends on its output (#1141 / D2 / #1122)\n- ⊗ Silently proceed against an empty cache -- emit the canonical `task triage:welcome` (N3 / #1143) breadcrumb to stderr first (#1141)\n- ⊗ Treat `[RESUME]`-tagged items as leftover -- they are the highest-priority class refinement processes (#1141 / D3 / #1123)\n- ⊗ Skip Phase 1 silently after Phase 0 -- always render the chaining decision so the user knows the entry point shifted (#1141, supersedes #845)\n- ⊗ Auto-accept or auto-reject proposed items without user review\n- ⊗ Create xBRIEFs without origin provenance (`references` linking to the source)\n- ⊗ Ingest items without deduplicating against existing xBRIEF references first\n- ⊗ Auto-update xBRIEFs based on origin changes -- user approves all updates\n- ⊗ Overwrite intentional divergence when reconciling stale origins\n- ⊗ Move xBRIEFs between folders manually -- always use `task scope:*` commands\n- ⊗ Delete xBRIEFs -- use `task scope:cancel` to preserve history\n- ⊗ Complete a scope without updating its origins (closing issues, posting comments)\n- ⊗ Skip deduplication during ingest -- always diff against existing references\n- ⊗ Add a CHANGELOG entry per individual action during refinement -- write one batch entry at the end of the full session\n- ⊗ Proceed to the next proposed item without waiting for user decision during evaluate\n- ⊗ Auto-push without explicit user instruction\n- ⊗ Rerender ROADMAP.md or PROJECT-DEFINITION.xbrief.json after every single accept/reject/promote/demote during high-volume triage -- `task roadmap:render` and `task project:render` are batch checkpoints, not per-edit taxes, and calling them N times for N lifecycle edits turns O(1) render work into O(N) without changing correctness (see #638)\n- ⊗ Return a final backlog view to the user without having run `task roadmap:render` and `task project:render` at least once since the last lifecycle edit -- batch the renders, but do not skip them\n\n## See also\n\n- Upstream skill: [`../deft-directive-triage/SKILL.md`](../deft-directive-triage/SKILL.md) (D6 / #1130) -- the canonical triage hygiene + queue selection playbook. Refinement Phase 0a consults `task triage:summary` (D2 / #1122) and Phase 0b consumes `task triage:queue --state=accept` (D11 / #1128), both of which are produced by the triage skill's decision flow. `[RESUME]`-tagged items (Phase 0c) originate from D3 (#1123) `--resume-on` conditions documented in the triage skill's Phase 3.\n- Reversibility verb in Phase 4: `task scope:undo <file>` (D15 / #1134).\n- Onboarding (empty-cache fallback target): `task triage:welcome` (N3 / #1143) -- the single chained command a fresh post-upgrade install runs before re-entering refinement.\n- Refs: #1141 (this rewrite), #1119 (umbrella), #1122 (D2), #1128 (D11), #1123 (D3), #1130 (D6), #1134 (D15), #1143 (N3), #1149 (N9 routing).\n",
208
+ "body": "# Deft Directive Refinement\n\nConversational refinement session -- ingest, evaluate, reconcile, and prioritize scope xBRIEFs with the user.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.\n\n**Upstream pass**: refinement begins with a triage pass -- see [`../deft-directive-triage/SKILL.md`](../deft-directive-triage/SKILL.md) (D6 / #1130) for the canonical cache-hygiene + \"what's next?\" queue playbook before continuing into the refinement flow below.\n\n**See also**: [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md) (canonical numbered-menu rule used by every Phase 0 / Phase 2-5 gate below) | `task cache:fetch-all` / `task cache:get` (Tier 1 unified content cache, #883 Story 2) | `task triage:bootstrap` / `task triage:accept` / `task triage:reject` / `task triage:defer` / `task triage:needs-ac` / `task triage:mark-duplicate` / `task triage:bulk-*` / `task triage:refresh-active` (Phase 0 action surface, #845 + #883 Story 3 rebind).\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 ingestion, origin freshness checks, and completion lifecycle all depend on `gh`.\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (Phase 0 Triage action menu, Phase 2 Evaluate per-item accept/reject, Phase 3 Reconcile flagged-item walk, Phase 4 Promote/Demote lifecycle gates, Phase 5 Prioritize reorder gates) 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 \"refinement\", \"reprioritize\", \"refine\", \"roadmap refresh\", or \"refresh roadmap\" (legacy v0.19 terms -- deft-directive-refinement is the current skill name)\n- User says \"triage\", \"action menu\", \"work the cache\", or \"pre-ingest\" -- first-class Phase 0 direct triggers introduced under #845; they route to Phase 0 (Triage), not the general refinement entry\n- New issues have accumulated since the last refinement session\n- Periodic maintenance pass (e.g. weekly or after a batch of user feedback)\n- User wants to review and organize the backlog\n\n! **Entry point (#1141, supersedes #845 / #883 action-menu).** Phase 0 -- Triage-first consultation is the canonical entry point for any refinement session. Phase 0 consults `task triage:summary` (D2 / #1122) and `task triage:queue --state=accept` (D11 / #1128) and pulls the `[RESUME]`-tagged slice (D3 / #1123) FIRST. Refinement does NOT itself triage cached candidates -- that work belongs to [`../deft-directive-triage/SKILL.md`](../deft-directive-triage/SKILL.md) (D6 / #1130). Phase 0 ! MUST chain into Phase 1 -- Ingest on completion (or surface the empty-cache fallback prompt when the cache has not yet been bootstrapped -- see Phase 0a below). Phase 1+ semantics are unchanged.\n\n## Prerequisites\n\n- ! `xbrief/` directory exists with lifecycle folders (`proposed/`, `pending/`, `active/`, `completed/`, `cancelled/`)\n- ! GitHub CLI (`gh`) is authenticated and can access the repo\n- ~ `PROJECT-DEFINITION.xbrief.json` exists (run `task project:render` if missing)\n\n## Session Model\n\nRefinement is a **conversational loop**, not a batch job. The user directs the flow:\n\n- \"Triage\" / \"action menu\" / \"work the cache\" / \"pre-ingest\" -> Phase 0 (Triage-first consultation, #1141) -- refinement consults the cache; the canonical decision-making playbook is `../deft-directive-triage/SKILL.md` (D6 / #1130)\n- \"Pull in issues\" / \"ingest\" -> Phase 0 ALWAYS runs first to consult `task triage:summary` + `task triage:queue --state=accept`; Phase 1 follows on the cohort Phase 0b produces (#1141)\n- \"Show proposed\" / \"evaluate\" -> Phase 2 (Evaluate)\n- \"Check origins\" / \"reconcile\" -> Phase 3 (Reconcile)\n- \"Accept these\" / \"reject that\" / \"promote\" / \"demote\" -> Phase 4 (Promote/Demote)\n- \"Reprioritize\" / \"reorder pending\" -> Phase 5 (Prioritize)\n- \"Close out\" / \"scope is done\" / \"completion\" -> Phase 6 (Completion Lifecycle)\n- \"Done\" / \"exit\" -> Exit\n\nThe agent may suggest the next phase, but the user decides. Phases can be entered in any order and repeated.\n\n## Branch Setup (Preflight)\n\n! Before making any changes, ensure you are working on a feature branch. This preflight runs before Phase 0 and again before Phase 1 if Phase 0 is auto-skipped.\n\n1. ! Check if the working tree has uncommitted changes that would conflict -- stop and ask the user to resolve them first\n2. ! Create or switch to a refinement branch (e.g. `refinement/YYYY-MM-DD`) if not already on one\n3. ! Confirm the branch and working directory to the user before proceeding\n\n## Phase 0 -- Triage-first consultation (cache-first, #1141)\n\n! Phase 0 is a thin consumer of the canonical triage cache: refinement consults `task triage:summary` (D2 / #1122) and `task triage:queue` (D11 / #1128) BEFORE walking any `xbrief/` lifecycle folder. The dedicated triage playbook lives at [`../deft-directive-triage/SKILL.md`](../deft-directive-triage/SKILL.md) (D6 / #1130) -- refinement does NOT itself triage cached candidates; it consumes the queue's `accept` and `[RESUME]` slices and turns them into scope xBRIEFs.\n\n! Phase 0 runs three sub-phases in canonical order: **Phase 0a -- Triage gate** -> **Phase 0b -- Cache-first ingestion** -> **Phase 0c -- Resume conditions**. Each sub-phase MUST run before the next, and Phase 0 MUST chain into Phase 1 -- Ingest on completion. Numbered prompts in Phase 0 ! MUST follow [`../../contracts/deterministic-questions.md`](../../contracts/deterministic-questions.md) (`Discuss` / `Back` as the final two numbered options; Discuss-pause semantic applies verbatim).\n\n**See also (#883 Story 2):** the unified cache (`task cache:fetch-all --source=github-issue --repo OWNER/NAME`) is the sole content-mirroring surface in v0.26.0+. Tier 1 reads MUST go through `task cache:get -- github-issue OWNER/NAME/<N>`. The legacy \"Three-Tier Inventory Model\" + action-menu walk that lived here pre-#1141 has moved out of refinement and into `../deft-directive-triage/SKILL.md` (D6 / #1130); refinement now consumes the post-decision queue rather than producing decisions.\n\n### Phase 0a -- Triage gate (`task triage:summary`)\n\n1. ! Invoke `task triage:summary` (D2 / #1122) and capture the one-liner.\n2. ! **Empty-cache backward-compat fallback.** If the one-liner is the documented empty-cache prompt (`[triage] cache empty -- run task triage:bootstrap`), the agent ! MUST emit the verbatim recovery message to stderr BEFORE any folder scan:\n\n ```\n triage cache empty -- run `task triage:welcome` (N3 / #1143) to onboard, or `task triage:bootstrap` to seed the cache directly; refinement Phase 0 cannot consult the queue against an empty cache. Falling back to a legacy `xbrief/proposed/` folder scan only if you opt in.\n ```\n\n Then prompt the user `Fall back to legacy folder-scan against xbrief/proposed/ for this session? [y/N]` (default `N`). On `N`, exit refinement with the canonical `deft-directive-refinement complete -- exiting skill.` confirmation and the chaining instruction `Run task triage:welcome (N3 / #1143) to onboard, then re-enter refinement.`. On `y`, chain into Phase 1 against `xbrief/proposed/` as the legacy fallback. ! MUST NOT silently proceed without surfacing the breadcrumb to `task triage:welcome` -- a fresh post-upgrade install needs that pointer to find the canonical onboarding ritual.\n\n3. ! **Outstanding-work gate.** If the cache is populated AND any of `untriaged`, `stale-defer (resume condition met)`, or `in-flight` is non-zero, surface the one-liner verbatim to the user with the canonical recommendation:\n\n ```\n triage cache has outstanding work -- recommend running `skills/deft-directive-triage/SKILL.md` (D6 / #1130) first. Proceed to refinement anyway? [y/N]\n ```\n\n ~ Default is `N`: deferring to the triage skill is the documented happy path because refinement consumes `accept`-decisioned candidates and an untriaged backlog means there are fewer `accept` rows than there could be. On `N`, exit with the canonical confirmation phrasing and the chaining instruction `Run skills/deft-directive-triage/SKILL.md to clear the backlog, then re-enter refinement.`. On `y`, proceed to Phase 0b.\n\n4. ? When all counts are zero (cache populated, no outstanding work), proceed to Phase 0b without prompting.\n\n⊗ Skip Phase 0a -- refinement on top of an untriaged cache wastes the operator's time on items the triage skill would have rejected, deferred, or marked needs-AC.\n⊗ Bypass the empty-cache fallback prompt -- a silent proceed against an empty cache surfaces a misleading \"no candidates\" state and hides the upgrade-onboarding path from the operator.\n\n### Phase 0b -- Cache-first ingestion (`task triage:queue --state=accept`)\n\n1. ! Pull the ingestion candidate list via `task triage:queue --state=accept` (D11 / #1128). Each row is a cached issue whose latest audit-log decision is `accept` -- the canonical \"ready to become a scope xBRIEF\" cohort. ! MUST NOT enumerate `xbrief/proposed/` independently of the queue; the folder participates only via the join described in step 2.\n2. ! Join the queue against `xbrief/proposed/` (and the rest of the lifecycle folders) by `references[].uri`: queue rows whose issue is already represented by an existing xBRIEF surface as \"already tracked\"; queue rows with no matching xBRIEF are \"new accept candidates\". Items already in `xbrief/proposed/` continue to participate -- they are joined against the cache rather than enumerated separately.\n3. ~ When the join surfaces zero new candidates (every `accept` row already has a xBRIEF), Phase 0b is a clean no-op; chain straight into Phase 0c.\n4. ! For each new candidate, fall through to Phase 1 -- Ingest, which delegates the actual scope-xBRIEF write to `task issue:ingest` (or `task triage:accept`, which already ingests into `proposed/`). After the proposed artifact exists, promote with `task scope:promote -- --from-issue=<N> [--repo OWNER/NAME]` (#1136 / D18), or chain accept+promote via `task triage:accept -- --issue <N> --repo OWNER/NAME --auto-promote` when the operator wants pending/ in one step.\n\n⊗ Walk `xbrief/proposed/` directly as the primary ingestion surface -- the cache is the authoritative \"what is ready to refine?\" surface; the folder is the destination, not the source of truth.\n⊗ Drop items that exist in `xbrief/proposed/` but lack a matching cache row -- those are reconciled later (Phase 3 / origin reconciliation), not silently discarded.\n\n### Phase 0c -- Resume conditions (`[RESUME]`-tagged items first)\n\n1. ! Before walking new untriaged candidates from Phase 0b, process every `[RESUME]`-tagged row in the queue. `[RESUME]` rows surface from D3 (#1123) when a prior `defer` audit entry's `resume-on` condition fires (atomics: `ref:closed:#N`, `ref:merged:#N`, `date:>=YYYY-MM-DD`, `pending-count:>=N|<=N`, composed by a single top-level `AND` or `OR`).\n2. ! Stale-defer (resume-eligible) items take priority over fresh untriaged when both are present in the same Phase 0 pass -- the operator made a forward-dated decision on the deferred item and the framework is honouring it. Treat the `[RESUME]` slice as the FIRST class of candidates surfaced to the user.\n3. ~ The exact precedence in `task triage:queue` is `[ORPHAN]` -> `[RESUME]` -> `[URGENT]` -> untriaged -> other (per D11 + D13 / #1132 grouping). Refinement consumes this order verbatim and surfaces `[RESUME]` candidates first; `[ORPHAN]` rows are out-of-scope for refinement (they are handled by the triage skill's audit phase).\n\n⊗ Treat `[RESUME]` rows as \"leftover\" -- they are the highest-priority class refinement is meant to process, because the operator already decided to revisit them when the condition fired.\n\n### Pre-Phase-1 handoff\n\n1. ! Surface a one-line session summary: `{resume_eligible} resume-eligible, {new_accept} new accept candidate(s), {already_tracked} already tracked in xbrief/`.\n2. ! Chain into Phase 1 -- Ingest, which now operates on the cohort produced by Phase 0b's join (`[RESUME]` rows first, then new accept candidates).\n3. ? If the user opts out of Phase 1 (e.g. \"that's it for today\"), exit via the Phase 0 mid-session exit surface below -- ! MUST NOT route to the `### EXIT` block under `## PR & Review Cycle` because that block is the post-PR-creation exit path and references a `PR #{N}` that does not yet exist at this point in the flow.\n\n#### Phase 0 mid-session exit surface\n\n! When the user opts out of Phase 1 after completing (or partially completing) Phase 0, perform exactly these steps -- ! MUST NOT mention any PR number, since none has been created yet:\n\n1. ! Surface the outstanding-work tally: `{resume_eligible} resume-eligible candidate(s) still pending, {new_accept} accept candidate(s) not yet ingested -- these will resurface on the next Phase 0 entry.`\n2. ! Note the audit-log location verbatim using double-backtick fencing so the inner path renders correctly: ``Audit log preserved at `xbrief/.eval/candidates.jsonl`; queue state is reproducible via `task triage:queue --state=accept`.``\n3. ! Confirm skill exit with the canonical phrasing: `deft-directive-refinement complete -- exiting skill.`\n4. ! Provide the Phase-0-appropriate chaining instruction: ``Resume with `task triage:queue --state=accept` to inspect the queue, or re-enter the refinement skill when ready to continue.`` Do NOT reference a PR, a review cycle, or a monitor agent.\n\n⊗ Skip Phase 1 silently after Phase 0 -- always render the chaining decision so the user knows the entry point shifted.\n⊗ Mutate `xbrief/proposed/` directly during Phase 0 -- only `task issue:ingest` (called from Phase 1) is allowed to write there; Phase 0 is read-only against the cache.\n⊗ Route Phase 0 mid-session opt-out to the post-PR `### EXIT` block under `## PR & Review Cycle` -- that block surfaces a non-existent `PR #{N}` and confuses the user.\n\n## Phase 1 -- Ingest\n\n! Scan external sources for new work items and create proposed scope xBRIEFs.\n\n! **Pre-filing master-diff check (#1102).** When a refinement pass FILES a new GitHub issue that proposes ADDING a file or directory (rather than ingesting an existing issue), first run the pre-filing existence check from [`../deft-directive-gh-slice/SKILL.md`](../deft-directive-gh-slice/SKILL.md) Step 5 -- `git ls-tree origin/master -- <path>` (or `gh api repos/{owner}/{repo}/contents/{path}`) -- so a stale \"add file X\" issue is never opened against state that already exists on master (the #1099 -> #1100 close-and-refile recurrence).\n\n### Step 1: Gather Sources\n\n1. ? Scan non-GitHub sources (Jira, direct user requests, etc.) manually if applicable — those ingest paths are not yet task-wrapped\n2. ! GitHub issues are ingested via the task wrapper documented in Step 3 — the task fetches open issues itself, so no separate `gh issue list` call is needed\n\n### Step 2: Deduplicate via References (Dry-Run Preview)\n\n1. ? Run `task issue:ingest -- --all --dry-run` to preview which issues the ingest task would create scope xBRIEFs for. The task deduplicates candidates against `references` entries in existing xBRIEFs (across all lifecycle folders) so already-tracked issues are skipped automatically.\n2. ! Present the user with the list of new-vs-already-tracked items the dry-run reports: \"{N} new items found, {M} already tracked\"\n3. ! Wait for user approval before proceeding to ingest\n\n### Step 3: Ingest Approved Items\n\n! Delegate ingest to `task issue:ingest` — the task is the canonical implementation of scope-xBRIEF creation. Skills MUST NOT reinvent the slug rules, reference shape, or deduplication logic inline (see #537 for background).\n\n- **Single issue**: `task issue:ingest -- <N>` — creates `xbrief/proposed/YYYY-MM-DD-<slug>.xbrief.json` with origin `references`, canonical slug from `scripts/slug_normalize.py` (see [`../../conventions/vbrief-filenames.md`](../../conventions/vbrief-filenames.md)), and schema-conformant shape.\n- **Batch**: `task issue:ingest -- --all [--label <L>] [--status <S>]` — ingests every open issue matching the filters, skipping duplicates by `references.uri` match.\n- **Preview**: add `--dry-run` to either form to preview without writing files.\n\nThe task emits xBRIEFs conforming to the canonical v0.6 schema (`xbrief/schemas/xbrief-core.schema.json`) with origin references in the form documented in [`../../conventions/references.md`](../../conventions/references.md):\n\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```\n\n- ! New scope xBRIEFs MUST target `\"xBRIEFInfo\": { \"version\": \"0.6\" }` (the task handles this automatically)\n- ! `plan.status` starts at `\"proposed\"`; the task sets this\n- ! Conform to `xbrief/schemas/xbrief-core.schema.json` (v0.6) -- the task validates before writing\n- ~ After ingest, review the generated xBRIEFs with the user before promoting any of them to `pending/`\n\n⊗ Hand-author scope xBRIEFs inside the skill when the ingest task exists — duplicating the narrative logic is how #534 (non-conformant references) and #537 (drift between skill and task) arise\n⊗ Write references with `url`/`id`/bare `github-issue` types — use the schema-conformant `{uri, type, title}` shape above\n⊗ Ingest an item that already has a matching xBRIEF reference -- `task issue:ingest` handles deduplication; skills MUST NOT duplicate that logic inline\n\n## Phase 2 -- Evaluate\n\n! List proposed items for interactive user review.\n\n### Step 1: List Proposed Items\n\n1. ! Read all xBRIEFs in `xbrief/proposed/`\n2. ! Present each item with:\n - Title and filename\n - Origin link(s) from `references`\n - Summary from `narratives` (if populated)\n - Labels/category (if available from origin)\n3. ! Sort by creation date (oldest first) or as user prefers\n\n### Step 2: Interactive Review\n\n! For each proposed item (or batch, as user directs):\n\n- ! Present the item and wait for user decision\n- ~ The user may: accept (promote to pending), reject (cancel), defer (keep in proposed), or request more detail\n- ! Do not proceed to the next item until the user responds\n- ? The user may batch-accept or batch-reject multiple items at once\n\n⊗ Auto-accept or auto-reject proposed items without user review\n\n## Phase 3 -- Reconcile (RFC D12)\n\n! Check if linked origins have changed since the xBRIEF was last touched. Delegate the scan to `task reconcile:issues` and walk the user through flagged items for approval (see #537 for why the skill is a thin wrapper over the task).\n\n### Step 1: Run the Reconciler\n\n```\ntask reconcile:issues\n```\n\nThe task scans every xBRIEF with a GitHub-backed reference (whether the reference uses the legacy `github-issue` bare type or the canonical `x-xbrief/github-issue` shape), fetches each linked issue, compares timestamps and state, and reports items in four buckets:\n\n- **Linked & current** — origin has not changed since the xBRIEF was last updated (no action)\n- **Stale** — origin `updatedAt` is newer than the xBRIEF (propose an update)\n- **Externally closed** — origin issue is `CLOSED` (propose cancellation or reconcile if intentional divergence)\n- **Unlinked** — xBRIEF has no GitHub reference (flag for review)\n\n### Step 2: Walk Flagged Items with the User\n\n1. ! For each **stale** item the task surfaces, show the user the diff between the current xBRIEF and the refreshed origin. Propose edits; ! wait for explicit user approval before writing anything.\n2. ! For each **externally closed** item, ask the user whether to `task scope:cancel <file>` it or preserve intentional divergence.\n3. ! For each **unlinked** item, ask whether to attach an origin reference or leave the xBRIEF as-is.\n\n### Step 3: Apply User-Approved Updates\n\n- ! Agent proposes edits; ! user approves each change\n- ! Never auto-update xBRIEFs — intentional divergence (xBRIEF refined beyond original issue scope) must be preserved\n- ! For approved updates, update the xBRIEF content and `xBRIEFInfo.updated` timestamp; prefer the task commands (`task scope:cancel`, `task scope:block`, etc.) over hand-editing where they apply\n\n⊗ Replace the task invocation with a hand-written `gh issue view` loop — the task is the canonical implementation; skills MUST NOT duplicate it (#537)\n⊗ Auto-update xBRIEFs based on origin changes without user approval\n⊗ Overwrite intentional divergence -- if a xBRIEF has been refined beyond the original issue, preserve the refinement\n\n### Origin sync after material xBRIEF edits (#2540)\n\n! When this refinement pass **materially updates** an origin-linked scope xBRIEF (AC, `plan.status`, or `plan.items` statuses/titles), run `task issue:sync-from-xbrief -- <path>` to post a sync comment on the linked GitHub issue so the human-facing tracker stays current. Use `--dry-run` to preview the comment without posting.\n\n! If sync is intentionally skipped (offline, issue frozen, divergence is deliberate), document the skip reason in the session notes or PR body — do not silently leave the origin stale.\n\n⊗ Materially edit an origin-linked xBRIEF without running `issue:sync-from-xbrief` or documenting why it was skipped\n\n## Phase 4 -- Promote/Demote\n\n! Move xBRIEFs between lifecycle folders using deterministic task commands. The status values below align with the canonical v0.6 Status enum (`draft | proposed | approved | pending | running | completed | blocked | failed | cancelled`) — note that `failed` is also a valid terminal transition for active work that could not complete.\n\n### Available Commands\n\n- `task scope:promote <file>` -- proposed/ -> pending/ (status: pending)\n- `task scope:activate <file>` -- pending/ -> active/ (status: running)\n- `task scope:complete <file>` -- active/ -> completed/ (status: completed)\n- `task scope:cancel <file>` -- any -> cancelled/ (status: cancelled)\n- `task scope:restore <file>` -- cancelled/ -> proposed/ (status: proposed)\n- `task scope:block <file>` -- stays in active/ (status: blocked)\n- `task scope:unblock <file>` -- stays in active/ (status: running)\n- `task scope:fail <file>` (v0.6+) -- active/ -> completed/ (status: failed) — record a failure terminal state when a scope cannot complete but should not be cancelled\n- `task scope:undo <decision_id>` (D15 / #1134) -- reverse a single scope-lifecycle audit entry (`demote` -> re-promote, `cancel` -> restore-from-cancelled-to-prior-folder, `restore` -> re-cancel); terminal actions (`complete` / `fail`) are REFUSED -- use `git revert` or hand-edit\n- `task scope:undo --batch-id=<uuid>` (D15 / #1134) -- reverse every audit entry tagged with the batch_id (e.g. the cohort produced by `task scope:demote --batch`); idempotent on already-undone entries; the undo cohort is itself reversible via the `undo_batch_id` minted on the new entries. Optional `--dry-run` previews without writing.\n- `task scope:undo --latest` (D15 / #1134) -- reverse the most-recent reversible audit entry (`demote` / `cancel` / `restore` / `undo`) not already undone; convenience form used by the N6 / #1146 smoketest contract.\n\n### Workflow\n\n1. ! Execute transitions using the task commands above -- they handle `plan.status` updates, `plan.updated` timestamps, and file moves atomically\n2. ! Derived-artifact renders (`task roadmap:render`, `task project:render`) happen after a **batch** of promotions/demotions, not after each individual item. During high-volume triage (e.g. dozens of accept/reject decisions in one session), defer both renders until the end of the batch -- the source of truth is the lifecycle folder contents under `xbrief/`, so ROADMAP.md and PROJECT-DEFINITION.xbrief.json can be refreshed once per batch without losing correctness.\n3. ! `task roadmap:render` regenerates ROADMAP.md from the updated lifecycle folder contents. Call it once per batch (typically at the end of Phase 4, before handing back to the user or transitioning to Phase 5), not after every single promote/demote.\n4. ! `task project:render` refreshes the PROJECT-DEFINITION items registry. Call it **once per refinement pass** -- usually at the end of the session alongside the final roadmap render -- unless the user explicitly needs an intermediate registry refresh. It is not a per-edit tax.\n5. ! Before the user is shown the final backlog state (end of Phase 4, end of Phase 5, or session exit), both `task roadmap:render` AND `task project:render` MUST have been run at least once so ROADMAP.md and PROJECT-DEFINITION.xbrief.json reflect the current lifecycle folder truth. This preserves correctness while allowing N promotions/demotions to share one render checkpoint.\n6. ! Mark rejected items as `cancelled` via `task scope:cancel` (never delete xBRIEFs)\n\n~ Operationally: a large refinement session can ingest/evaluate/promote multiple issues and close out with **one** final render checkpoint, rather than N repetitive renders after every individual item.\n\n⊗ Rerender derived artifacts (`task roadmap:render`, `task project:render`) after every single accept/reject/promote/demote during high-volume triage -- batch the lifecycle edits and render once at the end of the batch\n⊗ Move xBRIEFs between folders manually (cp/mv) -- always use `task scope:*` commands\n⊗ Delete xBRIEFs -- use `task scope:cancel` to preserve history\n\n## Phase 5 -- Prioritize\n\n! Reorder and organize the pending backlog.\n\n1. ! List all xBRIEFs in `xbrief/pending/` with titles, origins, and any phase/dependency metadata\n2. ~ Help the user set phases and dependencies:\n - Group related items into phases (via xBRIEF `items` hierarchy or `tags`)\n - Identify dependencies between items (via `edges` in xBRIEF schema)\n3. ! `task roadmap:render` is the **checkpoint** before showing the reordered backlog to the user -- not a per-edit tax. Run it ONCE at the end of the reorder pass to regenerate ROADMAP.md from the updated pending/ contents. Do not invoke it after each individual reorder action.\n4. ~ Present the regenerated roadmap summary to the user for confirmation\n\n## Phase 6 -- Completion Lifecycle\n\n! On scope completion, update origins to close the loop.\n\n### When a Scope Completes\n\n1. ! Read the completed xBRIEF's `references` array\n2. ! For each GitHub-issue reference (either the legacy bare `github-issue` type or the canonical `x-xbrief/github-issue` shape):\n - Close the issue with a comment linking to the implementing PR:\n ```\n gh issue close {N} --comment \"Completed via PR #{PR} -- scope xBRIEF: {filename}\"\n ```\n - The issue number is extracted from the reference `uri` (e.g. `https://github.com/o/r/issues/{N}`)\n3. ? For other reference types (`x-xbrief/jira-ticket`, `x-xbrief/user-request`, `x-xbrief/github-pr`, etc.), follow the appropriate update mechanism\n4. ! Update PROJECT-DEFINITION via `task project:render`\n\n⊗ Complete a scope without updating its origins\n~ Completion lifecycle can be triggered during refinement or as a standalone action after a PR merge\n\n! When the refinement session files a new umbrella issue (or surfaces one whose current-shape comment is missing), file the umbrella then file its `## Current shape (as of pass-N)` comment per `## Umbrella current-shape convention` in `AGENTS.md` (#1152) -- the edit-in-place comment is the canonical surface every subsequent design pass updates.\n\n! Before reporting an umbrella or epic's current status to the operator (what is done, what blocks, wave order), fetch `repos/<owner>/<repo>/issues/<N>/comments` via REST, read the `## Current shape (as of pass-N)` comment and any linked context/`LockedDecisions` xBRIEF — never conclude status from the issue body alone (claim-cites-state-surface, #2066).\n\n~ Issue-label hygiene for any umbrella or child issue this skill files: before creating issues, inspect the target repo's existing labels with `gh label list` or the labels API; choose one or more suitable existing labels when practical, or explicitly note that no label was applied. This is a recommendation, not a gate -- do not block issue creation solely because no label fits, and do not invent ad hoc labels outside the repo's existing label set.\n\n! When a refinement pass produces a slicing event (rare but possible -- e.g. a design pass on an existing umbrella files N additional Wave-N child issues), record the cohort in `xbrief/.eval/slices.jsonl` via `scripts/slice_record.py::write_slice(...)` with `actor=\"skill:refinement\"` immediately after the children are filed (#1132 / D13). Same call shape as `skills/deft-directive-gh-slice/SKILL.md` Step 6. The cohort record is what makes `task triage:audit --orphans` able to detect Wave-2+ children whose umbrella closes prematurely; without it the production-side drift this surface guards against re-fires. Skip when the pass produced no new child cohort (e.g. a pure re-prioritization).\n\n\n! When the umbrella + children were filed by hand (legacy `gh issue create` / `issue_write` MCP / prior pass-N runs that pre-date this skill's slicing phase), use the canonical retro verb `task slice:record-existing` (#1147 / N7) -- it wraps the same `slice_record.write_slice` helper with `actor=\"manual:operator\"`, takes `--umbrella=N --children=A,B,C [--wave-N=...]` flags, validates each issue via the N5 / #1145 `scm.call` shim, and is idempotent on a matching umbrella + child set (re-run is a no-op; `--force` writes a second record for legitimate multi-session slicing). Companion `task slice:list` enumerates persisted slices for verification. The backfill verb is the canonical retro path for cohorts D13's writer never saw.\n\n## CHANGELOG Convention\n\n- ! Write ONE batch `CHANGELOG.md` entry at the END of the full refinement session -- not one entry per xBRIEF created or promoted. The batch entry summarizes all changes made during the session.\n- ⊗ Add a CHANGELOG entry after each individual action during refinement -- wait until the full session is complete and write a single summary entry.\n\n## PR & Review Cycle\n\nAfter all refinement work is complete:\n\n1. ! Ask the user: \"Ready to commit and create a PR?\"\n2. ! Wait for explicit user confirmation before proceeding.\n\n### Pre-Flight (before pushing)\n\n! Run all pre-flight checks BEFORE committing and pushing:\n\n1. ! Verify `CHANGELOG.md` has an `[Unreleased]` entry covering the refinement changes\n2. ! Run `task check` -- all checks must pass\n3. ! Verify `.github/PULL_REQUEST_TEMPLATE.md` checklist is satisfiable for this PR. If the file is **missing**, do NOT block — copy the canonical template from `templates/PULL_REQUEST_TEMPLATE.md` (ship-with-deft) to `.github/PULL_REQUEST_TEMPLATE.md` in the consumer project, then proceed with pre-flight (#531). If the file exists but contains unsatisfiable checklist items for this PR, call them out to the user before pushing.\n4. ! **Mandatory file review**: Re-read ALL modified files before committing. Explicitly check for:\n - Encoding errors (em-dashes corrupted to replacement characters, BOM artifacts)\n - Unintended duplication (accidental double xBRIEFs or duplicate entries)\n - Structural issues (malformed xBRIEF JSON, broken references)\n - Semantic accuracy (verify that counts and claims in CHANGELOG entries match the actual data)\n\n### Commit, Push, and Create PR\n\n1. ! Commit with a descriptive message: `docs(xbrief): refinement session -- {summary}`\n2. ! Push the branch to origin\n3. ! Create a PR targeting the appropriate base branch\n\n### Review Cycle Handoff\n\n! After the PR is created, automatically sequence into `skills/deft-directive-review-cycle/SKILL.md`.\n\n- ! Inform the user: \"PR #{N} created -- starting review cycle.\"\n- ! Follow the full review cycle skill from Phase 1 (Deft Process Audit) onward.\n\n### EXIT\n\n! When the review cycle completes (exit condition met) or the PR is ready for human review:\n\n1. ! Explicitly confirm skill exit: \"deft-directive-refinement complete -- exiting skill.\"\n2. ! Provide chaining instructions to the user/agent:\n - If review cycle is complete and PR is approved: \"PR #{N} is ready for human merge review.\"\n - If review cycle is still in progress: \"Review cycle handed off to deft-review-cycle. Monitor PR #{N} for Greptile findings.\"\n - If returning to a monitor agent: \"Returning control to monitor agent -- refinement PR #{N} created and review cycle initiated.\"\n3. ! Do NOT continue into adjacent work after this point -- the skill boundary is an exit condition.\n\n## Anti-Patterns\n\n- ⊗ Bypass Phase 0 by walking `xbrief/proposed/` or `gh issue list` directly -- `task triage:queue --state=accept` (D11 / #1128) is the canonical ingestion-candidate surface (#1141)\n- ⊗ Skip Phase 0a's `task triage:summary` invocation -- the triage-gate decision (run the triage skill first vs proceed) depends on its output (#1141 / D2 / #1122)\n- ⊗ Silently proceed against an empty cache -- emit the canonical `task triage:welcome` (N3 / #1143) breadcrumb to stderr first (#1141)\n- ⊗ Treat `[RESUME]`-tagged items as leftover -- they are the highest-priority class refinement processes (#1141 / D3 / #1123)\n- ⊗ Skip Phase 1 silently after Phase 0 -- always render the chaining decision so the user knows the entry point shifted (#1141, supersedes #845)\n- ⊗ Auto-accept or auto-reject proposed items without user review\n- ⊗ Create xBRIEFs without origin provenance (`references` linking to the source)\n- ⊗ Ingest items without deduplicating against existing xBRIEF references first\n- ⊗ Auto-update xBRIEFs based on origin changes -- user approves all updates\n- ⊗ Overwrite intentional divergence when reconciling stale origins\n- ⊗ Move xBRIEFs between folders manually -- always use `task scope:*` commands\n- ⊗ Delete xBRIEFs -- use `task scope:cancel` to preserve history\n- ⊗ Complete a scope without updating its origins (closing issues, posting comments)\n- ⊗ Skip deduplication during ingest -- always diff against existing references\n- ⊗ Add a CHANGELOG entry per individual action during refinement -- write one batch entry at the end of the full session\n- ⊗ Proceed to the next proposed item without waiting for user decision during evaluate\n- ⊗ Auto-push without explicit user instruction\n- ⊗ Rerender ROADMAP.md or PROJECT-DEFINITION.xbrief.json after every single accept/reject/promote/demote during high-volume triage -- `task roadmap:render` and `task project:render` are batch checkpoints, not per-edit taxes, and calling them N times for N lifecycle edits turns O(1) render work into O(N) without changing correctness (see #638)\n- ⊗ Return a final backlog view to the user without having run `task roadmap:render` and `task project:render` at least once since the last lifecycle edit -- batch the renders, but do not skip them\n\n## See also\n\n- Upstream skill: [`../deft-directive-triage/SKILL.md`](../deft-directive-triage/SKILL.md) (D6 / #1130) -- the canonical triage hygiene + queue selection playbook. Refinement Phase 0a consults `task triage:summary` (D2 / #1122) and Phase 0b consumes `task triage:queue --state=accept` (D11 / #1128), both of which are produced by the triage skill's decision flow. `[RESUME]`-tagged items (Phase 0c) originate from D3 (#1123) `--resume-on` conditions documented in the triage skill's Phase 3.\n- Reversibility verb in Phase 4: `task scope:undo <file>` (D15 / #1134).\n- Onboarding (empty-cache fallback target): `task triage:welcome` (N3 / #1143) -- the single chained command a fresh post-upgrade install runs before re-entering refinement.\n- Refs: #1141 (this rewrite), #1119 (umbrella), #1122 (D2), #1128 (D11), #1123 (D3), #1130 (D6), #1134 (D15), #1143 (N3), #1149 (N9 routing).\n",
209
209
  "frontmatter_extra": "triggers:\n - refinement\n - reprioritize\n - refine\n - roadmap refresh\n - refresh roadmap\n - triage\n - action menu\n - work the cache\n - pre-ingest"
210
210
  },
211
211
  {
@@ -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 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\n## Probe-then-fill remote claims (#3120)\n\n! Before filling any **remote** handoff field (PR URL, PR number, commit/HEAD SHA, CI green/success, review score) or claiming `status: pass` / ship/gate done, MUST **probe then fill**:\n\n1. Run same-turn `git` + forge probes (examples: `git rev-parse HEAD`, `gh api repos/<owner>/<repo>/pulls/<N>`, `task pr:watch -- <N> --one-shot`, checks API).\n2. Copy IDs / URLs / SHAs / scores **only** from that probe JSON/text into the evidence block.\n3. Set `proof_status: bound` and attach short raw probe snippets (`command` + `snippet`) for each remote claim.\n\n! Handoff evidence axes: **work** (local) / **ship** (pushed branch or PR) / **gate** (CI/review on HEAD). `proof_status` is `bound` | `unbound` | `n/a-no-remote-claim`.\n! **Legal partial:** local work `done` + ship `not_started` / `blocked` **without** PR/SHA/CI/review fields and `proof_status: n/a-no-remote-claim` (or `status: partial`) is valid — do not invent ship state.\n! **Fail ranking:** **invented-done** (false/unbound remote artifacts under pass) is **stricter** than **empty-done**. Unbound remote claims → invalid evidence (fail), not pass-with-notes.\n! Machine check: `validateHandoffEvidence` in `packages/core/src/handoff-evidence/` (see `templates/agent-prompt-preamble.md` §11).\n⊗ Fill PR / SHA / CI / review fields from recollection, narration, or prior-turn memory.\n⊗ Claim `status: pass` with remote fields when `proof_status` is not `bound` or probes are missing (#3120).\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- ⊗ Invent remote PR/SHA/CI/review claims in handoff evidence without same-turn probe binding — invented-done (#3120)\n- ⊗ Fill remote ship/gate fields from memory when only local work completed; legal partial omits PR fields (#3120)\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`, Claude Code `Agent`, `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`) when the current agent is the top-level owner of that primitive (not a nested leaf — see Cursor leaf boundary). On Claude Code, top-level parents/orchestrators use the `Agent` tool with `run_in_background: true` (register primitive `claude-agent`, #3134); implementation leaves follow the Claude Code leaf boundary (blocking `pr:watch` or `stop-at: pr-open` sibling), not nested Agent. This generalizes the Approach-1 sub-agent monitor rule to implementation and fix workers as well — 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, per #2876 for OpenClaw `sessions_spawn`, and per #3134 for Claude Code `claude-code` / `claude-agent`). Probe the environment (tool set + env vars) to obtain the stable platform descriptor (`grok-build`, `warp-orchestrated`, `warp-manual`, `cursor-composer`, `cursor-cloud-agent`, `claude-code`, `openclaw`, etc.) from the launch adapter / `get_platform_capabilities` and map the descriptor to the appropriate tier + dispatch primitive (`start_agent`, `spawn_subagent`, the Cursor `Task` tool, Claude Code `Agent` / `claude-agent`, or OpenClaw `sessions_spawn`). The descriptor (not hard-coded tool presence) is the single source of truth for both launch and review monitoring.\n\n- **Tier 1 (orchestrated sub-agent)** → Approach 1 (spawn review-monitor sub-agent via the primitive matching the descriptor: `start_agent`, `spawn_subagent`, the Cursor `Task` tool with `run_in_background: true`, Claude Code `Agent` with `run_in_background: true` / register `claude-agent`, or OpenClaw `sessions_spawn`)\n- **Tier 2 (no sub-agent primitive, but scheduler/timer/auto-reinvocation)** → 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 `claude-code` (Claude-unique `Agent` / `CLAUDECODE` / `DEFT_PROBE_CLAUDE_CODE` signals), treat as **Tier 1 with the backgrounded Claude Code `Agent` poller path** (#3134) — NOT Tier 3 and NOT `cursor-composer` (bare `Task` is not a Claude-unique signal). If the descriptor is `openclaw` (`sessions_spawn` present), treat as **Tier 1 with the backgrounded `sessions_spawn` poller path** (#2876) — 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|claude-agent|sessions_spawn|openclaw-sessions-spawn`). Release with the matching release form (CLI: `deft review-monitor:release --pr <N>`; task: `task deft:review-monitor:release -- --pr <N>`) when done. Exit `0` ready / `1` not ready or held-by-other / `2` config. The sole source of truth is the sticky GitHub PR comment (`<!-- deft:review-owner -->`); legacy `.deft/review-monitor.json` is obsolete and ignored. On register conflict, attach to the existing owner or stop — 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! **Claude Code leaf boundary (#3134 / #2797 analogue):** Nested `Agent` (implementation leaf spawning a second-level review-monitor Agent) is unsupported/unreliable on some Claude Code surfaces. A Claude Code `drive-to: merge-ready` leaf MUST either keep ownership in the same agent by blocking on `deft pr:watch <N>` (or `task deft:pr:watch -- <N>` when include-present), or its envelope MUST instead be `stop-at: pr-open` so the orchestrator can spawn and register a sibling review-monitor with `--platform-primitive claude-agent`. ⊗ Background a nested Agent poller from an implementation leaf and exit claiming monitoring is active. Top-level parents/orchestrators that own the `Agent` primitive MAY still Approach-1 background a review-monitor Agent.\n\n**Approach 1 (preferred -- sub-agent orchestration available per platform descriptor):**\n\n! **Background dispatch (#1880 / #2876 / #3134):** Spawn the review-monitor sub-agent via the matching primitive IN THE BACKGROUND (Cursor: Task `run_in_background: true`; Claude Code: `Agent` `run_in_background: true`; Grok Build: `spawn_subagent` with parent yielding; OpenClaw: `sessions_spawn` with parent yielding). The parent MUST remain interactive while the poller runs — never block the parent OpenClaw/Cursor/Claude Code/Grok session for >~3 min of monitor ownership.\n\n! **Heartbeat contract for Cursor pollers (#1877 / #1166 / #2876 / #3134):** Claude Code `Agent` and OpenClaw `sessions_spawn` pollers share this contract. A Cursor `Task`, Claude Code `Agent`, or OpenClaw `sessions_spawn` review-monitor poller whose loop runs > ~3 min MUST honour the sub-agent heartbeat contract (`docs/subagent-heartbeat.md`), same as the `spawn_subagent` path — emit periodic progress so the parent can distinguish a live poller from a hung one.\n\n~ **Visible Control UI (OpenClaw / #3044):** When OpenClaw Control UI is the operator control plane, SHOULD spawn the review-monitor with `visible:true` when the tool surface allows so humans can inspect progress without attaching to the parent session; invisible empty settles are higher FC04 residual risk.\n\n! When the platform descriptor indicates Tier 1 (sub-agent support), spawn a review-monitor sub-agent using the primitive matching the descriptor:\n\n1. ! Launch via the matching primitive: `start_agent` (Warp), `spawn_subagent` (grok-build / TUI / non-Warp), the Cursor `Task` tool with `run_in_background: true` (`cursor-composer` / `cursor-cloud-agent`, #1877), the Claude Code `Agent` tool with `run_in_background: true` (`claude-code` / register `claude-agent`, #3134), **or OpenClaw `sessions_spawn` (`openclaw`, #2876)** with a prompt that instructs it to poll for Greptile completion. For `spawn_subagent`, Cursor `Task`, Claude Code `Agent`, and OpenClaw `sessions_spawn` the prompt MUST reference the canonical poller template `templates/swarm-greptile-poller-prompt.md` (with placeholders filled) plus the agent preamble; the working directory / context must be the PR branch (worktree or equivalent for hybrid).\n2. ! The sub-agent polls using the mechanism for its primitive: for `spawn_subagent` use `get_command_or_subagent_output` (adaptive cadence: ~20-30s first check after push, ~60s second, ~90s thereafter; Greptile typically lands in 3-7 min); for `start_agent` the native messaging path; for the Cursor `Task` tool the backgrounded-task completion-notification path; for Claude Code `Agent` the backgrounded-agent completion-notification path; for OpenClaw `sessions_spawn` the host session completion / messaging channel (prefer `task pr:watch` inside the child when available). Front-load the first check to catch fast reviews.\n3. ! When the exit condition is met (Greptile review current on the HEAD commit SHA, confidence meets resolved min (policy/dogfood/default; see Step 6 #3095), no P0/P1 remaining), the sub-agent reports completion back to the parent (via `send_message_to_agent`, the spawn_subagent result channel, or the OpenClaw sessions completion channel).\n4. ! The main conversation pane stays fully interactive during monitoring -- the user (or parent monitor) can continue other work.\n5. ! On receiving the completion message / result, the parent re-fetches findings (both gh pr view --comments and the secondary source) and proceeds to Step 5.\n\n⊗ 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`, Claude Code `Agent`, `start_agent`):\n\n1. ! Read the sticky lease (dual-invoke `verify:review-monitor` when available, else `gh api` issues comments for `<!-- deft:review-owner -->`).\n2. ! List active same-PR / same-`taskName` subagents when the host exposes that surface (OpenClaw `subagents list` or equivalent).\n3. ⊗ 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\n## Probe-then-fill remote claims (#3120)\n\n! Before filling any **remote** handoff field (PR URL, PR number, commit/HEAD SHA, CI green/success, review score) or claiming `status: pass` / ship/gate done, MUST **probe then fill**:\n\n1. Run same-turn `git` + forge probes (examples: `git rev-parse HEAD`, `gh api repos/<owner>/<repo>/pulls/<N>`, `task pr:watch -- <N> --one-shot`, checks API).\n2. Copy IDs / URLs / SHAs / scores **only** from that probe JSON/text into the evidence block.\n3. Set `proof_status: bound` and attach short raw probe snippets (`command` + `snippet`) for each remote claim.\n\n! Handoff evidence axes: **work** (local) / **ship** (pushed branch or PR) / **gate** (CI/review on HEAD). `proof_status` is `bound` | `unbound` | `n/a-no-remote-claim`.\n! **Legal partial:** local work `done` + ship `not_started` / `blocked` **without** PR/SHA/CI/review fields and `proof_status: n/a-no-remote-claim` (or `status: partial`) is valid — do not invent ship state.\n! **Fail ranking:** **invented-done** (false/unbound remote artifacts under pass) is **stricter** than **empty-done**. Unbound remote claims → invalid evidence (fail), not pass-with-notes.\n! Machine check: `validateHandoffEvidence` in `packages/core/src/handoff-evidence/` (see `templates/agent-prompt-preamble.md` §11).\n⊗ Fill PR / SHA / CI / review fields from recollection, narration, or prior-turn memory.\n⊗ Claim `status: pass` with remote fields when `proof_status` is not `bound` or probes are missing (#3120).\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- ⊗ Route Claude Code babysit/shepherd/watch to Approach 3 blocking poll when Claude `Agent` spawn is available — use Approach 1 with backgrounded `Agent` / `claude-agent` (#3134)\n- ⊗ Misclassify Claude Code as `cursor-composer` from bare `Task` alone (#3134)\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- ⊗ Invent remote PR/SHA/CI/review claims in handoff evidence without same-turn probe binding — invented-done (#3120)\n- ⊗ Fill remote ship/gate fields from memory when only local work completed; legal partial omits PR fields (#3120)",
251
251
  "frontmatter_extra": null
252
252
  },
253
253
  {
@@ -256,10 +256,7 @@
256
256
  "triggers": [
257
257
  "setup",
258
258
  "bootstrap",
259
- "onboard",
260
- "revisit experimental rules",
261
- "experimental rules",
262
- "experimental meta"
259
+ "onboard"
263
260
  ],
264
261
  "path": "skills/deft-directive-setup/SKILL.md",
265
262
  "version": "0.1",
@@ -276,7 +273,7 @@
276
273
  ],
277
274
  "path": "skills/deft-directive-swarm/SKILL.md",
278
275
  "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\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",
276
+ "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| `claude-code` | Claude `Agent` (`run_in_background`) / `claude-agent` | [`references/host-claude-code.md`](references/host-claude-code.md) |\n| `openclaw` | `sessions_spawn` | [`references/host-openclaw.md`](references/host-openclaw.md) |\n| `grok-build` | `spawn_subagent` | [`references/host-grok-build.md`](references/host-grok-build.md) |\n| `generic-terminal` (or explicit cloud) | serial / paste / `oz agent run-cloud` | [`references/host-generic.md`](references/host-generic.md) |\n\n### Core reference index (host-neutral)\n\n| Phase / topic | File |\n|---------------|------|\n| Phase 0 — 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 / hard-stop #3131)\n\n! After any leaf completion event (`subagent_announce` / parent-push / host completion notify), the parent’s **first response** MUST be one of:\n- tool-first ground-truth batch (`gh` / `git` / worktree or file status) then one consolidate, **or**\n- host yield (`sessions_yield` on OpenClaw, or equivalent), **or**\n- one short user answer that is **not** a repeated progress line.\n\n! **Hard-stop (machine-checkable, not prose-only):** **MUST NOT** emit N>2 near-identical assistant sentences (or streaming text chunks) in one turn with no `tool_use` / yield — **FC14** text-repetition hang. Library: `evaluateParentTurnShape` in `@deftai/directive-core/parent-turn-shape` (`packages/core/src/parent-turn-shape/`). Hosts SHOULD abort the turn when `ok === false`. Operator recovery: `docs/openclaw-agent-host.md` § Operator recovery — FC14. Soft skill text is **not** sole mitigation (#3131).\n\n! **Thin DONE = failed leaf:** completion without PR URL / merge evidence is **failed** (re-dispatch or take over) — 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⊗ N>2 near-identical assistant sentences with no tool_use / yield (FC14 / #3131 hard-stop).\n⊗ Treat thin DONE (no PR URL / merge evidence) as success (#2943).\n⊗ Rely on soft skill prose alone as the sole mitigation for the parent hang (#3131).\n\n\n\n### Completion latch after first consolidate (#3092)\n\n! After the parent emits **one** user/caller-visible consolidate for a child `runId` / settle batch, **identical or equivalent completion replay** for the same key MUST be **silent** (no tools, no re-QC, no second final; host silent token when defined, e.g. OpenClaw `NO_REPLY`). Re-open only on new `runId`/batch, principal explicit reopen, or materially new evidence (new HEAD, new blocker class). Replay storms: at most one fail-loud note, then silent. Full MUST: `templates/agent-prompt-preamble.md` §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). Require Cursor signals (`CURSOR_*` or Cursor-only Task surface) — not bare `Task` alone.\n4. ! **Probe for Claude Code** — Tier 1; descriptor `claude-code` (#3134). Claude-unique signals only: `Agent` (or `CreateAgent` / `SubagentStart`) with background / `run_in_background`, and/or `DEFT_PROBE_CLAUDE_CODE` / `DEFT_AGENT_RUNTIME=claude-code` / `CLAUDECODE`. ⊗ Misclassify as `cursor-composer` via bare `Task`.\n5. ! **Probe for the OpenClaw `sessions_spawn` tool** — Tier 1; descriptor `openclaw` (#2875). Do NOT misclassify as `grok-build` or `generic-terminal`.\n6. ! **Probe for `spawn_subagent` tool** — descriptor `grok-build`.\n7. ! **Select launch path automatically** — load the matching host adapter (route table). No static A/B/C menu.\n8. ! **Return a stable platform descriptor** for Phase 4/6: `warp-orchestrated`, `warp-manual`, `cursor-composer`, `cursor-cloud-agent`, `claude-code`, `openclaw`, `grok-build`, or `generic-terminal`.\n9. ? **Cloud escape hatch** — `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⊗ Classify Claude Code as `cursor-composer` / `generic-terminal` when Claude-unique signals are present (#3134).\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- ⊗ N>2 near-identical assistant sentences with no tool_use / yield (FC14 / #3131 hard-stop)\n- ⊗ Treat thin DONE (no PR URL / merge evidence) as success (#2943)\n- ⊗ Rely on soft skill prose alone as the sole parent-hang mitigation (#3131)\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- ⊗ Misclassify Claude Code as `cursor-composer` / `generic-terminal` (#3134)\n\nFull anti-pattern list: [`references/core-ops.md`](references/core-ops.md).",
280
277
  "frontmatter_extra": null
281
278
  },
282
279
  {
@@ -311,7 +308,7 @@
311
308
  ],
312
309
  "path": "skills/deft-directive-triage/SKILL.md",
313
310
  "version": "0.1",
314
- "body": "# Deft Directive Triage\n\nTriage-cache hygiene + \"what's next?\" work selection (ordered plan or ranked queue). Operates against the unified `.deft-cache/github-issue/` mirror (#883 Story 2) and the append-only `xbrief/.eval/candidates.jsonl` audit log (#845 Story 2); writes only via the canonical `task triage:*` verbs.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.\n\n## Platform Requirements\n\n! Requires **GitHub** as the SCM platform and the **GitHub CLI (`gh`)** authenticated against the active project's repo -- the cache surface (`task cache:fetch-all`) and the read-side gate (`task verify:cache-fresh`) both depend on it.\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (Phase 2 candidate selection, Phase 3 per-item decision walk) ! 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 are `Discuss` and `Back`, in that order, and the Discuss-pause semantic from the contract applies verbatim -- on `Discuss` the agent halts the in-progress sequence and resumes only on an explicit user signal.\n\n## Work selection fork (#2542 / #2402)\n\nDirective does not guess your mix: **ordered plan** (`task plan-sequence:*`) when you know the next units in order, or **ranked queue** (`task triage:queue`) when picking from the backlog. Labels bias the queue; they do not override an active plan.\n\n! Before Phase 2 on bare \"what's next?\", run `task plan-sequence:current`. Active sequence → that entry only; exhausted → fail closed. Explicit \"what's the queue?\" / \"build a cohort\" → Phase 2. See `commands.md` § Backlog Triage → Two paths.\n\n## Phase 0 -- Sync\n\n! Probe cache freshness before doing any classification or selection. Stale cache reads produce stale decisions; the gate is the contract.\n\n1. ! Run `task verify:cache-fresh` (D5 / #1127). Exit 0 -> proceed to Phase 1. Exit 1 (stale or blocked) -> refresh per the printed remediation. Exit 2 (no bootstrap) -> run `task triage:bootstrap` first. When the cache has zero entries, read paths auto-fetch from GitHub first (#2575).\n2. ~ Refresh path: `task cache:fetch-all -- --source=github-issue --repo OWNER/NAME` for an already-bootstrapped project; `task triage:bootstrap` for a first-time seed.\n3. ~ If `xbrief/active/*.xbrief.json` references are in play, run `task triage:refresh-active` to surface drift before the queue is rendered.\n4. ~ When the session one-liner carries `[scope-drift] N` (D14 / #1133), run `task triage:scope-drift` and choose subscribe / ignore before walking the queue.\n5. ⊗ Walk the queue against a stale cache -- the audit log will record decisions against bodies the operator never actually saw.\n\n## Phase 1 -- Classify\n\n! Inspect the auto-classification audit log so manually-decided items are not re-walked, and surface anomalies before the queue render.\n\n1. ! Run `task triage:classify --list` (D10 / #1129) to render effective rules and hold-markers.\n2. ! Walk recent `xbrief/.eval/candidates.jsonl` entries for anomalies (classifier disagreement, repeated defer, stale needs-ac); surface before Phase 2; do NOT auto-fix.\n3. ~ Scope widen/narrow via `task triage:scope --list` (D12 / #1131); edits belong in PROJECT-DEFINITION.\n4. ~ Label hygiene: recommend repo labels via `gh label list` when unlabeled; do not invent labels or block creation solely for missing labels.\n5. ⊗ Re-classify terminally decided items without operator approval -- supersession is `task triage:reset <N>` only.\n\n## Phase 2 -- Present\n\n! Apply the Work selection fork gate (#2542): when no ordered-plan is active, render `task triage:queue` before suggesting work (#1149). Active sequence yields to the ordered-plan entry (#2402).\n\n1. ! Run `task triage:queue --limit=N` (D11 / #1128) -- default `N=10`. Groups `[RESUME]` -> `[URGENT]` -> untriaged -> other; ranking via `plan.policy.triageRankingLabels[]`, tiebreak `updated_at` desc.\n2. ! For per-item detail, run `task triage:show <N>` (default) or `task triage:show --format=operator <N>` (#2890) -- cached payload, latest decision, audit timeline, active-xBRIEF flag; operator format is the pasteable Phase 3 brief backbone. Exit 0 on hit, 1 on cache miss (re-sync per Phase 0).\n3. ~ Present the ranked **queue listing** verbatim; do NOT silently re-rank, drop, or annotate the listing beyond the canonical renderer. This queue non-annotation rule does **not** forbid Phase 3 per-candidate operator briefs or leans (see Phase 3 / #2890).\n4. ⊗ Recommend a specific issue without `task triage:queue` first, or an issue absent from the queue without `task triage:show` to surface why.\n\n## Phase 3 -- Decide\n\n! Walk per-item decisions through the canonical `task triage:*` verbs (tasks own audit-log append / schema / `xbrief/proposed/` write).\n\n! **Operator brief (same turn as menu) (#2890 / #3116):** Before every per-item decision menu, present an operator brief in the **same operator-visible message/surface** as the menu, containing at least: **URL-first** lead (canonical issue URL as the first line for that item, or `#N title` + URL); labels (or explicit none); **current-state validity** (`still-open` | `partial` | `likely-shipped` | `needs-re-scope`) + one-line evidence (linked closed PR, code path, or \"no evidence of fix\"); 2–5 line problem/context summary; AC bullets or explicit \"thin body / no AC\"; agent **lean** + one-line why (Accept / Defer / Reject / Needs-AC / …). ~ Prefer `task triage:show --format=operator <N>` as the brief backbone (URL-first + validity placeholder); agent still owns validity verdict and lean. ⊗ Menu-only or chip-only Phase 3 turns without that brief. ⊗ Brief-only turn followed by a later chip/menu-only turn that does not restate the brief. ⊗ Body-only summary without validity check against current master, closed children, or linked PRs.\n\n! **Host structured-question adapter:** On chips / `ask_user` / similar UIs (e.g. OpenClaw `ask_user`), keep the prose brief in chat; structured options are **actions only** (Accept / Defer / Reject / Needs-AC / Mark duplicate / Discuss / Back). Option labels ≉ substitute for the brief.\n\nFor each candidate, render the canonical numbered action menu and dispatch:\n\n```\nWhat would you like to do with this candidate?\n 1. Accept -- `task triage:accept <N>`\n 2. Reject -- `task triage:reject <N>`\n 3. Defer -- `task triage:defer <N> [--resume-on <event>]`\n 4. Needs-AC -- `task triage:needs-ac <N>`\n 5. Mark duplicate -- `task triage:mark-duplicate <N> <of-issue>`\n 6. Discuss\n 7. Back\n```\n\n- ! Map user replies only to the displayed number (`1`-`7`) or exact displayed option text. ⊗ Do NOT infer from alphabetic host affordances or bare letters such as `d` / `b` unless those letters were visibly rendered as choices.\n- ! On `Discuss`, halt immediately, prompt `What would you like to discuss?`, resume only on explicit user signal. ⊗ Implicit resumption.\n- ! On `Back`, un-buffer prior selection and re-render its action menu only before a `task triage:*` dispatch; after dispatch use `task triage:reset`.\n- ~ Bulk: `task triage:bulk-{accept,reject,defer,needs-ac}`; results still flow through the audit log.\n- ⊗ Write to `xbrief/proposed/` directly -- only `task triage:accept` is authorised.\n\n## Phase 4 -- Audit\n\n! Confirm the session's decisions landed coherently before exiting the skill.\n\n1. ! Run `task triage:audit --format=json` (D11 / #1128); optional `#1180` filters `--since` / `--action`. Transform with `jq` -- framework does not compute trends.\n2. ! Run `task triage:summary` (D2 / #1122) -- `[triage] N untriaged · S stale-defer · M in-flight · WIP X/Y [⚠] [· [scope-drift] N]`.\n3. ~ Non-zero `[scope-drift]` → surface `task triage:scope-drift` + subscribe/unsubscribe/ignore remediation; then `task triage:bootstrap -- --resume`.\n4. ~ Stale accept (no active xBRIEF ref) → re-ingest or `task triage:reset`.\n5. ⊗ Skip Phase 4 audit.\n6. ! Umbrella/epic status: REST comments → `## Current shape (as of pass-N)` (#2066 / #1152); never body alone.\n\n## Reversibility\n\n! Undo via `task triage:reset <N>` (Layer 5; history never deleted). ⊗ Edit/delete `xbrief/.eval/candidates.jsonl` to \"undo\".\n\n## Anti-Patterns\n\n- ⊗ Recommend work without `task triage:queue` (#1149).\n- ⊗ Conclude \"nothing to do\" from folder scans or live GitHub alone (#2576).\n- ⊗ Stale-cache walk; reimplement audit/`proposed/` writes; treat defer/needs-ac as terminal; edit candidates.jsonl; menu-only Phase 3 without operator brief (#2890); body-only brief without URL-first or current-state validity (#3116).\n\n## EXIT\n\n! On opt-out: `deft-directive-triage complete -- exiting skill.` Chain: `deft-directive-refinement` (accepted items) · `deft-directive-swarm` (cohort) · `task cache:fetch-all` then re-enter. ⊗ Silent exit.\n\n## References\n\n- #1119 D6; #1128 D11 (`triage:queue` / `show` / `audit`); #2890 Phase 3 operator brief; #3116 validity + URL-first; #1122 / #1123 / #1127 / #1129 / #1131\n- Siblings: `deft-directive-refinement`, `deft-directive-swarm`, `deft-directive-sync`\n",
311
+ "body": "# Deft Directive Triage\n\nTriage-cache hygiene + \"what's next?\" work selection (ordered plan or ranked queue). Operates against the unified `.deft-cache/github-issue/` mirror (#883 Story 2) and the append-only `xbrief/.eval/candidates.jsonl` audit log (#845 Story 2); writes only via the canonical `task triage:*` verbs.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.\n\n## Platform Requirements\n\n! Requires **GitHub** as the SCM platform and the **GitHub CLI (`gh`)** authenticated against the active project's repo -- the cache surface (`task cache:fetch-all`) and the read-side gate (`task verify:cache-fresh`) both depend on it.\n\n## Deterministic Questions Contract\n\n! Every numbered-menu prompt rendered in this skill (Phase 2 candidate selection, Phase 3 per-item decision walk) ! 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 are `Discuss` and `Back`, in that order, and the Discuss-pause semantic from the contract applies verbatim -- on `Discuss` the agent halts the in-progress sequence and resumes only on an explicit user signal.\n\n## Work selection fork (#2542 / #2402)\n\nDirective does not guess your mix: **ordered plan** (`task plan-sequence:*`) when you know the next units in order, or **ranked queue** (`task triage:queue`) when picking from the backlog. Labels bias the queue; they do not override an active plan.\n\n! Before Phase 2 on bare \"what's next?\", run `task plan-sequence:current`. Active sequence → that entry only; exhausted → fail closed. Explicit \"what's the queue?\" / \"build a cohort\" → Phase 2. See `commands.md` § Backlog Triage → Two paths.\n\n## Phase 0 -- Sync\n\n! Probe cache freshness before doing any classification or selection. Stale cache reads produce stale decisions; the gate is the contract.\n\n1. ! Run `task verify:cache-fresh` (D5 / #1127). Exit 0 -> proceed to Phase 1. Exit 1 (stale or blocked) -> refresh per the printed remediation. Exit 2 (no bootstrap) -> run `task triage:bootstrap` first. When the cache has zero entries, read paths auto-fetch from GitHub first (#2575).\n2. ~ Refresh path: `task cache:fetch-all -- --source=github-issue --repo OWNER/NAME` for an already-bootstrapped project; `task triage:bootstrap` for a first-time seed.\n3. ~ If `xbrief/active/*.xbrief.json` references are in play, run `task triage:refresh-active` to surface drift before the queue is rendered.\n4. ~ When the session one-liner carries `[scope-drift] N` (D14 / #1133), run `task triage:scope-drift` and choose subscribe / ignore before walking the queue.\n5. ⊗ Walk the queue against a stale cache -- the audit log will record decisions against bodies the operator never actually saw.\n\n## Phase 1 -- Classify\n\n! Inspect the auto-classification audit log so manually-decided items are not re-walked, and surface anomalies before the queue render.\n\n1. ! Run `task triage:classify --list` (D10 / #1129) to render effective rules and hold-markers.\n2. ! Walk recent `xbrief/.eval/candidates.jsonl` entries for anomalies (classifier disagreement, repeated defer, stale needs-ac); surface before Phase 2; do NOT auto-fix.\n3. ~ Scope widen/narrow via `task triage:scope --list` (D12 / #1131); edits belong in PROJECT-DEFINITION.\n4. ~ Label hygiene: recommend repo labels via `gh label list` when unlabeled; do not invent labels or block creation solely for missing labels.\n5. ⊗ Re-classify terminally decided items without operator approval -- supersession is `task triage:reset <N>` only.\n\n## Phase 2 -- Present\n\n! Apply the Work selection fork gate (#2542): when no ordered-plan is active, render `task triage:queue` before suggesting work (#1149). Active sequence yields to the ordered-plan entry (#2402).\n\n1. ! Run `task triage:queue --limit=N` (D11 / #1128) -- default `N=10`. Groups `[RESUME]` -> `[URGENT]` -> untriaged -> other; ranking via `plan.policy.triageRankingLabels[]`, tiebreak `updated_at` desc.\n2. ! For per-item detail, run `task triage:show <N>` (default) or `task triage:show --format=operator <N>` (#2890) -- cached payload, latest decision, audit timeline, active-xBRIEF flag; operator format is the pasteable Phase 3 brief backbone. Exit 0 on hit, 1 on cache miss (re-sync per Phase 0).\n3. ~ Present the ranked **queue listing** verbatim; do NOT silently re-rank, drop, or annotate the listing beyond the canonical renderer. This queue non-annotation rule does **not** forbid Phase 3 per-candidate operator briefs or leans (see Phase 3 / #2890).\n4. ⊗ Recommend a specific issue without `task triage:queue` first, or an issue absent from the queue without `task triage:show` to surface why.\n\n## Phase 3 -- Decide\n\n! Walk per-item decisions through the canonical `task triage:*` verbs (tasks own audit-log append / schema / `xbrief/proposed/` write).\n\n! **Operator brief (same turn as menu) (#2890 / #3116):** Before every per-item decision menu, present an operator brief in the **same operator-visible message/surface** as the menu, containing at least: **URL-first** lead (canonical issue URL as the first line for that item, or `#N title` + URL); labels (or explicit none); **current-state validity** (`still-open` | `partial` | `likely-shipped` | `needs-re-scope`) + one-line evidence (linked closed PR, code path, or \"no evidence of fix\"); 2–5 line problem/context summary; AC bullets or explicit \"thin body / no AC\"; agent **lean** + one-line why (Accept / Defer / Reject / Needs-AC / …). ~ Prefer `task triage:show --format=operator <N>` as the brief backbone (URL-first + validity placeholder); agent still owns validity verdict and lean. ⊗ Menu-only or chip-only Phase 3 turns without that brief. ⊗ Brief-only turn followed by a later chip/menu-only turn that does not restate the brief. ⊗ Body-only summary without validity check against current master, closed children, or linked PRs.\n\n! **Host structured-question adapter:** On chips / `ask_user` / similar UIs (e.g. OpenClaw `ask_user`), keep the prose brief in chat; structured options are **actions only** (Accept / Defer / Reject / Needs-AC / Mark duplicate / Discuss / Back). Option labels ≉ substitute for the brief.\n\nFor each candidate, render the canonical numbered action menu and dispatch:\n\n```\nWhat would you like to do with this candidate?\n 1. Accept -- `task triage:accept -- --issue <N> --repo OWNER/NAME`\n 2. Reject -- `task triage:reject -- --issue <N> --repo OWNER/NAME`\n 3. Defer -- `task triage:defer -- --issue <N> --repo OWNER/NAME [--resume-on <event>]`\n 4. Needs-AC -- `task triage:needs-ac -- --issue <N> --repo OWNER/NAME`\n 5. Mark duplicate -- `task triage:mark-duplicate -- --issue <N> --of <of-issue> --repo OWNER/NAME`\n 6. Discuss\n 7. Back\n```\n\n- ! Map user replies only to the displayed number (`1`-`7`) or exact displayed option text. ⊗ Do NOT infer from alphabetic host affordances or bare letters such as `d` / `b` unless those letters were visibly rendered as choices.\n- ! On `Discuss`, halt immediately, prompt `What would you like to discuss?`, resume only on explicit user signal. ⊗ Implicit resumption.\n- ! On `Back`, un-buffer prior selection and re-render its action menu only before a `task triage:*` dispatch; after dispatch use `task triage:reset`.\n- ~ Bulk: `task triage:bulk-{accept,reject,defer,needs-ac}`; results still flow through the audit log.\n- ⊗ Write to `xbrief/proposed/` directly -- only `task triage:accept` is authorised.\n- ~ **Accept → pending chain (#1136):** `task triage:accept` ingests into **`proposed/`**. To stage into WIP (`pending/`) in one operator action: `task triage:accept -- --issue <N> --repo OWNER/NAME --auto-promote` (WIP cap still enforced; use `--force` on the accept command for WIP override). Separately, promote an already-accepted proposed scope by issue: `task scope:promote -- --from-issue=<N> [--repo OWNER/NAME]` (gates on latest `candidates.jsonl` decision = `accept`; non-accept refuses unless `--force-no-cache`; no decision soft-warns, `--strict` fails). Path-based `task scope:promote -- <file>` remains ungated for refinement scaffolds.\n\n## Phase 4 -- Audit\n\n! Confirm the session's decisions landed coherently before exiting the skill.\n\n1. ! Run `task triage:audit --format=json` (D11 / #1128); optional `#1180` filters `--since` / `--action`. Transform with `jq` -- framework does not compute trends.\n2. ! Run `task triage:summary` (D2 / #1122) -- `[triage] N untriaged · S stale-defer · M in-flight · WIP X/Y [⚠] [· [scope-drift] N]`.\n3. ~ Non-zero `[scope-drift]` → surface `task triage:scope-drift` + subscribe/unsubscribe/ignore remediation; then `task triage:bootstrap -- --resume`.\n4. ~ Stale accept (no active xBRIEF ref) → re-ingest or `task triage:reset`.\n5. ⊗ Skip Phase 4 audit.\n6. ! Umbrella/epic status: REST comments → `## Current shape (as of pass-N)` (#2066 / #1152); never body alone.\n\n## Reversibility\n\n! Undo via `task triage:reset <N>` (Layer 5; history never deleted). ⊗ Edit/delete `xbrief/.eval/candidates.jsonl` to \"undo\".\n\n## Quarterly closed-entry archive vs TTL prune (#1137)\n\nLive walkers (`triage:queue`, scope-drift, bootstrap) scan `.deft-cache/github-issue/`. Closed issues can linger forever. Operators may run an **explicit, reversible** archive pass — never auto on bootstrap/session/check.\n\n| Tool | What it does |\n| --- | --- |\n| `task triage:cache-archive` | Move **closed** + aged (default 30d) entries → `.deft-cache/archived/github-issue/...` with `archive-meta.json`. Skips open lifecycle scopes. `--dry-run` first. |\n| `task triage:archive-list` / `task triage:restore-from-archive` | List / move back to live. |\n| `task cache:prune` | **TTL hard-delete** by `expires_at` — **not** reversible; **not** closed-state archive. |\n\n! Prefer archive for closed clutter; use prune only for expired TTL / cap eviction. ⊗ Wire archive into session-start or `task check`.\n\n## Anti-Patterns\n\n- ⊗ Recommend work without `task triage:queue` (#1149).\n- ⊗ Conclude \"nothing to do\" from folder scans or live GitHub alone (#2576).\n- ⊗ Stale-cache walk; reimplement audit/`proposed/` writes; treat defer/needs-ac as terminal; edit candidates.jsonl; menu-only Phase 3 without operator brief (#2890); body-only brief without URL-first or current-state validity (#3116).\n\n## EXIT\n\n! On opt-out: `deft-directive-triage complete -- exiting skill.` Chain: `deft-directive-refinement` (accepted items) · `deft-directive-swarm` (cohort) · `task cache:fetch-all` then re-enter. ⊗ Silent exit.\n\n## References\n\n- #1119 D6; #1128 D11 (`triage:queue` / `show` / `audit`); #2890 Phase 3 operator brief; #3116 validity + URL-first; #1122 / #1123 / #1127 / #1129 / #1131; #1136 (`scope:promote --from-issue` / `triage:accept --auto-promote`)\n- Siblings: `deft-directive-refinement`, `deft-directive-swarm`, `deft-directive-sync`\n",
315
312
  "frontmatter_extra": "triggers:\n - triage\n - triage hygiene\n - work the cache\n - what's next\n - whats next\n - what should I work on\n - queue\n - build a cohort\n - build cohort"
316
313
  },
317
314
  {
@@ -343,7 +340,7 @@
343
340
  "path": "skills/deft-directive-xbrief/SKILL.md",
344
341
  "version": "0.1",
345
342
  "body": "# Deft Directive xBRIEF — on-demand create/verify\n\nCreate and verify dense xBRIEF artifacts (json|md|both) at an explicit path. Pack templates load on use — not an always-on novel.\n\nLegend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.\n\n## When to Use\n\n- Need a dense SoT brief (scope, playbook, mission, project) without freestyling long prose\n- Operator or agent says `xbrief create`, `xbrief verify`, or `compress into xbrief`\n- ⊗ Scope lifecycle work (promote / activate / complete) — use scope:* / intake instead\n\n## How (CLI)\n\n```bash\ndeft xbrief:create -- --format <json|md|both> --out <path> [--style scope|playbook|mission|project] [--title T] [--id ID] [--force]\ndeft xbrief:verify -- --format <json|md|both> --out <path> [--style scope|playbook|mission|project]\n```\n\n- ! `--format` and `--out` are **required**\n- ! `both` writes a stem pair: `*.xbrief.json` + `*.xbrief.md`\n- ! Paths expand portably (`~`, `%USERPROFILE%`); writes stay under project root (fail closed)\n- ! create/verify **do not** move lifecycle folders\n\n## Pack on use\n\n- ~ Full grammar + templates: `task packs:slice skills by-trigger --trigger xbrief` (or this skill path)\n- ~ Schema spine: `content/vbrief/schemas/xbrief-core-0.8.schema.json`\n- ⊗ Dump pack novels into always-on bootstrap or into SoT artifacts\n\n## Create vs lifecycle\n\n| Verb | Meaning |\n|------|---------|\n| `xbrief:create` / `xbrief:verify` | Write or check an artifact at `--out` |\n| `scope:*` / intake | Lifecycle birth and folder/status transitions |\n| `xbrief:preflight` | Implementation-intent gate (unchanged) |\n\n## Token budget\n\n- ! Keep this skill postcard-sized; load pack/CLI help only when creating or verifying\n- ⊗ Inline full schema manuals or multi-style novels into the always-on body\n\n## Anti-Patterns\n\n- ⊗ Overload `scope:promote` (or any lifecycle verb) to mean \"compress text\"\n- ⊗ Invent `xbrief:promote` for create\n- ⊗ Escape project root with `--out`\n- ⊗ Auto-write to personal memory stores from this skill\n\n## Exit\n\ndeft-directive-xbrief complete — create/verify done; chain to scope:* only when lifecycle is intended.",
346
- "frontmatter_extra": "triggers:\n - xbrief create\n - xbrief verify\n - create xbrief\n - verify xbrief\n - compress into xbrief\n - xbrief:create\n - xbrief:verify\n"
343
+ "frontmatter_extra": "triggers:\n - xbrief create\n - xbrief verify\n - create xbrief\n - verify xbrief\n - compress into xbrief\n - xbrief:create\n - xbrief:verify"
347
344
  }
348
345
  ]
349
346
  }