Deft directive build

From deftai/directive · View interactive version

Deft directive build is an AI agent skill from the GitHub repository deftai/directive. Build a project from scope xBRIEFs following Deft Directive framework standards. Use after deft-directive-setup has generated the project definition, or when the user has story xBRIEFs in xbrief/active/ ready to implement. Handles scaffolding, implementation, testing, and quality checks phase by pha

How to use this skill

Skill file

<!-- AUTO-GENERATED by task packs:render -- DO NOT EDIT MANUALLY -->

<!-- Purpose: rendered skill -->

<!-- Source of truth: packs/skills/skills-pack-0.1.json -->

<!-- Regenerate with: task packs:render -->

<!-- Edit the source, not this file. Slice instead of loading every SKILL.md: task packs:slice skills by-trigger --trigger <kw> (or list) -->

Deft Directive Build

Implements a project from its scope xBRIEFs following Deft Directive standards.

Legend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.

When to Use

Ordered-plan / cohort exhaustion (#2402)

Multi-scope turn/cache budget (epic #3009)

Multi-scope greenfield (app-bank pins, N story scopes) multiplies agent turns when ceremony, promote, check, and render are re-run per scope. Apply the following after offline seed.

Offline seed vs implement phase (#3010)

! Distinguish offline seed (operator or harness already ran directive init / deposit, pin-copied scopes into xbrief/proposed/, and recorded session ritual) from the agent implement phase.

! When seed + session ritual are already complete for the engagement:

Batch promote; one active implement (#3011)

! For a multi-scope pin, batch-stage scopes with task scope:promote -- --batch (all proposed/) or task scope:promote -- --batch <path>….

! Implement path remains one scope:activate + implement at a time — no multi-active write fence.

! When pin order is known, do not re-list the entire lifecycle tree every scope; walk the known ordered list.

⊗ Activate all scopes at once or drop the one-active-scope / story-ready stack.

Quality check once at end of multi-scope batch (#3012)

! On an approved multi-scope batch (operator-approved multi-story branch, swarm cohort, or pin walk): run the merge chokepoint once at the end of the batch (or after the last scope), not after every scope — prefer deft check; if the CLI is missing, use the tree-correct task form (task deft:check on include-only consumers; task check in framework source). Do not run both.

! Exception: if the last full check failed, fix loops MAY re-run check until green.

! Pre-PR / merge-ready gates remain end-of-unit — this does not weaken them.

! Iteration lane (affected tests / verify:forward-coverage / coverage:hotspots) still applies per scope during implementation (#1704).

⊗ Spam full directive check / task check after every scope when the batch is still mid-flight and the last merge-chokepoint check was green.

One-shot project:render (#3013)

! Greenfield init seeds a minimal render-ready PROJECT-DEFINITION. Treat task project:render as a refresh of items from lifecycle folders, not multi-turn identity research.

⊗ Invent project identity across many turns when seed already stamped the skeleton.

! When processing an approved multi-story cohort or an active ordered-plan sequence, stop after the final approved entry. Do not promote or dispatch adjacent stories from queue intuition. Continuation language advances only within the approved order; skill-chaining is non-authorizing.

Step 0 -- Implementation Preflight (#810)

The gate exits 0 only when the candidate xBRIEF lives in xbrief/active/ AND plan.status == "running". Any other state (pending/, proposed/, completed/, active/-with-non-running-status, malformed JSON, missing keys) exits 1 with an actionable redirect to task xbrief:activate <path>.

Platform Detection

! Before resolving any config paths, detect the host OS from your environment context:

| Platform | USER.md default path |

|--------------------|-------------------------------------------------------------------|

| Windows | %APPDATA%\deft\USER.md (e.g. C:\Users\{user}\AppData\Roaming\deft\USER.md) |

| Unix (macOS/Linux) | ~/.config/deft/USER.md |

Pre-Cutover Detection Guard

! Before proceeding with any build step, detect whether the project uses the pre-v0.20 document model or was generated by a strategy that emitted non-conformant v0.20 output shape (the root cause of most "build fails immediately after spec" complaints in #1166). Redirect or block with the precise remediation.

Detection Criteria

A project is pre-cutover if ANY of the following are true. This prose mirrors the executable helper in task migrate:preflight; when in doubt, the helper is canonical.

  1. SPECIFICATION.md exists and is neither a deprecation redirect nor a current generated spec export. A current generated spec export contains <!-- Purpose: rendered specification -->, all five lifecycle folders exist, and its <!-- Source of truth: ... --> marker names an authority artifact that exists: either xbrief/specification.xbrief.json for full-spec compatibility or xbrief/PROJECT-DEFINITION.xbrief.json for greenfield authority (legacy vbrief/... aliases remain read-compatible).
  2. PROJECT.md exists and contains neither the legacy <!-- deft:deprecated-redirect --> sentinel NOR the current Purpose: deprecation redirect canonical-banner marker (real content, not a deprecation redirect)
  3. xbrief/specification.xbrief.json exists but the lifecycle folders (xbrief/proposed/, xbrief/pending/, xbrief/active/, xbrief/completed/, xbrief/cancelled/) do NOT exist
  4. Strategy output shape violations (run task verify-strategy-output -- the canonical gate for source and consumer installs):

Action on Detection

! If pre-cutover or strategy-nonconformant state is detected, stop immediately and display an actionable message that cites the exact validator:

"This project was generated with pre-v0.20 or non-conformant strategy output. Run the deterministic validator and follow its remediation: task verify-strategy-output (works in source and after deft package install). For document-model migration, follow UPGRADING.md § Frozen pre-v0.20 document-model migration (#2068): pin v0.59.0, then run task migrate:vbrief from that payload. Otherwise task project:render / strategy re-run as indicated."

! Include specific details about what was detected (the validator output is authoritative):

! After the validator reports clean, re-run this guard before continuing.

⊗ Proceed with build when pre-cutover or strategy-nonconformant artifacts are detected -- always redirect to the frozen migration path first (or run the validator) and surface the exact remediation.

⊗ Silently ignore these artifacts or guess at fixes -- the validator (wired into task check and this guard) is the deterministic gate.

USER.md Gate

! Before proceeding, verify USER.md exists at the platform-appropriate path

(resolved via Platform Detection above, or $DEFT_USER_PATH if set).

Phase 1 before continuing -- do not proceed without user preferences

Forge-outage drop-back (#3422)

! On attributed platform outage or repeated REST 429/502/503 during YOLO / through-merge implement: drop GitHub I/O, report once to the human in chat, and re-probe on plan.policy.forgeOutageRetryMinutes (default 30; USER.md Personal wins; min 5; task policy:show --field=forgeOutageRetryMinutes). Local edit/test/commit MAY continue. Depth: CODE2 § #3180 / #3422. Complements #3167 / #3180.

⊗ Tight retry, empty-commit thrash, or sending the human to github.com as the only remediation.

Cost Phase Gate (#739)

! Before proceeding to File Reading, verify the project has gone through the

pre-build cost & budget transparency phase from skills/deft-directive-cost/SKILL.md.

This closes the adoption-blocker surfaced by issue #739 (refs #151 umbrella) where

users finished the spec flow and stopped at build because deft offered no cost

signal.

Detection

block populated with one of: build, rescope, no-build, skip).

populated (one or two sentences in plain language). A skip with no reason

recorded is treated the same as no decision.

Action

unpopulated OR a skip/rescope/no-build decision has no reason recorded:

stop immediately and redirect the user:

> "This project has not gone through the pre-build cost & budget transparency

> phase. Run skills/deft-directive-cost/SKILL.md to produce a plain-English

> COST-ESTIMATE.md, then re-run the build skill once the user has chosen

> build / rescope / no-build / skip(+reason)."

(chain to skills/deft-directive-refinement/SKILL.md to pull spec scope

back, or the interview), then re-run skills/deft-directive-cost/SKILL.md

before re-attempting build.

The user has explicitly stopped the project at the cost phase.

missing, when the decision is unpopulated, or when a skip / rescope / no-build

decision has no reason recorded.

build skill MUST honor the recorded decision.

File Reading

1. ./xbrief/active/ -- scope xBRIEFs for work items to build (required)

2. ./xbrief/PROJECT-DEFINITION.xbrief.json -- project identity, tech stack, architecture

3. ./.planning/codebase/MAP.md -- generated codebase orientation projection, if present (advisory)

4. USER.md at the platform-appropriate path (see Platform Detection) -- Personal section is highest precedence; Defaults are fallback

5. deft/main.md -- framework guidelines

6. deft/coding/coding.md -- coding standards

7. deft/coding/testing.md -- testing requirements

8. deft/coding/toolchain.md -- toolchain validation rules

9. deft/languages/{language}.md -- only for languages this project uses

Rule Precedence

USER.md Personal                  <- HIGHEST (name, custom rules -- always wins)
PROJECT-DEFINITION.xbrief.json   <- Project-specific (tech stack, architecture, config)
USER.md Defaults                  <- Fallback defaults (used when PROJECT-DEFINITION doesn't specify)
{language}.md                     <- Language standards
coding.md                         <- General coding
main.md                           <- Framework defaults
Scope xBRIEFs                     <- LOWEST

Change Lifecycle Gate

! Before any implementation that touches 3+ files, verify that a /deft:change <name> proposal exists and has been confirmed by the user:

Build Process

All xBRIEFs (including those read from xbrief/active/ and any new xBRIEFs this skill emits) MUST use "xBRIEFInfo": { "version": "0.8" }. Legacy 0.6 is read-accepted until deft migrate:xbrief. The validator accepts both; new writes are 0.8 only (see CODE3).

Step 1: Understand the Scope

"Here's what I see: {N} story xBRIEFs in active/. I'll start with {name}. Ready?"

Step 2: Verify Toolchain

Gate throughput — iteration fast lane vs merge chokepoint (#1704)

Invariant: every change MUST pass the full gate at least once before merge. Iteration MAY use a cheaper proxy; the merge chokepoint MUST NOT be skipped.

Cost model (swarm-heavy path): moves from roughly O(commits × full-gate) toward O(merges × full-gate) + O(iterations × cheap-proxy) when workers iterate with affected/static gates and run full task check only at PR/merge.

Dual stop — multi-iteration implement and pre-PR loops (#2442)

Multi-iteration implement-fix and pre-PR polish loops MUST carry both a success stop and a failure/budget stop (main.md ## Dual Stop Rule (#2442)). Single-turn edits and one-shot probes are exempt.

Defaults for this skill (override only with an explicit operator envelope or xBRIEF field):

| Loop class | Success stop | Default failure stop |

|------------|--------------|----------------------|

| Implement / quality fix (tests, lint, typecheck, coverage, AC) | Affected/static gates green for the change; AC met | max 5 fix iterations or 3 consecutive identical outcomes (same failing command + same primary error class) with no material code/config change |

| Pre-PR polish (deft-directive-pre-pr Read-Write-Lint-Diff) | Full pass with zero further edits | max 3 polish passes or 2 consecutive no-diff / same-diff outcomes |

| Full deft check re-run | tree-correct full gate green after a red merge chokepoint or a new commit | Counts toward the implement/quality fix envelope above (do not open a separate unbounded check-retry loop) |

On failure stop:

PlanItem stopConditions — mid-execution precondition STOP (#1613)

When the active plan item declares stopConditions, treat them as checkable mid-execution precondition STOP anchors (not done criteria — those stay in narrative.Acceptance).

Depth: vbrief/vbrief.md § STOP conditions (anchors); schema $defs.StopConditionAnchor.

Budget-aware effort - bank the pass before deepening (#3266)

When a hard turn or cost budget is detectable (session:start effort_budget / env DEFT_MAX_TURNS / DEFT_MAX_BUDGET / host descriptor #1461), size effort to the stated acceptance bar first. This is the success-side analog of dual-stop (#2442): dual-stop stops thrash on failure; bank-the-pass stops budget exhaustion on over-deepening.

Core helper: packages/core/src/session/effort-budget.ts (detectHardEffortBudget, recommendVerificationDepth). Composes #2442, #1581, #3214, #1006.

Enforcement note: skill defaults are behavioral. Durable delivery/acceptance circuit-breaker: #3143 packages/core/src/delivery-attempt/ (evaluatePreDispatch, .deft/delivery-attempts/). Docs: docs/delivery-attempt.md. Route delivery/acceptance automatic retries through that gate; do not invent a parallel ledger in this skill.

AC-pass banking checkpoint - finalize on green (#3285)

Sharpens #3266: the first moment stated/official acceptance criteria pass is a banking checkpoint, not a license to keep spending the turn budget on self-imposed depth.

Core helpers: packages/core/src/session/ac-pass-banking.ts (evaluateAcPassBanking, bankAcPass, decidePostBankFinding, simulateSurplusInsufficientRun); policy: packages/core/src/policy/ac-pass-banking.ts (plan.policy.acPassBanking). Composes #3266, #3284, #3282 (optional bank-event JSONL), #1006.

Step 3: Build Phase by Phase

For each phase:

  1. ! Scaffold — file structure, dependencies, config
  2. ! Test first — write tests before implementation (TDD)
  3. ! Implement — make tests pass, following deft coding standards
  4. ! Verify (iteration lane) — run affected/static gates per #1704 fast lane above; fix failures before checkpoint commits
  5. ! Origin sync — when this phase materially changed an origin-linked scope xBRIEF (plan.references includes x-xbrief/github-issue), run task issue:sync-from-xbrief -- <path> (or --dry-run to preview) so the linked GitHub issue receives a sync comment; if skipped, document why in the PR or session notes (#2540)
  6. ! Checkpoint — tell user what's done, what's next

Step 4: Quality Gates

After EVERY phase (iteration lane — #1704):

vitest run --coverage <changed-paths>   # or project test runner on touched modules
task coverage:hotspots                  # branch headroom before merge
task verify:forward-coverage            # new-source coverage (#1310)

Before PR / phase handoff (merge chokepoint):

deft check          # preferred full gate (getting-started / #2893)
# else tree-correct: task deft:check on include-only consumers; task check in framework source
task test:coverage  # >=85% or PROJECT-DEFINITION.xbrief.json override

Product-first done-gate (#3284) / literal AC (#3267)

At intake, capture the task statement's exact acceptance commands as executable AC (plan.acceptance.commands + #3267 literal_acceptance_commands). Empty is allowed only with none_stated: true (ladder: stated → derived → project_floor). Before declaring done, run them verbatim — same paths, same flags, same working directory. Self-chosen verification is supplementary, never a substitute. Extends #973. task check runs verify:ac first (fail-fast); hygiene is second and may become advisory under pressure. Rapid ceremony = AC-only.

task verify:ac -- <active-story-path>

Exit 0 = pass or none stated with valid marker; exit 1 = a stated command failed; exit 2 = config. (verify:literal-ac is the #3267 mechanism alias.)

Product-oracle gate integrity (#3322 / #3156)

A red product verification may be resolved only by a product change or an independently re-derived oracle (both sides rebuilt from scratch, different method). In-place repair of the failing comparison then pass is not a pass — it is an unresolved discrepancy.

Operator-log hygiene (lazy-load, #1940)

When the story touches operator-facing services (dashboards, multi-process

workers, WARN/ERROR operators triage):

checklist in docs/operator-log-hygiene-checklist.md to story AC or probe

locked decisions before claiming logging done

(#481) — those are different lanes

consumer-owned shape; optional pack stub under

docs/operator-log-hygiene-consumer-pack-stub.md

Discovery keywords: operator log, operator-facing logs, observability checklist

— also indexed in REFERENCES.md.

Goal-gate determinism (lazy-load, #852)

When authoring or tightening story acceptance criteria, quality gates, or skill

steps during build:

scope, stop, and preserve are rigid; pure execution path is flexible guidance

gates own "done" (see also verification/verification.md and Fail Loud #1006)

Discovery keywords: goal-gate-determinism, rigid goals flexible path — also

indexed in REFERENCES.md.

Coding Standards (Summary)

Read full files when you need detail:

See deft/coding/coding.md and deft/coding/testing.md for full rules.

Pre-Commit File Review

! Before every commit, re-read ALL modified files and explicitly check for:

  1. ! Encoding errors -- em-dashes corrupted to replacement characters, BOM artifacts, mojibake from round-trip read/write
  2. ! Unintended duplication -- accidental double entries in CHANGELOG.md, scope xBRIEF files, or structured data files
  3. ! Structural issues -- malformed CHANGELOG entries, broken table rows, mismatched index entries, invalid JSON/YAML
  4. ! Semantic accuracy -- verify that counts, claims, and summaries in CHANGELOG entries and ROADMAP changelog lines match the actual data in the commit (e.g. "triaged 4 issues" must match the number actually triaged, issue numbers cited must match the issues actually added)
  5. ! Semantic contradictions -- when adding a ! or ⊗ rule that prohibits a specific command, pattern, or behavior, search the same file for any ~, ≉, or prose that recommends or permits the same command/pattern -- resolve all contradictions in the same commit before pushing
  6. ! Strength duplicates -- when strengthening a rule (e.g. upgrading ~ to !), grep for the term in the full file and verify no weaker-strength duplicate remains
  7. ! Forward test coverage -- for each new source file in this PR (scripts/, src/, cmd/, *.py, *.go), verify a corresponding test file exists in the same PR; running existing tests is not sufficient for new code

⊗ Commit without re-reading all modified files first.

Commit Strategy

feat(phase-1): scaffold project structure
feat(phase-1): implement core data models with tests
feat(phase-2): add REST API endpoints with integration tests

Error Recovery

Declare the contract (#3383)

! Before writing code in response to an operator instruction, name the active xBRIEF and quote what it says about the behavior in question.

! If there is no active story, there is nothing to name — do not treat a completed file as the contract.

⊗ Implement from a completed xBRIEF as if it were the current next-build contract.

Probe-then-fill remote claims (#3120)

! 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:

  1. 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).
  2. Copy IDs / URLs / SHAs / scores only from that probe JSON/text into the evidence block.
  3. Set proof_status: bound and attach short raw probe snippets (command + snippet) for each remote claim.

! 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.

! 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.

! 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.

! Machine check: validateHandoffEvidence in packages/core/src/handoff-evidence/ (see templates/agent-prompt-preamble.md §11).

⊗ Fill PR / SHA / CI / review fields from recollection, narration, or prior-turn memory.

⊗ Claim status: pass with remote fields when proof_status is not bound or probes are missing (#3120).

Completion

"The project is built and all quality checks pass. Describe any new features you'd like to add — I'll follow the deft standards we've set up."

Significant decision log (#1396)

! When this scope makes a significant choice (architecture, product behavior, security, public/private boundary, data model, runtime topology, hard-to-reverse process), record it with task decision:write (or --body-file for multi-line fields) so later agents load rationale without inventing it.

~ Prefer attaching with --scope <active-xbrief> when the decision is bound to this story; use standalone xbrief/decisions/ for cross-cutting / multi-scope process choices.

~ Before claiming a process/architecture path was 'already decided', run task decision:list -- --query <topic> (or --issue N).

⊗ Require a decision record for every trivial scope or routine fix.

⊗ Merge lessons (#1513) into decision records, or replace ADRs under docs/decisions/ADR-*.md.

Docs: docs/decision-log.md · xbrief/decisions/README.md.

Intent-constraint fail path (#4587 / #5574 Prefer-A / #7031)

! When task check / verify:intent-constraint fails on a new throw/reject/abort or numeric-const without a merge-base record, classify the condition: expected operational deny → returned-failure / filter without throw-reject-abort-numeric-const (free); invariant / corruption / impossible-if-healthy → fail-fast + a declared record (rewrite solely to clear the gate is forbidden). Any remaining new hard fact among the four FACT_KINDS (including numeric-const on an otherwise operational path) still needs that record.

! Write the declaration: put the values on plan["x-directive/intentConstraint"], run scope:record-intent-constraint from any shell (no terminal step; it writes kind: "declared"), and land the record on the merge base before the product PR — a record PR, or the activation PR that adds the brief — then rebase. A declaration is not consent: under human merge the person who merges the record PR reviews it; under bot merge nothing human does. Attended: tell the human in the parent chat what the record declares. Do not soften an invariant throw solely to clear the gate.

⊗ Ride the record in the product PR (same-PR records are not authoritative).

⊗ Recut evaluateIntentConstraint or let an approved-scope digest authorize throw sites.

⊗ Treat a declared record as human approval.

Anti-Patterns

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.