<SddTaskScaffolding keywords="task-scaffolding, dependency-graph, bdd, execution-planning, mandatory-rules-linkage, rules-cascade, rule-activation, hierarchical-tasks, modes, extend-dag, scope-graph, sdd-phase-3" type="directive" ver="3.0">
  <Directive_Context>
    <Mission>
      Decompose the spec tree into a DAG of compact task tickets ready for autonomous execution by `sdd-execute` orchestrator (which dispatches phase-subagents under `phase-execution-protocol`).

      Convergence point. Entry point: `specs/README.md` Scope Graph — canonical map of all scopes and their dependencies. From Portal extract:
      - All scopes with their scope-type and `depends-on` edges (Mermaid graph + Scopes table).
      - Per scope: read `specs/<scope>/<scope>.spec.md` for rules, requirements, architecture.
      - Per product/library scope: read `specs/<scope>/<module>/<module>.spec.md` if 8 Module Map exists.

      Outputs:
      - `tasks/README.md` — project-level tracker (Entry Points, Tracker Index, High-Level cross-scope DAG, Decision Log). No global Cascade Table here — each scope has its own.
      - `tasks/<scope>/README.md` — per-scope tracker: Cascade Table (derived from scope graph), intra-scope DAG, Tracker.
      - `tasks/<scope>/<scope>.task-NN.md` — compact tickets for scope-level tasks.
      - `tasks/<scope>/<module>/<module>.task-NN.md` — module-level tickets (when modules exist in scope).
      - `tasks/integration/` — cross-scope integration tickets (optional; only when a dedicated `integration` scope is registered in Scope Graph).

      Next phase: `sdd-execute` consumes one ticket at a time, dispatches phase-subagents per ticket's Phases Overview, then `audit`.

      **Glossary.** Orchestrator = agent under `sdd-execute` SKILL. Phase agent = subagent under `phase-execution-protocol`. Auditor = agent under `audit`. Scope = architecturally cohesive unit from scope graph. scope-type ∈ {infrastructure, contracts, library, product}.
    </Mission>
  </Directive_Context>

  <Belief_State>
    <Axiom id="AX_DIRECTIVE_MODE">
      **Two modes, auto-detected from intake:**
      - `initial` — first run, `tasks/` absent or empty.
      - `extend-dag` — add tickets for new/refined scope or module or pivot list, without regenerating existing.
    </Axiom>

    <Axiom id="AX_MODE_AUTO_DETECT_OR_HALT">
      | Condition | Mode |
      |---|---|
      | No `tasks/` OR empty | `initial` |
      | `tasks/` present + intake names new/refined scope or module OR Pivot Invalidation List | `extend-dag` |
      | `tasks/` present + intake unclear | HALT, ask operator |
    </Axiom>

    <Axiom id="AX_SPEC_IS_SOLE_SOURCE">
      **Phase reads specs only, never code.** Allowed inputs: operator intake; `specs/README.md`; per-scope spec files; per-module spec files; in `extend-dag` — existing `tasks/` artifacts (for max Task-ID + current DAG); rule files at `ai/directives/<category>/<rule>.xml`. No project-wide search (grep / find / ripgrep) outside the listed reads. Spec/code mismatch is resolved by `audit`.
    </Axiom>

    <Axiom id="AX_SCOPE_GRAPH_DETECTION">
      Detection is driven by `specs/README.md` Scope Graph (Mermaid `graph TD`) and Scopes table. Portal absent → no specs → HALT.

      From Portal extract:
      - All scope names and their scope-types (from Scopes table).
      - Dependency edges A→B (from Mermaid graph or Scopes table `depends-on`).
      - For each scope with ✅ status, read its spec file at `specs/<scope>/<scope>.spec.md`.

      Cascade computation requires full scope graph traversal:
      - **Traversed-scopes** for a target scope = all scopes reachable via `depends-on` edges (transitive closure).
      - **Cascade** = union of Effective Rules from traversed-scopes + target-scope rules + (module rules if product/library) + task additions.

      | Scopes present | Result |
      |---|---|
      | Only infrastructure scopes | scaffold infra tasks only; no module trackers |
      | Mix of product/library + infra/contracts | full project; infra tasks = DAG roots |
      | No scopes at all | HALT: no spec input |
    </Axiom>

    <Axiom id="AX_EXTEND_DAG_PRESERVES_EXISTING_IDS">
      **In `extend-dag`, existing Task-IDs and ticket files are immutable.**

      - New tasks get next sequential `TSK-NN` after max existing.
      - Existing tickets are NOT regenerated even if upstream specs changed — that is the orchestrator's reopen scenario via `sdd-execute`, not regeneration.
      - `add-scope` upstream → scaffold only for the new scope.
      - `add-module` or `refine-module` upstream → scaffold only for the new/changed surface; unchanged-surface tickets untouched.
      - Per-scope Cascade Table may update; existing tickets keep their old per-phase `Rules:` lists — orchestrator re-derives on reopen if the operator opts in.
      - DAG edges/IDs preserved; new tasks appended.
    </Axiom>

    <Axiom id="AX_RULES_RESOLUTION_HARD_FAIL">
      **All rule references must resolve; missing rule = abort.** Sources: scope spec (5 Effective Rules for infra; 4.5 Rules for product/library), module spec (9 Handoff Module Rules Additions), task (operator-supplied at STEP_4). Each ref must exist as `ai/directives/<category>/<rule>.xml`. On miss: abort with explicit list. A placeholder rule reference (TBD, `<rule>`, "to be authored", any unresolved name) = abort, never write a ticket against it.
    </Axiom>

    <Axiom id="AX_RULES_CASCADE_RESOLUTION">
      **Effective rule-set per task = union of 5 tiers; later tier overrides earlier on collision.**

      Tier order (low → high):
      1. **traversed-scopes** — union of Effective Rules from all scopes reachable via `depends-on` from target scope (transitive closure).
      2. **target-scope** — scope spec 5 Effective Rules (infra) or 4.5 Rules (product/library).
      3. **module:<name>** — module spec 9 Handoff Module Rules Additions (when modules exist).
      4. **task** — operator-supplied during ticket generation.

      Materialization:
      - **Cascade Table** (Scope × Categories) lives in `tasks/<scope>/README.md` per scope, NOT in `tasks/README.md`. Generated from scope graph automatically.
      - **Per-phase `Rules:` bullet list** inside each ticket's section 3 Phases block: derived by scaffolder per `AX_RULE_ACTIVATION_PLAN` from cascade × THAT PHASE's Target Files + kind. Rules are NOT declared at ticket level — only per phase.
      - Auditor recomputes effective set per-phase from sources and compares with each phase block.
    </Axiom>

    <Axiom id="AX_RULE_ACTIVATION_PLAN">
      Rules are resolved per phase, not per ticket. For each phase declared in the ticket's section 2 Phases Overview:

      1. Read `ai/directives/knowledge.xml` — the canonical rule registry (`<Rules>` section).
      2. From the scope's Project-Wide Rules, extract the candidate rule set for this scope.
      3. For each candidate rule: evaluate its `<Triggers>` and `<SkipWhen>` against THIS PHASE's `Target Files` and phase `kind`. Include the rule only when `<Triggers>` match AND `<SkipWhen>` does not apply. Signal-based only — no hardcoded language/tool knowledge in this directive.
      4. **Transitive closure via `<Depends_On>`.** For each included rule, open its file and read its `<Depends_On>` section (optional; lists rule-file paths this rule architecturally extends). Add every dependency to the phase's Rules set. Recurse until the set stops growing. Cycles → halt `H_RULES_CYCLE`. Missing dependency file → halt `H_MISSING_RULES`. This produces the explicit, fully-resolved set; phase-subagent does NOT walk `<Depends_On>` at runtime.
      5. For each rule in the resolved set:
         - `<File>` → full path to rule file (`ai/directives/<category>/<rule>.xml`); render as Markdown link in the phase's `Rules:` bullet list.
         - `<RequiresVerification>` → collect aliases for ticket-level Verification table (step 7).
      6. Write the phase's `Rules:` bullet list with one `[<rule-id>](<rule-file-path>)` per included rule (direct + transitive, all explicit).
      7. After all phases are processed, collect the union of all `<RequiresVerification>` aliases across all phases of this ticket. Group rules by alias (multiple rules may share `check-command`). Resolve each unique alias from infra-spec Verification Commands.
         - Alias present in spec → use its invocation.
         - Alias absent → halt: H_VERIFICATION_COMMAND_MISSING (alias, ticket ID).
      8. Write ticket section 5 Verification table (ticket-level, single table):
         | Command | Required by |
         One row per unique alias. "Required by" = comma-separated rule IDs that declared it. Phase-subagent runs only the rows whose Required-by intersects with its phase's `Rules`.
    </Axiom>

    <Axiom id="AX_DAG_AND_TICKET_BOUNDARIES">
      **Topological order, no cycles. Default: minimum tickets — one per coherent spec unit.** Product / library scope → one ticket per module-spec. Infrastructure / contracts scope → one ticket per discrete capability.

      DAG edges derive from real file-level dependencies, Bootstrap → consumers, and cross-scope `depends-on`. No «logical layer» phases — Ports → Adapters → Integrations is an analysis aid in discovery, NOT a ticket-multiplication rule. A Port and its single confirmed-v1 Adapter co-edit and live in one ticket.

      **Split one ticket into N only when BOTH conditions hold:**
      - **(P) Parallel sub-process potential** — N phase-subagents dispatched simultaneously; Target Files disjoint across all phases of each ticket; no Deps edge among the N.
      - **(C) Context budget overflow** — combined cascade Rules + Spec References + Target Files exceed comfortable single-context for one phase-subagent's phase.

      **NOT a reason to split:** audit milestone granularity (audit runs once per ticket regardless of size); logical layering (Port + Adapter ship together); partial shippability (consumer can't pick a half-module); human time-units (hours / days — irrelevant for AI execution bounded by context window).

      Sequential split (A → B with hard Deps) without (C) = pure overhead: B's phase-subagent re-reads what A's already loaded; zero wall-clock gain.

      Cross-scope: scope B DONE before A's tasks consuming B's outputs. Bootstrap tickets DONE before non-bootstrap of the same scope.
    </Axiom>

    <Axiom id="AX_BOOTSTRAP_TICKET_DERIVATION">
      **Bootstrap Requirements rows with Owner=`this-scope-task` aggregate into the minimum number of tickets per `AX_DAG_AND_TICKET_BOUNDARIES`.** Default — group by Resolution affinity (all `package` rows → one «install deps» ticket; all `structural` rows editing the same config file → one ticket); subdivide only when (P) parallel-executable or (C) context overflow. Source: scope spec Bootstrap Requirements (infrastructure 9, contracts 7, library 8, product 8).
      - Rows with Owner=`external-prereq-scope` → cross-scope dependency edge, not a ticket here.
      - Rows with Owner=`operator-action` → noted in tracker index as a blocking external prerequisite, not a ticket.
      - Bootstrap tickets must be DONE before any non-bootstrap ticket of the same scope (e.g. `install package` precedes `wire config that uses package`).
      - Bootstrap tickets carry Verification populated from the Resolution column (e.g. `npm ls <pkg>` exit 0).
      - If Bootstrap Requirements is absent from the spec → abort with `H_BOOTSTRAP_REQUIREMENTS_MISSING` (the spec did not pass discovery STEP_7).
    </Axiom>

    <Axiom id="AX_TICKET_HAS_BDD_AND_TESTS">
      **Ticket carries BDD scenarios mapped to concrete tests.**

      - Acceptance Criteria = strict BDD (Given/When/Then) translated from DbC pre/post + Requirements & Constraints + Decision Log. Negative scenarios, fallbacks, trust boundaries, platform limits pulled from spec, not inferred from component name.
      - Each scenario gets a verification level marker: `contract` | `unit` | `integration` | `e2e`.
      - Each scenario maps to `<test-file>::<canonical case name>` in section 6 Test Scenario Coverage, OR explicit `Deferred Test Ownership: <task-id>`.
      - At least one phase of kind `test` MUST exist whose Target Files contains the test file, unless every scenario has `Deferred Test Ownership`.
      - Canonical case names are normative: phase-subagent uses verbatim or updates the ticket before phase DONE.
      - BDD describes behavior, not language-specific syntax.
      - For every DbC contract in Spec References (Port / Adapter / Value Object / branded type / discriminated union): one `contract`-level typing scenario MUST exist — covers input/output shape, branded-type rejection at boundary, union exhaustiveness. `Deferred Test Ownership` not allowed for typing scenarios — they ship with the types.
    </Axiom>

    <Axiom id="AX_DONE_REQUIRES_EVIDENCE">
      A Round cannot close (`[x] DONE` on the ticket) until ALL of:
      - verification commands executed; result + exit code recorded in Execution Log;
      - every BDD scenario has `<file>::<case>` confirmed OR deferred owner recorded;
      - every entity introduced beyond module Entity Inventory logged as `Introduced <Name> because <reason>`;
      - `Runtime Backing` honestly recorded; `real-runtime` claim without real implementation requires explicit `Deferred Runtime Scope`.
    </Axiom>

    <Axiom id="AX_TICKET_DEDUPLICATION">
      **Project-wide content lives ONCE in `tasks/README.md`.** Declared there: file-header convention, baseline Completion Rule, Execution Log template, post-task audit hint. Per-scope Cascade Table lives in `tasks/<scope>/README.md`. Per ticket: only task-specific Meta, BDD, Test Scenario Coverage, Completion additions (if any), Execution Log instance (initially empty plan).
    </Axiom>

    <Axiom id="AX_TASK_ID_UNIQUENESS">
      **`TSK-NN` is project-wide unique, sequential, immutable.**

      - Before generating a ticket, scan `tasks/**/*.task-*.md` for collisions.
      - ID never changes — even if ticket file moves between scopes.
      - Code references via file headers point to IDs, not paths.
      - Auditor cross-checks via `AX_TASK_ID_INTEGRITY`.
      - Collision = abort; operator resolves.
    </Axiom>

    <Axiom id="AX_REOPEN_TICKET_FORMAT">
      **Reopens accumulate as appended Rounds in one ticket; never spawn parallel tickets for same scope.**

      - Meta `Reopens: <count> (<YYYY-MM-DD> — <last reason>)` on a single line; field omitted when 0.
      - Status returns to `[~] IN_PROGRESS`; no separate `REOPENED`.
      - Execution Log structured by `### Round N — <date>, <reason>`, append-only. Old Rounds NEVER edited.
      - Re-runs are governed by `sdd-execute` orchestrator: audit FAIL triggers a `fix`-kind re-run of ONLY the phases whose Target Files contain finding locations. Phases not flagged are NOT re-run.
    </Axiom>

    <Axiom id="AX_EXECUTION_LOG_PLAN_VS_FACT">
      **Scaffolding writes a MINIMAL skeleton; phase-subagent appends event lines as work happens.**

      - **SKELETON** for Round 1 = under `### Round 1 — <date>, initial`, one `#### P<N>` block per phase declared in section 2 Phases Overview. Each block contains ONLY the closing lines:
        ```
        #### P<N>
        - [ ] `<ts>` ver <cmd from section 5> → <pass|fail> exit=<code>
        - [ ] `<ts>` DONE
        ```
        No pre-filled `file` / `test` / `cov` / `rules` / `recon` / `sync` lines — those were noise (duplicated Target Files / section 6 / Rules: list / git diff). Event lines (`intro` / `decision` / `tried` / `discovery` / `insight` / `verified` / `BLOCKED`) are APPENDED by the phase agent only when the event actually happens.
      - **FACT** = the closing `[x]` lines have placeholders replaced with real values; preceding event lines exist only if their event happened.
      - Each phase block ends with `**Handoff →** artifacts: [...]; decisions: [...]; open: [...]` line.
      - Round closes with `#### Round close` block (single `DONE`) emitted by orchestrator after the last phase.
      - **Forbidden**: `[x]` line containing any unreplaced `<…>` literal = fabricated done.
      - Append-only by Rounds.

      A trivial phase with no surprises has 2 lines (`ver`, `DONE`) + Handoff. A phase with real engineering content (decisions, discoveries, intros) has those lines too — but they earn their place by carrying information that isn't elsewhere.
    </Axiom>

    <Axiom id="AX_FILE_HEADER_TASK_TRACEABILITY">
      **Files carry a unified file-header contract; IDs only, never paths; append-only for `@tasks`.**

      Required file-level fields in execution profile:
      - `@file` — mandatory; what the file holds.
      - `@consumers` — mandatory; one or more consumers (see `AX_CONSUMERS_TAG_SEMANTICS`).
      - `@tasks` — mandatory; associated `TSK-NN` list.

      Canonical header shape:
      ```
      // @file: <what the file holds>
      // @consumers: <consumer-1, consumer-2, ...>
      // @tasks: TSK-04, TSK-12
      ```
    </Axiom>

    <Axiom id="AX_CONSUMERS_TAG_SEMANTICS">
      `@consumers:` names the entity (class, function, interface) that depends on this file's primary exports — not a file path, not a folder name. Name MUST match the consuming entity as named in the spec.
    </Axiom>

    <Axiom id="AX_CROSS_SCOPE_TASK_PLACEMENT">
      Cross-scope integration tasks belong to the scope that **initiates or owns** the integration. If both sides have equal weight, create a dedicated `integration` scope in the Scope Graph and register it in `specs/README.md`. Never scatter pieces of one integration across multiple scope folders. `tasks/_integration/` is deprecated — do not create it.
    </Axiom>

    <Axiom id="AX_AUDIT_HOOK">
      Round is complete only after `audit` returns PASS. `sdd-execute` orchestrator dispatches audit-subagent automatically after the last phase of a Round closes — operator does not invoke audit manually. `[x] DONE` on the ticket is mechanical close, not verification. Until audit PASS, dependents are blocked.
    </Axiom>

    <Axiom id="AX_PHASES_DECLARED_IN_HEADER">
      Every ticket declares its work as an ordered list of phases in `## 2. Phases Overview` (compact table) and `## 3. Phases` (block per phase). Phase kinds are a closed vocabulary: `bootstrap | impl | test | config | doc | refactor`. (`fix` is reserved for re-runs at execution time, not for scaffolding.)

      One phase = one focused unit of work for one subagent. Cross-phase dependencies (`Deps:`) are explicit. The orchestrator dispatches phases sequentially; the phase-subagent reads ONLY its phase's block, its phase's Rules, and prior-phase Handoff payloads.

      Phase emission rules during scaffolding:
      - Default mapping per Target Files content:
        - production source files (e.g. `*.ts`, `*.py` excluding tests) → `impl` phase.
        - test files (`*.test.*`, `*.spec.*`) → `test` phase, depends on the corresponding `impl`.
        - third-party tool config files (`eslint.config.*`, `vitest.config.*`, `lefthook.yml`, etc.) → `config` phase.
        - markdown docs → `doc` phase.
        - package install + foundational config (from Bootstrap Requirements) → `bootstrap` phase, no Deps.
        - trivial wiring files (module barrel `index.ts`, parent re-export update, single-line type-alias re-export) → NOT a separate ticket and NOT a separate phase. They are added to the `Target Files` of the `impl` phase that creates the symbols they re-export.
      - Each phase carries its own `Rules:` list — subset of cascade-derived rules whose `<Triggers>` apply to its file class.
      - Each phase carries its own `Target Files:` bullet list (NO ticket-level `Target Files` outside phases).
      - Each phase carries `Inputs:` (`none` or list of prior phase IDs whose Handoff it consumes) and `Exit:` (one-line verifiable criterion).

      Forbidden: emitting a ticket without `## 2. Phases Overview` and `## 3. Phases`; collapsing impl + test into one phase (they have different rule sets and different verification commands); emitting Target Files at ticket level instead of per-phase.
    </Axiom>

    <Axiom id="AX_SSOT_TRACEABILITY">
      **No contract duplication.** Tickets link to spec sections via Markdown anchors. Module spec for contracts/consumers/invariants; scope spec 4 only for cross-cutting constraints.
    </Axiom>

    <Axiom id="AX_DIALOGUE_DISCIPLINE">
      - **Phase agreement.** Agent never closes a phase autonomously. Signal `STATUS=READY_TO_ADVANCE`; operator confirms. Emit Phase Progress every round.
      - **Neutral + critical.** Operator asks to merge tasks, skip a test, accept low coverage → surface the risk, demand justification. No auto-agreement.
      - **Confidence explicit.** LOW / MEDIUM / HIGH stated. Under LOW: do not lock the DAG, do not close TASK_GENERATION.
      - **Context budget.** Long dialogues: top-3 questions; compact Phase Progress; do not repeat full DAG when 1–2 edges changed.
    </Axiom>

    <Axiom id="AX_DECISION_LOG_REQUIRED">
      Non-default scaffolding choices (operator merges 3 tasks into 1, refuses deferred coverage, overrides cascade activation) → `D-NNN` entry in `tasks/README.md` Decision Log with rationale.
    </Axiom>

    <Axiom id="AX_OPERATOR_LANGUAGE">
      **Directive prose (axioms, halt names, step procedures, contract identifiers, structural section headings) — English.**
      **Operator-facing artifact prose and operator-facing messages — Russian.** Russian applies to:
      - Ticket body text (Purpose, Description, BDD scenario content after `Given` / `When` / `Then`, Decision Log `Why` / `Risk`).
      - README content (Decision Log entries, Notes, descriptions).
      - Halt messages emitted to the operator.
      - Phase Progress free-text fields.

      English regardless of context: code paths, file names, axiom IDs (`AX_*`), Trace anchors, IDs (`TSK-NN` / `D-NNN` / `H_*`), severity / status tokens (`TODO` / `IN_PROGRESS` / `DONE` / `BLOCKED`), BDD keywords, verification-level tokens, runtime-backing tokens, structural section headings, field labels.
    </Axiom>

    <Axiom id="AX_STATELESS_ARTIFACT">
      All DAG decisions, links, BDD, completion rules baked into Markdown. Downstream sessions start with no scaffolding history.
    </Axiom>

    <Axiom id="AX_TICKET_SECTION_NAMES_NORMATIVE">
      Ticket sections are wrapped with `<!--SECTION:UPPER_SNAKE-->…<!--/SECTION:UPPER_SNAKE-->` markers (grammar: `extract-section.sh`). **Anchor names in `TASK_TICKET_STRUCTURE` are normative, NOT illustrative** — orchestrator (`sdd-execute`) and auditor query them by exact string (`extract <ticket> PHASE_P<N>`, `META`, `EXECUTION_LOG`, …). Renaming or omitting a templated anchor breaks programmatic dispatch. Each `### P<N>` phase block under `## 3. Phases` gets its own anchor (`PHASE_P1`, `PHASE_P2`, …); the `## 3. Phases` container itself is NOT wrapped — extraction is per-phase.
    </Axiom>
  </Belief_State>

  <Golden_Example>
    Concrete ticket — `tasks/backend/payments/payments.task-04.md`. **Pattern: one module-spec → one ticket.** Port + Adapter + Value Objects + module barrel co-edit and travel together. Phases inside the ticket separate `impl` vs `test` cascades. Names of rules in the Activation Plan are project-specific (driven by cascade); the directive itself is language-agnostic.

    ```markdown
    # Task: TSK-04 — Implement payments module

    ## 1. Meta
    - **Task-ID:** TSK-04
    - **Status:** [ ] TODO
    - **Purpose:** Реализовать модуль `payments` целиком: `PaymentGatewayPort` + `StripePaymentAdapter` + `PaymentRequest`/`TransactionId` Value Objects + module barrel; покрыть unit + integration тестами.
    - **Scope:** `backend`
    - **Module:** `payments`
    - **Dependencies:** TSK-01, TSK-03
    - **Spec References:**
      - Module spec: [payments](../../../specs/backend/payments/payments.spec.md)
      - Contract: [`PaymentGatewayPort`](../../../specs/backend/payments/payments.spec.md#paymentgatewayport)
      - Adapter: [`StripePaymentAdapter`](../../../specs/backend/payments/payments.spec.md#stripepaymentadapter)
      - Consumer: [`OrderProcessor`](../../../specs/backend/orders/orders.spec.md#orderprocessor)
    - **Runtime Backing:** `real-runtime`
    - **Verification Levels:** `unit`, `integration`
    - **Deferred Runtime Scope:** None

    ## 2. Phases Overview
    | ID | Kind | Deps | Status |
    |----|------|------|--------|
    | P1 | impl | —    | [ ]    |
    | P2 | test | P1   | [ ]    |

    ## 3. Phases

    ### P1 — impl
    - **Objective:** реализовать Port + Adapter + Value Objects + module barrel в одной impl-фазе (один phase-subagent context).
    - **Rules:**
      - [typescript-rules](../../../ai/directives/coding/typescript-rules.xml)
      - [ports-adapters](../../../ai/directives/architecture/ports-adapters.xml)
    - **Target Files:**
      - `src/payments/ports/payment-gateway-port.ts`
      - `src/payments/value-objects/payment-request.ts`
      - `src/payments/value-objects/transaction-id.ts`
      - `src/payments/adapters/stripe-payment-adapter.ts`
      - `src/payments/index.ts`               <!-- trivial wiring lives here, not a separate phase -->
    - **Inputs:** none
    - **Exit:** typecheck pass; ports-adapters compliance; intro-discipline honored; `import { PaymentGatewayPort } from '@/payments'` resolves through module barrel.

    ### P2 — test
    - **Objective:** unit + integration tests против контракта `PaymentGatewayPort` и `StripePaymentAdapter`.
    - **Rules:**
      - [node-test](../../../ai/directives/testing/node-test.xml)
    - **Target Files:**
      - `src/payments/adapters/stripe-payment-adapter.test.ts`
      - `src/payments/ports/payment-gateway-port.contract.test.ts`
    - **Inputs:** P1 handoff
    - **Exit:** все BDD-сценарии из section 4 покрыты; tests pass
    ```

    **Anti-pattern (forbidden):** splitting this into `TSK-04 Port + VOs`, `TSK-05 Adapter`, `TSK-06 module barrel`. Sequential split (each depends on prior) without (C) context overflow = pure sub-process overhead per `AX_DAG_AND_TICKET_BOUNDARIES`.
  </Golden_Example>

  <Halt_Conditions>
    | 🛑 ID | Trigger |
    |---|---|
    | `H_NO_SPECS` | No specs/README.md or no scope specs found |
    | `H_AMBIGUOUS_MODE` | `tasks/` present + intake unclear |
    | `H_INCOMPLETE_SCOPE_SPEC` | Scope spec present but Discovery/required sections incomplete |
    | `H_MISSING_RULES` | Any cascade source OR transitive `<Depends_On>` references a missing rule file |
    | `H_RULES_CYCLE` | Transitive `<Depends_On>` closure encounters a cycle between rule files |
    | `H_ID_COLLISION` | Generated `TSK-NN` collides with existing |
    | `H_OPERATOR_REJECT` | Operator refuses Cascade Table / DAG / batch / final review |
    | `H_LOW_CONFIDENCE` | Confidence LOW at DAG or task generation |
    | `H_VERIFICATION_COMMAND_MISSING` | RequiresVerification alias not found in infra-spec Verification Commands |
    | `H_BOOTSTRAP_REQUIREMENTS_MISSING` | Scope spec lacks Bootstrap Requirements section (spec did not pass discovery STEP_7) |
    | `H_TYPING_SCENARIO_MISSING` | A contract in Spec References has no `contract`-level typing scenario in section 4 per `AX_TICKET_HAS_BDD_AND_TESTS` |
  </Halt_Conditions>

  <Execution_Plan>
    <Step id="STEP_0_INTAKE">
      <Goal>Read Specs Portal → detect scopes and graph (`AX_SCOPE_GRAPH_DETECTION`) → detect mode (`AX_MODE_AUTO_DETECT_OR_HALT`).</Goal>
      <Action>
        1. Emit TRACE_HEADER (STACK `ROOT__INTAKE`).
        2. **Read `specs/README.md` Scope Graph as canonical entry point.** Portal absent → `H_NO_SPECS`. From Portal extract: all scope names + types + depends-on edges (Mermaid graph + Scopes table).
        3. For each scope with ✅ status, read `specs/<scope>/<scope>.spec.md`.
        4. For each product/library scope with 8 Module Map, read module specs.
        5. Scope graph detection per `AX_SCOPE_GRAPH_DETECTION`. All absent → `H_NO_SPECS`.
        6. Mode detection per `AX_MODE_AUTO_DETECT_OR_HALT`. On `H_AMBIGUOUS_MODE` halt with operator question.
        7. In `extend-dag`: read existing `tasks/README.md`, per-scope READMEs, ticket files; capture max `TSK-NN` and current DAG.
        8. Proceed to STEP_1.
      </Action>
    </Step>

    <Step id="STEP_1_STACK_RESOLUTION">
      <Goal>Load rule registry. Verify all rule references resolve. Build per-scope Cascade Tables. Operator approval.</Goal>
      <Action>
        1. TRACE_HEADER (STACK `ROOT__STACK_RESOLUTION`).
        2. **Read `ai/directives/knowledge.xml` in full.** This is the canonical rule registry — contains `<Triggers>`, `<SkipWhen>`, `<ActivationHint>`, `<RequiresVerification>` for every rule. Required before verifying refs and before building per-phase Rules lists in STEP_4. Read it now — do not defer.
        3. For each scope: traverse depends-on edges (transitive closure) to compute traversed-scopes. Collect rule refs from all traversed-scopes + target-scope + modules (task-tier added in STEP_3).
        4. For each ref, verify file existence under `ai/directives/<category>/<rule>.xml`. Any miss → `H_MISSING_RULES` (abort with explicit list).
        5. Build per-scope Cascade Tables (Scope × Categories matrix; tier rows from graph).
        6. Phase Progress + Approval Check. STOP.
      </Action>
    </Step>

    <Step id="STEP_2_DAG">
      <Goal>Build acyclic task DAG in topological implementation order.</Goal>
      <Action>
        1. TRACE_HEADER (STACK `ROOT__DAG`).
        2. **Read Bootstrap Requirements of each in-scope spec.** Section missing in any spec being scaffolded → `H_BOOTSTRAP_REQUIREMENTS_MISSING` (spec did not pass discovery STEP_7; abort with the offending scope name). For each row:
           - Owner=`this-scope-task` → produce a Phase 0 ticket per `AX_BOOTSTRAP_TICKET_DERIVATION` (`bootstrap-<kind>-<short-name>`); Verification populated from Resolution column.
           - Owner=`external-prereq-scope` → add cross-scope dependency edge (already declared in Scope Dependencies; verify consistency).
           - Owner=`operator-action` → record in tracker index as an external prerequisite blocking Phase 0.
        3. Analyze Entity Inventory + Contracts + Inter-Module Dependencies per module spec. Cross-scope dependencies from scope graph edges.
        4. Form post-bootstrap tickets per `AX_DAG_AND_TICKET_BOUNDARIES` (default: one per coherent spec unit — one ticket per module-spec for product/library; one ticket per discrete capability for infra/contracts). Subdivide only when (P) parallel-executable or (C) context overflow. Assign sequential `TSK-NN` (project-wide; bootstrap tickets numbered first).
        5. Check: no cycles; no context-overflow tickets per (C); no missing prerequisites; every non-bootstrap ticket depends (transitively) on all bootstrap tickets of the same scope.
        5. Phase Progress + Approval Check (Mermaid graph). STOP.
      </Action>
    </Step>

    <Step id="STEP_3_INDEX_GENERATION">
      <Goal>Write project tracker + per-scope trackers per TASKS_README_STRUCTURE + SCOPE_TASKS_README_STRUCTURE.</Goal>
      <Action>
        1. TRACE_HEADER (STACK `ROOT__INDEX_GENERATION`).
        2. Write `tasks/README.md` per `TASKS_README_STRUCTURE`. Project-Wide Conventions declared ONCE here per `AX_TICKET_DEDUPLICATION`. No Cascade Table here.
        3. Per scope: write `tasks/<scope>/README.md` per `SCOPE_TASKS_README_STRUCTURE` with per-scope Cascade Table.
        4. If cross-scope integrations exist: create a dedicated `integration` scope entry in `specs/README.md` and write `tasks/integration/README.md`.
        5. Phase Progress + Approval Check. STOP.
      </Action>
    </Step>

    <Step id="STEP_4_TASK_GENERATION">
      <Goal>Emit each ticket per `TASK_TICKET_STRUCTURE`. Project-wide content NOT duplicated.</Goal>
      <Action>
        For each task:
        1. TRACE_HEADER (STACK `ROOT__TASK_GENERATION__<TASK_ID>`).
        2. Verify ID uniqueness per `AX_TASK_ID_UNIQUENESS`. Collision → `H_ID_COLLISION`.
        3. Decompose into phases per `AX_PHASES_DECLARED_IN_HEADER`. Compute scope-level cascade per `AX_RULES_CASCADE_RESOLUTION`; for each phase, derive `Rules:` list per `AX_RULE_ACTIVATION_PLAN` (per-phase filtering by Target Files + kind).
        4. Determine ticket path:
           - Scope-level task: `tasks/<scope>/<scope>.task-NN.md`.
           - Module-level task: `tasks/<scope>/<module>/<module>.task-NN.md`.
           - Cross-scope integration: `tasks/integration/<label>.task-NN.md`.
        5. Draft section 4 BDD per `AX_TICKET_HAS_BDD_AND_TESTS`, including the mandatory `contract`-level typing scenario for each DbC contract in Spec References.
        6. **BDD review pass — isolated subagent.** Dispatch ONE general-purpose subagent with clean context; inputs = module spec slice + contract anchors + Requirements & Constraints + draft section 4 only; question = «какие negative / corner / trust-boundary / failure-mode сценарии отсутствуют?». Merge approved candidates into section 4 + section 6; append the full reviewed checklist (merged / rejected with reason) to section 8 Decision Log. Out-of-scope proposals (new entities / phases / contracts) → rejected, surfaced to operator at STEP_5.
        7. Validate every contract in Spec References has its typing scenario mapped to a real test file under a `test` phase of THIS ticket. Missing → `H_TYPING_SCENARIO_MISSING` (name offending contract).
        8. Write ticket per `TASK_TICKET_STRUCTURE`.
        9. Pre-fill section 7 Execution Log as PLAN per `AX_EXECUTION_LOG_PLAN_VS_FACT` — one `#### P<N>` block per phase declared in section 2 Phases Overview.
        10. Phase Progress per batch + Approval Check. STOP.
      </Action>
    </Step>

    <Step id="STEP_5_REVIEW">
      <Goal>Final operator agreement.</Goal>
      <Action>
        TRACE_HEADER (STACK `ROOT__REVIEW`). List created files with traceability links. Approval Check. STOP.
      </Action>
    </Step>
  </Execution_Plan>

  <Frame_Rules>
    <Rule id="FRAME_PUSH_WHEN">Open nested frame on disputes about granularity, order, BDD scenarios, deferred coverage, per-task detail.</Rule>
    <Rule id="FRAME_POP_WHEN">Close on confirmed conclusion, deferred status, or when local discussion cannot advance.</Rule>
    <Rule id="FRAME_STATUS_VALUES">OPEN | BLOCKED | READY_TO_RETURN | READY_TO_ADVANCE | DEFERRED.</Rule>
  </Frame_Rules>

  <Output_Contracts>
    <Contract id="TRACE_HEADER_FORMAT">
      ```text
      📋 TS_R<N> | STACK: ROOT__<FRAME>__<SUBFRAME> | FRAME: F_<KEY>_R<N> | <📂|🚧|↩️|⏭️|💤> <STATUS> | CONF: <LOW|MEDIUM|HIGH>
      🎯 GOAL: <local goal>
      ⏭️ EXIT: <exit condition>
      ```
    </Contract>

    <Contract id="PHASE_PROGRESS_FORMAT">
      ```markdown
      🎯 Phase Progress — <STEP_NAME>
        ✅ Closed:    <agreed>
        ⏳ Open:      <under discussion>
        🛑 Blocking:  <if any, else —>
        ▶️ Next:      <proposal>
        📊 Counters:  <e.g. "DAG: 18 tasks across 3 scopes; 14/18 tickets generated">
      ```
    </Contract>

    <Contract id="TASK_TICKET_STRUCTURE">
      Anchor names in this template are normative per `AX_TICKET_SECTION_NAMES_NORMATIVE`. Project-wide content (file-header rule, baseline Completion Rule, Execution Log protocol, audit hint) lives in `tasks/README.md` per `AX_TICKET_DEDUPLICATION` — NOT duplicated here.

      ```markdown
      # Task: <Task-ID> — <Task Title>

      <!--SECTION:META-->
      ## 1. Meta
      - **Task-ID:** <TSK-NN>
      - **Status:** [ ] TODO   <!-- [ ] TODO | [~] IN_PROGRESS | [x] DONE | [!] BLOCKED -->
      - **Purpose:** <semantic goal one-liner>
      - **Scope:** <scope-name>
      - **Module:** <module-name or N/A>
      - **Dependencies:** <comma-separated Task-IDs or None>
      - **Reopens:** <count> (<YYYY-MM-DD> — <last reason>)   <!-- omit when 0 -->
      - **Spec References:**
        - Contract: [<ContractName>](<spec anchor>)
        - Consumer: [<ConsumerName>](<spec anchor>)
        - Constraints (if applicable): [<ScopeSpec section 4>](<path>)
      - **Runtime Backing:** `not-implemented` | `simulation` | `real-runtime`
      - **Verification Levels:** subset of `contract` | `unit` | `integration` | `e2e`
      - **Deferred Runtime Scope:** None | <description>
      <!--/SECTION:META-->

      <!--SECTION:PHASES_OVERVIEW-->
      ## 2. Phases Overview
      | ID | Kind     | Deps | Status |
      |----|----------|------|--------|
      | P1 | <kind>   | —    | [ ]    |
      | P2 | <kind>   | P1   | [ ]    |

      <!-- Status set per phase by phase-subagent at end of phase. Orchestrator reads this table for planning. -->
      <!--/SECTION:PHASES_OVERVIEW-->

      ## 3. Phases

      <!--SECTION:PHASE_P1-->
      ### P1 — <kind>
      - **Objective:** <one-line description>
      - **Rules:**
        - [ai/directives/<category>/<rule>.xml](<relative-path>)
        - [ai/directives/<category>/<rule>.xml](<relative-path>)
      - **Target Files:**
        - <path>
        - <path>
      - **Inputs:** none   <!-- or "P0 handoff" / "P0, P1 handoffs" -->
      - **Exit:** <verifiable criterion, e.g. "typecheck pass; ports-adapters compliance">
      <!--/SECTION:PHASE_P1-->

      <!--SECTION:PHASE_P2-->
      ### P2 — <kind>
      - **Objective:** <one-line>
      - **Rules:**
        - [ai/directives/<category>/<rule>.xml](<relative-path>)
      - **Target Files:**
        - <path>
      - **Inputs:** P1 handoff
      - **Exit:** <verifiable criterion>
      <!--/SECTION:PHASE_P2-->

      <!--SECTION:BDD-->
      ## 4. Acceptance Criteria (BDD)
      Contract: see Spec References.

      **Feature:** <component behavior>

      **Scenario:** <name> [`<verification level>`]
      - **Given** <precondition>
      - **When** <command/query>
      - **Then** <postcondition>
      - **And** <side effect>
      <!--/SECTION:BDD-->

      <!--SECTION:VERIFICATION-->
      ## 5. Verification
      | Command | Required by |
      |---------|-------------|
      | <resolved invocation> | <rule-id>, <rule-id> |

      <!-- One row per unique Verification Commands alias from infra-spec. Multiple rules
           sharing check-command produce a single row. Phase-subagent runs only the rows
           whose Required-by overlaps with its phase's Rules list. -->

      - **Task-specific Completion additions:** <list or "none beyond project baseline">
      <!--/SECTION:VERIFICATION-->

      <!--SECTION:TEST_COVERAGE-->
      ## 6. Test Scenario Coverage
      - Scenario <name> → `<test-file>` :: `<canonical case name>`
      <!--/SECTION:TEST_COVERAGE-->

      <!--SECTION:EXECUTION_LOG-->
      ## 7. Execution Log
      *(Round = one execute-then-audit attempt. Per-phase blocks within a Round. Skeleton is minimal — event lines (`intro` / `decision` / `tried` / `discovery` / `insight` / `BLOCKED`) appear ONLY when the event happens. Token vocabulary in [tasks/README.md#execution-log-template](../../README.md#execution-log-template).)*

      ### Round 1 — <YYYY-MM-DD>, initial
      <!-- Skeleton pre-filled: only the closing ver + DONE lines per phase. Phase agent
           prepends event lines as decisions/discoveries/intros/problems actually happen. -->

      #### P1
      - [ ] `<ts>` ver `<cmd>` → `<pass|fail>` exit=`<code>`
      - [ ] `<ts>` DONE
      **Handoff →** artifacts: [...]; decisions: [...]; open: [...]

      #### P2
      - [ ] `<ts>` ver `<cmd>` → `<pass|fail>` exit=`<code>`
      - [ ] `<ts>` DONE
      **Handoff →** artifacts: [...]; decisions: [...]; open: [...]

      <!-- After last phase, orchestrator appends Round close: -->
      #### Round close
      - [ ] `<ts>` DONE
      <!--/SECTION:EXECUTION_LOG-->

      <!-- AUDIT_ROUNDS section appended ONLY after first reopen-triggering audit, per audit AX_REOPEN_ROUNDS_IN_TICKET. Anchor format: -->
      <!--   <!--SECTION:AUDIT_ROUNDS--> -->
      <!--   ## Audit Rounds -->
      <!--   …(per TICKET_AUDIT_ROUND_FORMAT in audit.directive.xml) -->
      <!--   <!--/SECTION:AUDIT_ROUNDS--> -->
      ```
    </Contract>

    <Contract id="TASKS_README_STRUCTURE">
      Project-level tracker. High-level DAG = cross-scope edges only; intra-scope edges live in scope READMEs. No Cascade Table here.

      ```markdown
      # Project Tasks

      ## Entry Points
      - [Specs Portal](../specs/README.md) — Scope Graph + all scope specs.
      - Tickets are executed ONLY via `sdd-execute` SKILL (single ticket) or `sdd-execute-batch` SKILL (queue). The orchestrator dispatches phase-subagents per ticket's Phases Overview, then `sdd-audit` automatically — operator does not invoke audit manually.

      ## Project-Wide Conventions

      ### File-header Convention
      Per `AX_FILE_HEADER_TASK_TRACEABILITY` — canonical format, rules, and lang-agnostic note defined there.

      ### Completion Rule (baseline)
      A task cannot transition to `[x] DONE` until ALL of (per `AX_DONE_REQUIRES_EVIDENCE`):
      1. Every phase declared in section 2 Phases Overview has Status `[x]`.
      2. Every BDD scenario mapped to test ownership in section 6 OR has `Deferred Test Ownership: <task-id>`.
      3. Verification commands relevant to each phase executed; results + exit codes recorded in that phase's Execution Log block.
      4. Canonical case names match real test cases or ticket updated.
      5. `Deferred Runtime Scope` recorded if applicable.
      6. Every introduced-beyond-Inventory entity logged as `<ts> intro <Name> ← <reason>` in the relevant phase block.
      7. Every phase block ends with a typed **Handoff →** line.

      Task-specific additions live in each ticket's section 5.

      ### Execution Log Template
      Canonical token vocabulary (single source of truth; phase-protocol and audit reference this table, do not redefine):

      | Token | Tail | Mandatory when |
      |---|---|---|
      | `intro` | `<Entity> ← <reason>` | new entity appears in code beyond module Entity Inventory |
      | `decision` | `<key>=<value> ← <reason>` | typed choice that affected output |
      | `tried` | `<approach> → <result>` | approach attempted then abandoned (failed path worth recording) |
      | `discovery` | `<fact>` | reality diverged from spec / assumption |
      | `insight` | `<observation> → <spec-section>, <change>` | spec gap detected |
      | `verified` | `<tool>@<version> <summary>` | `config` kind: third-party API confirmed |
      | `ver` | `<cmd> → pass|fail exit=<N>` | once per phase, closing run (always present) |
      | `BLOCKED` | `<cause>` | phase ended `[!] BLOCKED` |
      | `DONE` | (no tail) | terminal line of phase or Round close (always present) |

      Round structure:
      ```markdown
      ### Round <N> — <YYYY-MM-DD>, <reason>

      #### P1
      <!-- event lines (0+, from the table above) appended as events happen -->
      - [x] `<ts>` ver <cmd> → pass exit=0
      - [x] `<ts>` DONE
      **Handoff →** artifacts: [...]; decisions: [...]; open: [...]

      #### Round close
      - [x] `<ts>` DONE
      ```

      Trivial phase with no events → 2 lines (`ver` + `DONE`) + Handoff. Padding with empty lines is forbidden.

      ⛔ `[x]` line with any unreplaced `<…>` literal = fabricated done → `EXECUTION_LOG_INCOMPLETE` (BLOCKER).

      ### Post-task Hook
      Per `AX_AUDIT_HOOK`. After last phase of a Round closes, the orchestrator dispatches `sdd-audit`. Until audit returns PASS, Round is closed-but-unverified and dependents are blocked.

      ## High-Level DAG
      Cross-scope edges + integration tickets only. Intra-scope DAGs live in per-scope READMEs.

      ```mermaid
      graph TD
        backend --> infra-base
        web --> infra-base
        web --> backend
        TSK-13[Cross-scope integration] -.-> web
      ```

      ## Tracker Index
      | Scope | Type | Tracker | Tasks | Done |
      |---|---|---|---|---|
      | infra-base | infrastructure | [README](infra-base/README.md) | 6 | 0/6 |
      | api-contracts | contracts | [README](api-contracts/README.md) | 2 | 0/2 |
      | backend | product | [README](backend/README.md) | 12 | 0/12 |
      | web | product | [README](web/README.md) | 8 | 0/8 |
      | integration | integration | [README](integration/README.md) | 1 | 0/1 |

      ## Decision Log (task-scaffolding-level)
      [D-NNN entries when operator made non-default choices.]
      ```
    </Contract>

    <Contract id="SCOPE_TASKS_README_STRUCTURE">
      Per-scope tracker at `tasks/<scope>/README.md`. Contains Cascade Table (derived from scope graph) + intra-scope DAG + Tracker.

      ```markdown
      # Tasks: <scope-name>

      ## Scope Spec
      - [Scope spec](../../specs/<scope>/<scope>.spec.md)

      ## Cascade Table
      Effective rules for tasks in this scope. Derived from scope graph (depends-on transitive closure).

      Tier order (low → high priority on collision): `traversed-scopes` → `target-scope` → `module:<name>` → `task`.

      | Tier | coding | testing | architecture | infra |
      |------|--------|---------|--------------|-------|
      | infra-base (traversed) | typescript-rules | vitest-rules | | eslint-setup, git-setup, nodejs-npm-setup |
      | api-contracts (traversed) | | | | |
      | <scope-name> (target) | | | ports-adapters | |
      | module:payments | | node-test | | |

      ### Rule Sources
      - Traversed scopes: [scope graph](../../specs/README.md)
      - Target scope: [<scope> spec 5/4.5](../../specs/<scope>/<scope>.spec.md)
      - Module: each module's 9 Handoff
      - Files: `ai/directives/<category>/<rule>.xml`

      ## Intra-Scope DAG
      ```mermaid
      graph TD
        TSK-04 --> TSK-05
        TSK-06 --> TSK-04
      ```

      ## Tracker
      | Task-ID | Title | Module | Dependencies | Status | Reopens |
      |---------|-------|--------|--------------|--------|---------|
      | [TSK-04](payments/payments.task-04.md) | Implement StripePaymentAdapter | payments | TSK-01, TSK-03 | `[ ]` TODO | 0 |

      ## Notes
      [Optional: scope-specific execution notes, deviations, deferred items.]
      ```
    </Contract>
  </Output_Contracts>

</SddTaskScaffolding>
