Claude Skill

skf-refine-architecture

Improve architecture doc using verified skill data and VS feasibility findings. Use when the user requests to "refine skill architecture" or "improve architecture doc."

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download armelhbobdad-bmad-module-skill-forge-src_skf-refine-architecture-492e73e.zip · 27 KB
Part of armelhbobdad/bmad-module-skill-forge — 15 skills

Install

skills CLI npx skills add https://github.com/armelhbobdad/bmad-module-skill-forge/tree/main/src/skf-refine-architecture
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install armelhbobdad-bmad-module-skill-forge@llmmart
Git git clone https://github.com/armelhbobdad/bmad-module-skill-forge.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole armelhbobdad/bmad-module-skill-forge collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

Refine Architecture

Overview

Takes an original architecture document + generated skills + optional VS feasibility report, and produces a refined architecture with gaps filled, issues flagged, and improvements suggested — all backed by specific API evidence from the generated skills. This workflow enhances the original architecture — it never deletes original content, only adds annotations, subsections, and suggestions.

Conventions

  • Bare paths (e.g. references/<name>.md) resolve from the skill root.
  • references/ holds prompt content carved out of SKILL.md (workflow stages chained via frontmatter nextStepFile, plus static reference docs); scripts/ and assets/ hold deterministic helpers and templates.
  • {skill-root} resolves to this skill's installed directory (where customize.toml lives, if present).
  • {project-root}-prefixed paths resolve from the project working directory.
  • {skill-name} resolves to the skill directory's basename.

Role

You are an architecture refinement analyst operating in Ferris Architect mode. You bring expertise in API surface analysis, integration gap detection, and evidence-backed architecture improvement, while the user brings their architecture vision and generated skills. Every suggestion must cite specific APIs from the generated skills — evidence-backed suggestions, not speculation.

Workflow Rules

These rules apply to every step in this workflow:

  • Never speculate — every gap, issue, or improvement must cite specific APIs, types, or function signatures from the generated skills
  • Only load one step file at a time — never preload future steps
  • If any instruction references a subprocess or tool you lack, achieve the outcome in your main context thread
  • Always communicate in {communication_language}
  • At any interactive prompt, the inputs cancel, exit, [X], q, or :q exit cleanly with exit code 6 (halt_reason: "user-cancelled")
  • If {headless_mode} is true, auto-proceed through confirmation gates with their default action and log each auto-decision

Stages

# Step File Auto-proceed
1 Initialize & Load Inputs references/init.md No (confirm)
2 Gap Analysis references/gap-analysis.md Yes
3 Issue Detection references/issue-detection.md Yes
4 Improvements references/improvements.md Yes
5 Compile Refined Architecture references/compile.md No (review)
6 Report references/report.md Yes
7 Workflow Health Check references/health-check.md Yes

Invocation Contract

Aspect Detail
Inputs architecture_doc_path [required], vs_report_path [optional]
Flags --headless / -H (auto-resolve all gates); --architecture-doc <path> (skip step 1 prompt for the required input); --vs-report-path <path> (skip step 1 prompt for the optional VS report); --scope-skills <names> (comma-separated in-scope skill names; overrides scope derivation in gap analysis)
Gates step 1: Input Gate [use args] step 5: Review Gate [C] continue / [X] cancel step 6: Exit menu [R] review / [X] exit
Outputs refined-architecture-{arch_project_name}.md at {outputFolderPath} ({arch_project_name} = the architecture doc's frontmatter project_name, else config project_name — resolved in init.md), plus refine-architecture-result-{timestamp}.json and refine-architecture-result-latest.json
Headless All gates auto-resolve with default action when {headless_mode} is true. Per-flag args (--architecture-doc, --vs-report-path) consumed at the gates that would otherwise prompt.
Exit codes See "Exit Codes" below

Exit Codes

Every HARD HALT in this workflow exits with a stable code so headless automators can branch on the failure class without grepping message text:

Code Meaning Raised by
0 success step 7 (terminal)
2 input-missing / input-invalid step 1 §1 (headless missing architecture-doc arg, or invalid path) → input-missing; non-existent file → input-invalid
3 resolution-failure On-Activation §5 (output_folder or forge_data_folder unconfigured)
4 write-failure On-Activation §5 pre-flight write probe; step 1 §3c (RA state file write failed); step 5 §6 (refined-architecture write failed); step 6 §3 (result-contract write failed)
5 state-conflict step 1 §3 (no skills found — refinement requires ≥1 skill)
6 user-cancelled step 1 §1 prompt cancelled; any prompt that accepted cancel/exit/:q; step 5 review gate [X]
7 inventory-unreliable step 1 §2 (>20% skill-inventory warnings exceed budget)
8 recovery-failed step 5 §1 (durability state insufficient to reconstruct Step 02-04 findings); step 6 §1 (## Refinement Summary absent from the compiled document)

Result Contract (Headless)

When {headless_mode} is true, step 6 emits a single-line JSON envelope on stdout before chaining to step 7, and every HARD HALT emits the same envelope shape on stderr with status: "error":

SKF_REFINE_ARCHITECTURE_RESULT_JSON: {"status":"success|error","refined_path":"…|null","gap_count":0,"issue_count":0,"improvement_count":0,"exit_code":0,"halt_reason":null}

status is "success" on the terminal happy path, "error" on any HALT. halt_reason is one of: null (success), "input-missing", "input-invalid", "insufficient-skills", "output-folder-unconfigured", "forge-folder-unconfigured", "inventory-unreliable", "write-failed", "recovery-failed", "user-cancelled". exit_code matches the table above.

On Activation

  1. Load config from {project-root}/_bmad/skf/config.yaml and resolve:

    • project_name, user_name, communication_language, document_output_language
    • skills_output_folder, forge_data_folder, output_folder, sidecar_path
  2. Compute run-scoped variables:

    • timestamp ← UTC YYYYMMDD-HHmmss captured at activation time. Fixed for the entire workflow run; report.md reuses this when writing the result contract.
  3. Resolve {headless_mode}: true if --headless or -H was passed as an argument, or if headless_mode: true in {sidecar_path}/preferences.yaml. Default: false.

  4. Resolve workflow customization. Run:

    python3 {project-root}/_bmad/scripts/resolve_customization.py \
        --skill {skill-root} --key workflow
    

    The script merges the three customization layers per bmad-customize's structural merge rules (scalars override, arrays append):

    • {skill-root}/customize.toml — bundled defaults
    • _bmad/custom/<skill-name>.toml under {project-root} — team overrides (committed)
    • _bmad/custom/<skill-name>.user.toml under {project-root} — personal overrides (gitignored)

    If the script fails or is missing, fall back to reading {skill-root}/customize.toml directly — the bundled defaults are an empty string for each path scalar.

    Apply the path-scalar fallback now so stage files don't have to repeat the conditional logic. For each scalar, if the merged value is empty or absent, use the bundled default:

    • {refinementRulesPath} ← workflow.refinement_rules_path if non-empty, else references/refinement-rules.md
    • {outputFolderPath} ← workflow.output_folder_path if non-empty, else {output_folder}
    • {onCompleteCommand} ← workflow.on_complete if non-empty, else empty (no-op — report.md skips the hook invocation entirely)

    Stash all three as workflow-context variables. Stage files reference them directly — no conditional at the usage site.

    Also apply the array surfaces (not silent no-ops): run workflow.activation_steps_prepend now, treat workflow.persistent_facts as standing context for the run (file:-prefixed entries load their file/glob contents as facts), then run workflow.activation_steps_append after activation.

  5. Pre-flight config + write probe. Assert both output paths are configured, then probe writability — order matters: an empty path makes mkdir -p "" fail, which would misreport a missing config (exit 3) as a write failure (exit 4) and collapse the distinction the Result Contract draws.

    Config-completeness (exit 3). If {outputFolderPath} is empty: HALT (exit code 3, halt_reason: "output-folder-unconfigured") — "output_folder is not configured in config.yaml. Add an output_folder path and re-run [RA]." If {forge_data_folder} is empty: HALT (exit code 3, halt_reason: "forge-folder-unconfigured") — "forge_data_folder is not configured in config.yaml. Add a forge_data_folder path and re-run [RA]."

    Write probe (exit 4). With both paths now non-empty, verify each is writable — a read-only mount, full disk, or permissions-denied path otherwise only surfaces at init.md §3c's RA state file write, by which point the user has already gone through input prompts:

    for dir in "{outputFolderPath}" "{forge_data_folder}"; do
      mkdir -p "$dir" && \
        printf 'probe' > "$dir/.skf-write-probe" && \
        rm "$dir/.skf-write-probe"
    done
    

    On any non-zero exit: HALT (exit code 4, halt_reason: "write-failed"). In headless mode, every HALT above emits the error envelope per Result Contract (Headless) with refined_path: null.

  6. Load, read the full file, and then execute references/init.md to begin the workflow.

Files (bmad-module-skill-forge)
  • references
    • compile.md 7.5 KB
      ---
      nextStepFile: 'report.md'
      # {arch_project_name} resolved in init.md (arch-doc frontmatter project_name, else config project_name).
      outputFile: '{outputFolderPath}/refined-architecture-{arch_project_name}.md'
      ---
      
      <!-- Config: communicate in {communication_language}. Compile the refined architecture document in {document_output_language}. -->
      
      # Step 5: Compile Refined Architecture
      
      ## STEP GOAL:
      
      Produce the refined architecture document by starting with the original as a base, adding gap-fill subsections, issue callout blocks, and improvement suggestions. Append a Refinement Summary. Present for user review before finalizing.
      
      ## Rules
      
      - Do not discover new gaps, issues, or improvements — use only what Steps 02-04 produced
      - Do not delete, reword, or rearrange original architecture content
      - Present compiled document for user review (gate checkpoint)
      
      ## MANDATORY SEQUENCE
      
      ### 1. Prepare the Original as Base
      
      Load the complete original architecture document.
      
      This is the base. Every line of the original appears in the refined document unmodified — the workflow only adds annotations and subsections; dropping or rewording original content silently discards the user's architecture.
      
      **Context recovery check:** If gap, issue, or improvement findings from Steps 02-04 are not available in context (e.g., due to context degradation in long runs), attempt to read the durability state from `{forge_data_folder}/ra-state-{project_name}.md`. Parse the `<!-- [RA-GAPS] -->`, `<!-- [RA-ISSUES] -->`, and `<!-- [RA-IMPROVEMENTS] -->` comment blocks to recover the complete formatted findings (each block contains full citation text with evidence, not just counts). If a section is still missing or contains only summary counts after recovery, HALT (exit code 8, `halt_reason: "recovery-failed"`): "⚠️ Context for the [Gaps|Issues|Improvements] analysis was lost and the durability state is insufficient to reconstruct findings. Re-run [RA] from the beginning — step 01 will reset the state file, then steps 02-04 will rebuild all findings." In headless, emit the error envelope per SKILL.md "Result Contract (Headless)" with `refined_path: null`.
      
      ### 2. Insert Gap-Fill Subsections
      
      For each gap finding from Step 02:
      
      **Locate the most relevant section** in the original architecture where this integration would logically belong.
      
      **Insert a gap-fill subsection** one heading level deeper than the parent section:
      
      ```markdown
      #### RA: {Library A} <-> {Library B} Integration Path
      
      > [!NOTE] **Gap Identified by Refine Architecture**
      > This integration path was not documented in the original architecture but is supported by skill API evidence.
      
      {Gap description with full evidence citation from Step 02}
      
      **Proposed Integration:**
      {Suggested architecture content describing how the libraries connect}
      ```
      
      If no clear parent section exists, collect orphan gaps into a new section: "## RA: Additional Integration Paths"
      
      ### 3. Insert Issue Annotations
      
      For each issue finding from Step 03:
      
      **Locate the section** containing the contradicted claim.
      
      **Insert an issue callout block** immediately after the contradicted text:
      
      ```markdown
      > [!WARNING] **Issue Detected by Refine Architecture** ({severity})
      > Architecture states: "{quoted claim}"
      > Skill reality: {contradicting evidence from skill}
      > {IF VS report}: VS verdict: {verdict} for {pair}
      >
      > **Suggested Correction:** {specific correction with API evidence}
      ```
      
      **Placement priority:** Place each issue callout immediately after the contradicted text in its original location. If the contradicted claim is inside a Markdown list item, code block, or table row where inserting a callout block would break syntax, place the callout immediately after the enclosing block instead. If the contradicted claim cannot be precisely located, collect into "## RA: Additional Issues Detected" at the end of the document, ordered by severity (Critical first, then Major, then Minor).
      
      ### 4. Insert Improvement Suggestions
      
      For each improvement finding from Step 04:
      
      **Locate the section** where the library is discussed.
      
      **Insert an improvement subsection** one heading level deeper:
      
      ```markdown
      #### RA: Enhancement — {Improvement Title}
      
      > [!TIP] **Improvement Suggested by Refine Architecture** ({value} value)
      > {skill_name} provides `{api}` which is not currently leveraged.
      
      {Full improvement description with evidence citation from Step 04}
      
      **How to Incorporate:**
      {Specific suggestion for updating the architecture}
      ```
      
      **Order by value:** High value improvements first, then Medium, then Low.
      
      **Placement fallback:** If the library's only architecture mention is inside a table, code block, or Mermaid diagram where inserting a subsection would break syntax, collect into `## RA: Additional Improvements Suggested` at the end of the document.
      
      ### 5. Add Refinement Summary Section
      
      Append a `## Refinement Summary` section containing:
      
      - **Header:** "Produced by: Refine Architecture workflow using {skill_count} skills" and date
      - **Changes Made table** with the following rows:
      
      | Category | Count | Breakdown |
      |----------|-------|-----------|
      | Gaps Filled | {gap_count} | — |
      | Issues Flagged | {issue_count} | Critical: {critical_count}, Major: {major_count}, Minor: {minor_count} |
      | Improvements Suggested | {improvement_count} | High: {high_count}, Medium: {medium_count}, Low: {low_count} |
      | Skills Used as Evidence | {skill_count} | — |
      - **Evidence Sources table:** Each skill name and how many refinements cite it
      - **Next Steps:** Review `[!WARNING]` issues, `[!NOTE]` gaps, `[!TIP]` improvements; then run **[SS] Stack Skill** to compose your individual skills into a unified stack skill, providing this refined architecture doc when prompted
      
      ### 6. Write the Refined Document
      
      Write the complete refined architecture to `{outputFile}`.
      
      On any write failure (read-only mount, disk full, permissions denied): HALT (exit code 4, `halt_reason: "write-failed"`) with the captured error. In headless, emit the error envelope per SKILL.md "Result Contract (Headless)" with `refined_path: null`. The On-Activation §5 write probe should have caught an unwritable output folder earlier — if it surfaces here, the filesystem state changed mid-workflow.
      
      ### 7. Present Compiled Document for Review
      
      "**Refined architecture compiled. Please review:**
      
      ---
      
      {Display the Refinement Summary section only — not the full document}
      
      ---
      
      **The full refined document has been written to:** `{outputFile}`
      
      Please review the refinements:
      - {gap_count} gap-fill subsections added
      - {issue_count} issue annotations inserted
      - {improvement_count} improvement suggestions included
      - Original architecture content preserved in full
      
      **Does the refinement look correct?**"
      
      ### 8. Present MENU OPTIONS
      
      Display: **Select:** [C] Continue to Final Report | [X] Cancel
      
      #### GATE [default: C]
      
      This is a review gate: halt for the user's decision and do not chain onward until they approve — an unreviewed compile ships un-vetted refinements. Headless auto-selects [C] (log: "headless: auto-approve compiled architecture").
      
      #### Menu Handling Logic:
      
      - IF C: Load, read entire file, then execute {nextStepFile}
      - IF cancel / exit / [X] / q / :q: HALT (exit code 6, `halt_reason: "user-cancelled"`) — display "Cancelled — refinement not finalized." In headless, emit the error envelope per SKILL.md "Result Contract (Headless)" with `refined_path: null`. These global cancel tokens pre-empt the feedback branch below.
      - IF Any other: Process as feedback, adjust specific refinements in the document, rewrite {outputFile}, redisplay preview, then [Redisplay Menu Options](#8-present-menu-options)
      
      
    • gap-analysis.md 8.6 KB
      ---
      nextStepFile: 'issue-detection.md'
      refinementRulesData: '{refinementRulesPath}'
      ---
      
      <!-- Config: communicate in {communication_language}. Append gap-analysis findings to the RA state file in {document_output_language}. -->
      
      # Step 2: Gap Analysis
      
      ## STEP GOAL:
      
      Find undocumented integration paths — library pairs that have compatible APIs (from the generated skills) but are not described in the architecture document. For each gap, document what APIs connect and propose an architecture section describing the integration.
      
      ## Rules
      
      - Focus only on undocumented integration paths (gaps) — do not detect contradictions (Step 03) or suggest expansions (Step 04)
      - Every gap must include evidence citations from actual skill content
      
      ## MANDATORY SEQUENCE
      
      ### 1. Reference Refinement Rules
      
      Use the refinement rules loaded in Step 01 from `{refinementRulesData}`. If not available in context, reload from `{refinementRulesData}`.
      
      Extract: gap classification (Missing Integration Path, Undocumented Data Flow, Absent Bridge Layer) and detection method.
      
      ### 2. Extract Integration Claims from Architecture
      
      Parse the architecture document for statements describing two or more technologies working together.
      
      **Detection method — prose-based co-mention analysis:** From prose text, find sentences or paragraphs where two or more technology names appear in an *integration relationship* — data flowing between them, one wrapping/bridging/extending/consuming another, or a layer boundary connecting them — not mere co-mention in the same document.
      
      **Mermaid limitation:** Detect co-mentions from prose text only, not from Mermaid diagram syntax — an integration drawn only in a diagram would otherwise surface as a false-positive gap. If `` ```mermaid `` blocks are present in the architecture document, inform the user: "Integration paths documented exclusively in Mermaid diagrams are excluded from co-mention analysis and may appear as false-positive gaps. Consider adding prose descriptions for diagram-only integration paths." Display this warning informatively and immediately continue — this does not halt or modify the analysis sequence.
      
      **Build documented pairs list:**
      - Each pair: `{library_a, library_b, architectural_context}`
      - `architectural_context`: the quoted text or paraphrased description of their relationship
      
      ### 2b. Establish Document Scope
      
      The skill inventory (Step 01 §2) can span a wider product surface than the architecture document under refinement. Pairs drawn from a different surface are not actionable gaps for this document — surfacing them injects irrelevant integration recommendations (e.g. wiring real-time A/V libraries into an admin-dashboard architecture).
      
      Resolve the in-scope skill set:
      
      - **If `{scope_skills}` was provided** (via `--scope-skills`, resolved in Step 01 §1): use it verbatim as `{in_scope_skills}` — it is authoritative.
      - **Otherwise derive:** `{in_scope_skills}` = every inventory skill whose name or primary technology is referenced anywhere in the architecture document (reuse the technology references parsed in §2; match on skill name and library/technology keywords, case-insensitive, word-boundary). Be conservative — when a skill's relevance is ambiguous, treat it as **in-scope**. Surfacing a borderline gap is safer than burying a real one.
      
      `{out_of_scope_skills}` = inventory skills not in `{in_scope_skills}`. A library pair is **out-of-scope** when either of its libraries is in `{out_of_scope_skills}`.
      
      **Safe default:** If scope cannot be derived (e.g. the architecture references no inventory skill by name) and no `{scope_skills}` was provided, treat all skills as in-scope and note: "Could not derive document scope — analyzing all skill pairs." This keeps borderline gaps visible rather than hiding them.
      
      Store `{in_scope_skills}` and `{out_of_scope_skills}` as workflow state — Step 03 (issue detection) reuses them.
      
      ### 3. Read the Pre-Computed Library Pairs
      
      Read the pre-computed unique library pairs from `skill_inventory.pairs` (the enumerate helper's `--pairs` output cached in Step 01 §2 — the complete, deterministic pair set). Do not re-derive it in-context: a silently dropped or duplicated pair is a missed integration gap, this workflow's headline output.
      
      If `skill_inventory.pairs` is absent (the helper was unavailable and the Step 01 §2 fallback path ran), derive the pairs from the inventory as a graceful-degradation fallback only.
      
      ### 4. Load Skill API Surfaces for Cross-Reference
      
      <!-- Subagent delegation: read SKILL.md files in parallel, return compact JSON -->
      
      For each library in the skill inventory, delegate reading to a parallel subagent. Launch up to **8 subagents concurrently** (batch larger inventories in rounds of 8).
      
      **Each subagent receives one skill's SKILL.md path and:**
      1. Reads the SKILL.md file
      2. Extracts the API surface
      3. Returns only this compact JSON — no prose or extra commentary:
      
      ```json
      {
        "skill_name": "...",
        "exports": ["functionName(params): ReturnType", "..."],
        "protocols": ["HTTP", "gRPC", "WebSocket", "message queue", "file I/O", "IPC"],
        "data_formats": ["JSON", "protobuf", "CSV", "binary", "streaming"]
      }
      ```
      
      **Extraction rules for subagents:**
      - `exports`: exported functions with signatures, exported types/interfaces/classes
      - `protocols`: any protocol indicators found in the SKILL.md
      - `data_formats`: any data format indicators found in the SKILL.md
      - If a field has no matches, return an empty array `[]`
      
      **Parent collects all subagent JSON summaries.** Do not load full SKILL.md content into parent context. Store the collected summaries as `{skill_api_surfaces}` workflow state — Step 03 (issue detection) and Step 04 (improvements) reuse them exactly like `{in_scope_skills}`, rather than re-reading each SKILL.md into the parent. This §4 delegate-the-read (compact-JSON return, no full-file load in parent) is the canonical API-surface read pattern for the workflow.
      
      **From metadata.json (read in parent — lightweight), also extract:**
      - `language` — primary programming language
      - `exports` — export count and names
      
      ### 5. Cross-Reference: Identify Gaps
      
      For each library pair in `skill_inventory.pairs` (from §3) not already documented in the architecture:
      
      **Check API compatibility:**
      - Does Library A export types or data that Library B can consume?
      - Do both libraries share a compatible protocol or data format?
      - Are they in the same language or is there a bridge mechanism available?
      
      **Scope routing (from §2b):** Before classifying, check the pair's scope. If the pair is **out-of-scope** (either library is in `{out_of_scope_skills}`), do not add it to the gap list even when its APIs are compatible — record it in the informational **Out-of-Scope** bucket instead (a compatible pair that belongs to a different product surface than this architecture). Only **in-scope** pairs proceed to gap classification below.
      
      **If compatible APIs exist (in-scope pair) but NO architecture mention:**
      - Classify the gap type (Missing Integration Path, Undocumented Data Flow, or Absent Bridge Layer)
      - Document the connecting APIs from both skills
      - Propose a brief architecture section describing the integration
      
      **Cite each gap in this format:**
      ```
      **[GAP]**: {description}
      
      Evidence:
      - {skill_a} exports: `{function}({params}) -> {return_type}`
      - {skill_b} accepts: `{function}({params})`
      - Compatibility: {explanation}
      
      Suggestion: {proposed architecture section content}
      ```
      
      **If no compatible APIs:** Skip this pair — not all pairs need to integrate.
      
      ### 6. Report Gaps & Store Findings
      
      Report the in-scope gap count, then list each gap as a row of **# / Library A / Library B / Gap Type / Connecting APIs** followed by its full §5 citation. Two signals are not inferable from the counts and must survive regardless of format:
      
      - **N == 1 (only one skill loaded):** gap analysis is skipped — pairwise integration analysis needs ≥2 skills, and libraries without a matching skill are invisible to it. Recommend generating skills for all architecture libraries with [CS] or [QS] before re-running [RA], and note issue detection still runs.
      - **Out-of-scope compatible pairs exist (from §2b/§5):** list them separately for awareness only — they were not counted as gaps — and note that re-running with `--scope-skills` (naming the skills to include) pulls any that belong into scope.
      
      Store the **in-scope** gap findings per the Finding Storage rule (refinement rules), under a `<!-- [RA-GAPS] ... -->` block. Record out-of-scope pairs under a separate `<!-- [RA-OUT-OF-SCOPE] ... -->` marker so Step 05 leaves them out of the refined document — they are informational only.
      
      ### 7. Auto-Proceed to Next Step
      
      Load, read the full file and then execute `{nextStepFile}`.
      
      
    • health-check.md 901 B
      ---
      # Note: `shared/health-check.md` resolves relative to the SKF module root
      # ({project-root}/_bmad/skf/ when installed, {project-root}/src/ during
      # development), not relative to this step file.
      nextStepFile: 'shared/health-check.md'
      ---
      
      <!-- Config: communicate in {communication_language}. -->
      
      # Step 7: Workflow Health Check
      
      ## STEP GOAL:
      
      Chain to the shared workflow self-improvement health check at `{nextStepFile}`. This is the terminal step of refine-architecture — after the shared health check completes, the workflow is fully done.
      
      ## Rules
      
      - No user-facing reports, file writes, or result contracts in this step — those belong in step 6
      - Delegate directly to `{nextStepFile}` with no additional commentary
      - Do not attempt any other action between loading this step and executing `{nextStepFile}`
      
      ## MANDATORY SEQUENCE
      
      Load `{nextStepFile}`, read it fully, then execute it.
      
    • improvements.md 4.5 KB
      ---
      nextStepFile: 'compile.md'
      refinementRulesData: '{refinementRulesPath}'
      ---
      
      <!-- Config: communicate in {communication_language}. Append improvement findings to the RA state file in {document_output_language}. -->
      
      # Step 4: Improvement Detection
      
      ## STEP GOAL:
      
      Identify capability expansions — library features documented in the generated skills that the architecture does not leverage. Detect unused capabilities, cross-library synergies visible from skill API surfaces, and alternative patterns that could strengthen the architecture. For each improvement, document the capability and suggest how to incorporate it.
      
      ## Rules
      
      - Focus only on capability expansions not leveraged in the architecture — do not repeat gaps (Step 02) or issues (Step 03)
      - Improvements are additive suggestions — they enhance, not contradict, the architecture
      - Every improvement must include evidence citations from actual skill content
      
      ## MANDATORY SEQUENCE
      
      ### 1. Reference Refinement Rules
      
      Use the refinement rules loaded in Step 01 from `{refinementRulesData}`. If not available in context, reload from `{refinementRulesData}`.
      
      Extract: improvement classification (Unused Capability, Cross-Library Synergy, Alternative Pattern) and detection method.
      
      ### 2. Build Architecture Usage Map
      
      For each library referenced in the architecture document, extract how it is used:
      
      - What capabilities are described (e.g., "Loro for real-time data sync")
      - What APIs or features are referenced
      - What role it plays in the architecture
      
      This creates a map of `{library} -> {described_usage[]}` for comparison against full skill API surfaces.
      
      ### 3. Compare Skill API Surfaces Against Architecture Usage
      
      For each skill in the inventory:
      
      **Start from the surfaces already collected.** Reuse `{skill_api_surfaces}` (the compact `{exports, protocols, data_formats}` summaries from Step 02 §4) for exports, types, and protocol support — do not re-read SKILL.md in the parent.
      
      **For the fuller capability read** — documented capabilities and features that go beyond §4's exports/protocols/data_formats extraction — delegate to parallel subagents mirroring Step 02 §4 (the canonical delegate-the-read pattern): each subagent reads one SKILL.md and returns compact JSON listing that skill's documented capabilities/features; the parent collects the summaries without loading full SKILL.md content. Reload a file directly only if its summary is unavailable or context has compacted.
      
      **Compare against the architecture usage map:**
      - Which exports does the architecture reference or imply usage of?
      - Which exports are not referenced in the architecture at all?
      
      **For each unreferenced capability:**
      - Evaluate relevance: would this capability strengthen the architecture?
      - Skip trivial or internal-only exports (utilities, helpers, debug functions)
      - Flag capabilities that could address architectural concerns or expand functionality
      
      ### 4. Detect Cross-Library Synergies
      
      Examine pairs of skills for complementary capabilities not exploited in the architecture:
      
      - Does Library A export an event system that Library B could consume?
      - Does Library A produce a data format that Library B has an optimized processor for?
      - Do two libraries offer overlapping capabilities that could be unified?
      
      **Only flag synergies where both sides have documented APIs** — do not speculate about undocumented features.
      
      ### 5. Document Each Improvement
      
      For each detected improvement, cite it in this format:
      
      ```
      **[IMPROVEMENT]**: {description}
      
      Evidence:
      - {skill_name} exports: `{function}({params}) -> {return_type}`
      - Architecture uses: {what the architecture currently describes}
      - Untapped: {what the skill offers that the architecture does not mention}
      
      Suggestion: {how to incorporate this capability into the architecture}
      ```
      
      **Categorize improvements:**
      - **High:** Capabilities that address known architectural concerns or significantly expand functionality
      - **Medium:** Capabilities that add convenience or efficiency improvements
      - **Low:** Capabilities that are nice-to-have but not impactful
      
      ### 6. Report Improvements & Store Findings
      
      Report the improvement count with its high/medium/low value breakdown, then list each improvement as a row of **# / Library / Improvement Type / Value / Summary** followed by its full §5 citation.
      
      Store the improvement findings per the Finding Storage rule (refinement rules), under a `<!-- [RA-IMPROVEMENTS] ... -->` block (its citations carry the evidence, value rating, and suggestion).
      
      ### 7. Auto-Proceed to Next Step
      
      Load, read the full file and then execute `{nextStepFile}`.
      
      
    • init.md 10 KB
      ---
      nextStepFile: 'gap-analysis.md'
      refinementRulesData: '{refinementRulesPath}'
      # Resolve `{enumerateStackSkillsHelper}` by probing
      # `{enumerateStackSkillsProbeOrder}` in order (installed SKF module path
      # first, src/ dev-checkout fallback); first existing path wins. §2 calls
      # it for the deterministic skill inventory (cascade-resolved exports,
      # metadata-hash, confidence-tier mapping).
      enumerateStackSkillsProbeOrder:
        - '{project-root}/_bmad/skf/shared/scripts/skf-enumerate-stack-skills.py'
        - '{project-root}/src/shared/scripts/skf-enumerate-stack-skills.py'
      ---
      
      <!-- Config: communicate in {communication_language}. -->
      
      # Step 1: Initialize Refinement
      
      ## STEP GOAL:
      
      Load the architecture document (required), scan the skills folder to build a skill inventory with metadata, load the optional VS feasibility report for context, validate that all inputs exist and meet minimum requirements, and present an initialization summary before auto-proceeding.
      
      ## Rules
      
      - Focus only on loading inputs, scanning skills, and validating prerequisites — do not perform analysis
      - Present a clear initialization summary so downstream steps have validated inputs
      
      ## MANDATORY SEQUENCE
      
      ### 1. Accept Input Documents
      
      "**Refine Architecture — Evidence-Backed Refinement** (additive — never deletes original content).
      
      If you wanted to *verify* the stack first, type `cancel` and run `[VS] Verify Stack`; if no skills exist yet, run `[CS] Create Skill`. Otherwise, please provide the following:
      1. **Architecture document path** (REQUIRED) — your project's architecture doc to refine
      2. **VS feasibility report path** (OPTIONAL) — from a previous [VS] Verify Stack run, for additional context
      
      Or type `cancel` / `exit` / `:q` at any prompt to abort cleanly."
      
      Wait for user input. Store the validated architecture document path as `architecture_doc`. **GATE [default: use args]** — If `{headless_mode}` and `--architecture-doc` was provided: use that path and auto-proceed, log: "headless: using provided architecture path". If `--vs-report-path` was provided, consume it at the VS validation below. If `--architecture-doc` is absent in headless: HALT (exit code 2, `halt_reason: "input-missing"`) and emit the error envelope.
      
      - If the user enters `cancel`, `exit`, `[X]`, `q`, or `:q` at any sub-prompt: Display "Cancelled — no refinement was performed." and HALT (exit code 6, `halt_reason: "user-cancelled"`).
      
      **Validate architecture document:**
      - Confirm the file exists and is readable
      - If missing or unreadable: "Architecture document not found at `{path}`. Provide a valid path."
      - HALT (exit code 2, `halt_reason: "input-invalid"`) if the user cannot provide a valid path. In headless, emit the error envelope per SKILL.md "Result Contract (Headless)" immediately.
      
      **Resolve `{arch_project_name}` (names the refined output file):** Read the architecture document's YAML frontmatter. If it declares a `project_name`, store that value as `{arch_project_name}`; otherwise fall back to the config `{project_name}` resolved at activation. Stash `{arch_project_name}` as a workflow-context variable — `compile.md` and `report.md` resolve `{outputFile}` from it. This makes a producer-side refine of a consumer's architecture doc (the producer/consumer forge split) name the proposal after the doc's own project rather than the forge workspace config. Producer-side working state (`ra-state-{project_name}.md`) and the VS report auto-probe stay keyed on the config `{project_name}`.
      
      **Validate VS report (if provided via `--vs-report-path` or interactive input):**
      - Confirm the file exists and is readable
      - If missing at user-provided path: attempt auto-probe (below) before giving up
      - Store VS report availability as `vs_report_available: true|false` and `vs_report_path`
      
      **Scope hint (optional, `--scope-skills`):** If `--scope-skills <names>` was provided, store the parsed comma-separated list as `{scope_skills}` — gap analysis (Step 02 §2b) uses it as the authoritative in-scope skill set. If absent, leave `{scope_skills}` empty; Step 02 derives scope from the architecture document instead.
      
      ### 2. Scan Skills Folder
      
      **Resolve `{enumerateStackSkillsHelper}`** from `{enumerateStackSkillsProbeOrder}`; first existing path wins.
      
      **Primary path — deterministic enumeration via shared helper:**
      
      ```bash
      python3 {enumerateStackSkillsHelper} enumerate {skills_output_folder} --pairs --reliability
      ```
      
      The helper walks `{skills_output_folder}`, reads each `metadata.json`, applies the version-aware resolution (export-manifest → `active` symlink → flat fallback), captures the exports cascade (metadata → references → SKILL.md), maps `confidence_tier`, and emits structured JSON with one entry per skill plus a top-level `warnings[]` array. Cache the result as `skill_inventory`.
      
      `--pairs` additionally attaches `skill_inventory.pairs` — the complete, deterministic set of unique `{library_a, library_b}` combinations over the skill names (`itertools.combinations`, sorted-name order, `pair_count == N*(N-1)/2`) — plus `skill_inventory.pair_count`. Cache both alongside the inventory. This is the exact pair set Step 02 (gap analysis) iterates; the helper owns the combinatorics, so a pair can never be silently dropped or duplicated at larger N and downstream steps read the set rather than re-deriving it.
      
      Each helper-emitted entry includes: `skill_name`, `version`, `language`, `confidence_tier`, `exports_documented`, `source_repo`, `source_root`, and a `metadata_hash` for change-detection across runs. The helper's `warnings[]` carries per-skill skip reasons (missing SKILL.md/metadata.json, non-symlink `active`, orphan-versions, schema-version violations).
      
      **Failure-budget guard:** `--reliability` attaches the helper-computed verdict — `inventory_reliable` (boolean), `unreliable_ratio`, `skill_count`, `warning_count` — so the reliability threshold lives in one unit-tested place and this step reads a boolean rather than re-deriving a ratio. If `inventory_reliable` is false, HALT (exit code 7, `halt_reason: "inventory-unreliable"`) with: "Inventory scan unreliable — {warning_count}/{skill_count + warning_count} skills returned skip warnings. Re-run [RA] after skills stabilize." In headless, emit the error envelope.
      
      **Fallback path — graceful degradation when the helper is unavailable:** If `{enumerateStackSkillsHelper}` has no existing candidate, fall through to the LLM-driven inventory: walk `{skills_output_folder}` and for each `{skill_package}` read `metadata.json` and extract `name`, `language`, `confidence_tier`, `stats.exports_documented`, `source_repo`/`source_root`. Skip packages missing SKILL.md or metadata.json with a logged warning. On this degraded path only — with no helper to consult — treat the run as unreliable and HALT the same way if skip warnings exceed one in five of the scanned packages.
      
      ### 3. Validate Minimum Requirements
      
      **Check skill count:**
      - At least 1 valid skill must exist
      - If no skills found: "**Cannot proceed.** No skills found in `{skills_output_folder}`. Generate skills with [CS] Create Skill or [QS] Quick Skill, then re-run [RA]."
      - HALT (exit code 5, `halt_reason: "insufficient-skills"`). In headless, emit the error envelope.
      - If exactly 1 valid skill found: "⚠️ Proceeding with 1 skill. Note: gap analysis will find no gaps — pairwise analysis requires at least 2 skills. Step 02 will still execute and issue an appropriate notice. Issue detection and improvement detection will proceed normally."
      
      **Output paths (`{outputFolderPath}`, `forge_data_folder`):** both were asserted non-empty (config-completeness → exit 3, `output-folder-unconfigured` / `forge-folder-unconfigured`) and then probed for writability (→ exit 4, `write-failed`) at On-Activation §5. If either was unconfigured or unwritable the run already halted there, so both are guaranteed present and writable here — no re-check needed.
      
      **Check architecture document:**
      - Confirm it was loaded successfully in section 1
      - If not: HALT with error (should not reach here if section 1 validation passed)
      
      ### 3b. Auto-Probe VS Report
      
      **Auto-probe VS report (if not provided by user in section 1, OR if user-provided path was invalid):**
      - Only attempt if `forge_data_folder` is non-empty and the directory exists (validated above); otherwise skip probe and set `vs_report_available: false`
      - Check for `{forge_data_folder}/feasibility-report-{project_name}.md`
      - If found: "Auto-discovered VS report at `{path}`. Loading for additional context."
      - Store `vs_report_available: true` and `vs_report_path`
      - If not found: `vs_report_available: false` — "Proceeding without VS report — issue detection will rely on skill data only."
      
      ### 3c. Reset RA State File
      
      Create (or overwrite) `{forge_data_folder}/ra-state-{project_name}.md` with a fresh header:
      
      ```markdown
      <!-- RA state for {project_name} — generated {current_date} -->
      ```
      
      This ensures steps 02-04 append to a clean slate and context recovery in step 5 never loads stale findings from a prior run.
      
      On any write failure (read-only mount, disk full, permissions denied): HALT (exit code 4, `halt_reason: "write-failed"`) with the captured error and emit the error envelope. The On-Activation §5 probe should have caught this earlier — if it surfaces here, the filesystem state changed mid-workflow.
      
      ### 4. Load Refinement Rules
      
      Load `{refinementRulesData}` for reference by downstream steps.
      
      Extract: gap detection rules, issue detection rules, improvement detection rules, citation format, and preservation rules.
      
      ### 5. Display Initialization Summary
      
      "**Architecture Refinement Initialized**
      
      | Field | Value |
      |-------|-------|
      | **Architecture Doc** | {architecture_doc} |
      | **VS Report** | {vs_report_path or 'Not provided — issue detection will use skill data only'} |
      | **Skills Loaded** | {skill_count} |
      
      **Skill Inventory:**
      
      | Skill | Language | Tier | Exports |
      |-------|----------|------|---------|
      | {skill_name} | {language} | {confidence_tier} | {exports_documented} |
      
      **Proceeding to gap analysis...**"
      
      ### 6. Auto-Proceed to Next Step
      
      Load, read the full file and then execute `{nextStepFile}`.
      
      
    • issue-detection.md 6.1 KB
      ---
      nextStepFile: 'improvements.md'
      refinementRulesData: '{refinementRulesPath}'
      ---
      
      <!-- Config: communicate in {communication_language}. Append issue-detection findings to the RA state file in {document_output_language}. -->
      
      # Step 3: Issue Detection
      
      ## STEP GOAL:
      
      Find contradictions between what the architecture document claims and what the generated skills reveal about actual API surfaces. Detect language boundary issues not addressed, protocol mismatches assumed away, and missing bridge layers. If a VS feasibility report is available, incorporate RISKY and BLOCKED verdicts as confirmed issues.
      
      ## Rules
      
      - Focus only on contradictions between architecture claims and skill API reality
      - Do not detect gaps (Step 02) or suggest expansions (Step 04)
      - Every issue must cite both the architecture claim and the contradicting skill evidence
      
      ## MANDATORY SEQUENCE
      
      ### 1. Reference Refinement Rules
      
      Use the refinement rules loaded in Step 01 from `{refinementRulesData}`. If not available in context, reload from `{refinementRulesData}`.
      
      Extract: issue classification (API Mismatch, Protocol Contradiction, Language Boundary Ignored, Type Incompatibility) and VS report integration rules.
      
      ### 2. Extract Integration Claims from Architecture
      
      Parse the architecture document for specific claims about how technologies interact.
      
      **Claim types to extract:**
      - **API claims:** "Library X provides/exposes/exports {function/endpoint}"
      - **Protocol claims:** "Library X communicates via {protocol}"
      - **Data flow claims:** "Data flows from X to Y as {format}"
      - **Integration claims:** "X and Y integrate through {mechanism}"
      - **Capability claims:** "Library X handles {capability}"
      
      For each claim, record:
      - The exact text or paraphrase from the architecture
      - The section where it appears
      - The libraries referenced
      
      ### 3. Verify Claims Against Skill API Surfaces
      
      For each extracted claim, verify against the compact API surfaces already collected in Step 02 §4 — the per-skill `{skill_api_surfaces}` summaries (`{exports, protocols, data_formats}`), carried forward as workflow state exactly like `{in_scope_skills}`. Reload a skill's SKILL.md directly only if its summary is unavailable or context has compacted (see Step 02 §4 for the canonical delegate-the-read pattern). Then check:
      
      **API Mismatch check:**
      - Does the claimed API actually exist in the skill's export list?
      - Does the function signature match what the architecture describes?
      - If the architecture describes an API that does not appear in the skill: flag as issue
      
      **Protocol Contradiction check:**
      - Does the skill document the protocol the architecture assumes?
      - If the architecture claims gRPC but the skill shows HTTP-only: flag as issue
      
      **Language Boundary check:**
      - If two libraries are in different languages, does the architecture describe a bridge mechanism?
      - If the architecture assumes direct calls across language boundaries without FFI/IPC: flag as issue
      
      **Type Incompatibility check:**
      - Does the architecture assume type compatibility that the skills contradict?
      - If Library A exports Type X but the architecture claims Library B consumes it, and Library B expects Type Y: flag as issue
      
      ### 4. Incorporate VS Report (If Available)
      
      If `vs_report_available` is true:
      
      **Scope filter (reuse `{out_of_scope_skills}` from Step 02 §2b):** The VS report carries verdicts across the entire skill set, which may exceed this architecture's surface. Before promoting any verdict, check the pair's scope — if a verdict is for an **out-of-scope** pair (either library in `{out_of_scope_skills}`), do not promote it to an issue for this architecture; record it under the informational Out-of-Scope bucket instead. Only **in-scope** pairs' verdicts are promoted by the rules below.
      
      **Load the VS feasibility report and extract verdicts:**
      - **Risky verdicts** (match case-insensitively): Promote to confirmed issues with the VS evidence as additional citation
      - **Blocked verdicts** (match case-insensitively): Promote to critical issues requiring architecture redesign
      - **Plausible verdicts:** Note informatively — Plausible is not an issue by itself. Only flag as a potential issue if the VS rationale text explicitly states "no direct API evidence" or "weak evidence"
      
      **For each VS-sourced issue, include dual citations:**
      - Evidence from the skill content
      - Verdict and rationale from the VS report
      
      If `vs_report_available` is false: Skip this section. Issue detection proceeds with skill data only.
      
      ### 5. Document Each Issue
      
      For each detected issue, cite it in this format:
      
      ```
      **[ISSUE]**: {description}
      
      Architecture states: "{quoted claim from original document}" (Section: {section_name})
      Skill reality: {skill_name} exports: `{actual_api}` — {explanation of contradiction}
      {IF VS report}: VS verdict: {Risky|Blocked} for {pair} — {VS rationale}
      
      Suggestion: {specific correction with API evidence}
      ```
      
      **Severity classification:**
      - **Critical:** Blocked VS verdicts, fundamental language barriers with no bridge
      - **Major:** Risky VS verdicts, protocol mismatches, missing bridge layers
      - **Minor:** Plausible VS verdicts where the VS rationale explicitly states "no direct API evidence" or "weak evidence", minor type differences with easy conversion
      
      ### 6. Report Issues & Store Findings
      
      Report the in-scope issue count with its critical/major/minor breakdown, then list each issue as a row of **# / Libraries / Issue Type / Severity / Summary** followed by its full §5 citation. One signal is not inferable from the counts and must survive regardless of format:
      
      - **Out-of-scope VS verdicts were set aside (from §4):** list them separately for awareness only — they were not counted as issues — and note that re-running with `--scope-skills` pulls any that belong into scope.
      
      Store the **in-scope** issue findings per the Finding Storage rule (refinement rules), under a `<!-- [RA-ISSUES] ... -->` block (its citations carry the architecture claim, skill evidence, VS verdict, severity, and suggestion). Record any out-of-scope VS verdicts under the shared `<!-- [RA-OUT-OF-SCOPE] ... -->` marker so Step 05 leaves them out — informational only.
      
      ### 7. Auto-Proceed to Next Step
      
      Load, read the full file and then execute `{nextStepFile}`.
      
      
    • refinement-rules.md 6.1 KB
      <!-- Static reference loaded by gap-analysis.md, issue-detection.md, and improvements.md. -->
      
      # Architecture Refinement Rules
      
      ## Purpose
      
      Rules for detecting gaps, issues, and improvements in an architecture document using generated skill data as the evidence source.
      
      ---
      
      ## Gap Detection Rules
      
      Gaps are undocumented integration paths — library pairs that have compatible APIs but no architecture description.
      
      ### Detection Method
      
      1. Read the pre-computed unique library pairs from `skill_inventory.pairs` (emitted by the enumerate helper's `--pairs` flag) — do not re-derive them in-context
      2. For each pair, check if both skills export APIs that could connect (compatible types, shared protocols, complementary producer/consumer patterns)
      3. Cross-reference against the architecture document: does the document describe how these two libraries interact?
      4. If compatible APIs exist but NO architecture description exists, this is a **gap**
      
      ### Gap Classification
      
      | Gap Type                     | Description                                                            | Example                                                                              |
      |------------------------------|------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
      | **Missing Integration Path** | Two libraries can connect but the architecture never describes how     | Skill A exports JSON producer, Skill B accepts JSON input, no mention of A-to-B flow |
      | **Undocumented Data Flow**   | Data moves between libraries but the flow is not described             | Architecture mentions both libraries but not their data exchange mechanism           |
      | **Absent Bridge Layer**      | Cross-language or cross-protocol libraries need a bridge not mentioned | Rust library and TypeScript library with no IPC/FFI description                      |
      
      ---
      
      ## Issue Detection Rules
      
      Issues are contradictions between architecture claims and verified API reality from the skills.
      
      ### Detection Method
      
      1. Extract every integration claim from the architecture document (prose co-mention analysis)
      2. For each claim, verify against the actual API surfaces in the skills
      3. Flag contradictions: claimed APIs that do not exist, assumed compatibility that breaks, missing bridge layers
      
      ### Issue Classification
      
      | Issue Type                    | Description                                                    | Example                                                                      |
      |-------------------------------|----------------------------------------------------------------|------------------------------------------------------------------------------|
      | **API Mismatch**              | Architecture describes an API that does not exist in the skill | "Library X exposes a streaming API" but skill shows only batch APIs          |
      | **Protocol Contradiction**    | Architecture assumes a protocol the library does not support   | "Communicates via gRPC" but skill shows HTTP-only exports                    |
      | **Language Boundary Ignored** | Architecture assumes direct calls across language boundaries   | "Calls Rust functions from TypeScript" with no FFI/IPC mechanism described   |
      | **Type Incompatibility**      | Architecture assumes type compatibility that does not hold     | "Passes CRDT documents directly" but types are incompatible across libraries |
      
      ### VS Report Integration
      
      When a VS feasibility report is available:
      - RISKY verdicts become **confirmed issues** with the VS evidence as additional citation
      - BLOCKED verdicts become **critical issues** requiring architecture redesign
      - Plausible verdicts become potential issues **only if** the VS rationale text explicitly states "no direct API evidence" or "weak evidence" — otherwise they are informational only
      
      ---
      
      ## Improvement Detection Rules
      
      Improvements are capability expansions — library features documented in skills but not leveraged in the architecture.
      
      ### Detection Method
      
      1. For each skill, enumerate its full API surface (all exports, types, protocols)
      2. Compare against how the architecture uses that library
      3. Identify capabilities present in the skill but absent from the architecture
      
      ### Improvement Classification
      
      | Improvement Type          | Description                                                             | Example                                                                        |
      |---------------------------|-------------------------------------------------------------------------|--------------------------------------------------------------------------------|
      | **Unused Capability**     | Library has a feature the architecture does not mention                 | "Loro supports document CRDTs but architecture only uses data sync"            |
      | **Cross-Library Synergy** | Two libraries have complementary features not combined in architecture  | "Library A's event system could feed Library B's stream processor"             |
      | **Alternative Pattern**   | Skill documents a better pattern than the one described in architecture | "Skill shows batch API is more efficient than the per-item approach described" |
      
      ---
      
      ## Finding Storage (Steps 02-04)
      
      Each analysis step stores its findings two ways: as workflow state for Step 05, and appended to `{forge_data_folder}/ra-state-{project_name}.md` as a labeled `<!-- [RA-...] ... -->` block holding the **complete formatted findings** — full citation blocks with evidence and suggestions, not just counts — so Step 05 can recover them if context degrades on a long run. The refined document itself is written once, in Step 05; Steps 02-04 never write to it.
      
      ---
      
      ## Preservation Rules
      
      1. **Never delete original content** — only add annotations and subsections
      2. **Follow original section layout** — add refinement subsections within existing sections
      3. **Use callout blocks** for issues: `> [!WARNING]` or `> [!NOTE]` format
      4. **Mark additions clearly** — prefix added subsections with "RA:" or use a refinement marker
      5. **Maintain original heading hierarchy** — refinement subsections are one level deeper than the parent
      
    • report.md 6.3 KB
      ---
      # {outputFile} resolves from the activation-stored {outputFolderPath}
      # variable (set in SKILL.md On Activation §4 from output_folder config +
      # customize override) and {arch_project_name} (resolved in init.md from the
      # architecture doc's frontmatter project_name, else config project_name).
      outputFile: '{outputFolderPath}/refined-architecture-{arch_project_name}.md'
      nextStepFile: 'health-check.md'
      ---
      
      <!-- Config: communicate in {communication_language}. Render the user-facing summary in {document_output_language}. -->
      
      # Step 6: Present Report
      
      ## STEP GOAL:
      
      Present the complete refinement summary to the user. Display counts of gaps filled, issues flagged, and improvements suggested. Provide the output file path and recommend next steps. Offer the user options to review changes in detail or exit. Chains to the shared health check on exit.
      
      ## Rules
      
      - Focus only on presenting the completed refinement — no new analysis
      - Do not discover new gaps, issues, or improvements, and do not modify the refined document
      - Chains to the local health-check step via `{nextStepFile}` after completion — the user-facing summary is not the terminal step
      
      ## MANDATORY SEQUENCE
      
      ### 1. Load Refined Document
      
      Read the `{outputFile}` to have all data available for presentation.
      
      Verify the `## Refinement Summary` section is present. If it is absent, HALT (exit code 8, `halt_reason: "recovery-failed"`): "⚠️ Refinement Summary not found in `{outputFile}`. Step 05 may not have completed successfully. Re-run [RA] from the beginning." In headless, emit the error envelope per SKILL.md "Result Contract (Headless)" with `refined_path: null`.
      
      **Extract metrics from the Refinement Summary section:** Parse `gap_count`, `issue_count`, `improvement_count`, `critical_count`, `major_count`, `minor_count`, `high_count`, `medium_count`, `low_count`, and `skill_count` from the Changes Made table and Evidence Sources table. Use these extracted values in the summary table and next-steps sections below.
      
      ### 2. Display Summary
      
      "**Refine Architecture — Refinement Complete**
      
      ---
      
      | Metric | Count |
      |--------|-------|
      | **Gaps Filled** | {gap_count} |
      | **Issues Flagged** | {issue_count} (Critical: {critical_count}, Major: {major_count}, Minor: {minor_count}) |
      | **Improvements Suggested** | {improvement_count} (High: {high_count}, Medium: {medium_count}, Low: {low_count}) |
      | **Skills Used as Evidence** | {skill_count} |
      
      **Evidence Sources:** (which skills contributed evidence)
      
      {Display the Evidence Sources table from the Refinement Summary section of the document}
      
      ---
      
      **Your refined architecture is at:** `{outputFile}`
      
      The original architecture content is fully preserved. All refinements are clearly marked with `[!NOTE]`, `[!WARNING]`, and `[!TIP]` callout blocks that you can accept, modify, or remove."
      
      ### 3. Present Next Steps
      
      "**Recommended next steps:**
      
      1. **Review the refined document** — accept, modify, or remove individual refinements
      2. **[SS] Stack Skill** — compose-mode activates automatically when SS detects existing individual skills without a codebase; provide this refined architecture doc as the architecture document when prompted
      3. **Re-run [VS] Verify Stack** if you made changes based on issue corrections — to confirm resolution
      
      {IF issues with Critical severity were found:}
      **⚠️ Attention:** {critical_count} critical issue(s) were flagged. These indicate fundamental contradictions between your architecture and the verified API surfaces. Address these before proceeding to stack skill composition."
      
      ### 4. Present Menu
      
      Display: "**[R] Review changes in detail** | **[X] Exit refinement**"
      
      #### Menu Handling Logic:
      
      - **IF R:** Walk through each refinement with its full evidence citation:
        1. First, all gaps with their evidence and proposed integration paths
        2. Then, all issues ordered by severity with architecture claim vs. skill reality
        3. Finally, all improvements ordered by value with untapped capability details
        After completing the walkthrough, redisplay the menu.
      
      - **IF X:** "**Refined architecture saved to:** `{outputFile}`
      
      Re-run **[RA] Refine Architecture** anytime after updating your skills or architecture document.
      
      **Architecture refinement complete.**"
      
        ### Result Contract
      
        Write the result contract per `shared/references/output-contract-schema.md`: the per-run record at `{outputFolderPath}/refine-architecture-result-{timestamp}.json` (reuse the activation-stored `{timestamp}`, resolution to seconds) and a copy at `{outputFolderPath}/refine-architecture-result-latest.json` (stable path for pipeline consumers — copy, not symlink). Include the refined architecture doc path in `outputs`; include `gap_count`, `issue_count`, and `improvement_count` in `summary`. On any write failure: HALT (exit code 4, `halt_reason: "write-failed"`) and emit the error envelope.
      
        When `{headless_mode}` is true, also emit the single-line envelope on **stdout** before chaining to step 7 (matches the SKILL.md "Result Contract (Headless)" shape):
      
        ```
        SKF_REFINE_ARCHITECTURE_RESULT_JSON: {"status":"success","refined_path":"{outputFile}","gap_count":{gap_count},"issue_count":{issue_count},"improvement_count":{improvement_count},"exit_code":0,"halt_reason":null}
        ```
      
        **Post-completion hook (optional).** If `{onCompleteCommand}` is non-empty (resolved at SKILL.md On Activation §4 from `workflow.on_complete`), invoke it after the result contract is finalized:
      
        ```bash
        {onCompleteCommand} --result-path={result_json_path}
        ```
      
        where `{result_json_path}` is the per-run record written above (`{outputFolderPath}/refine-architecture-result-{timestamp}.json`). Log success/failure to `workflow_warnings[]` — never fail the workflow on a hook error. The hook runs after the result contract is finalized so notifiers, indexers, or downstream pipelines (index the refined doc, chain the next workflow) see a complete record. When `{onCompleteCommand}` is empty (bundled default), skip the invocation entirely.
      
        Then load, read the full file, and execute `{nextStepFile}` — the health-check step is the true terminal step of this workflow.
      
      #### EXECUTION RULES:
      
      - This is the exit gate: halt for the user's choice. [R] walks every refinement with its evidence (repeatable — re-shows this menu after each pass); [X] chains to the health check, the true workflow exit. Headless auto-selects [X].
      
      
  • customize.toml 2.3 KB
    # DO NOT EDIT -- overwritten on every update.
    #
    # Workflow customization surface for skf-refine-architecture.
    # Team overrides:     _bmad/custom/skf-refine-architecture.toml (under {project-root})
    # Personal overrides: _bmad/custom/skf-refine-architecture.user.toml (under {project-root})
    
    [workflow]
    
    # --- Configurable below. Overrides merge per BMad structural rules: ---
    #   scalars: override wins • arrays (persistent_facts, activation_steps_*): append
    #   arrays-of-tables with `code`/`id`: replace matching items, append new ones.
    
    # Steps to run before the standard activation (uv probe, config load).
    # Overrides append. Use for org-wide pre-flight checks (auth, network,
    # compliance) that must precede architecture refinement work.
    
    activation_steps_prepend = []
    
    # Steps to run after activation but before the first stage executes.
    # Overrides append. Use for context loads or banner customization that
    # should run once activation completes successfully.
    
    activation_steps_append = []
    
    # Persistent facts the workflow keeps in mind for the whole run
    # (refinement standards, evidence-citation rules, house-style preservation
    # guardrails). Overrides append.
    #
    # Each entry is either:
    #   - a literal sentence, e.g. "Refinements must cite specific API signatures, never speculate."
    #   - a file reference prefixed with `file:`, e.g.
    #     "file:{project-root}/docs/refine-policy.md" (globs supported; file
    #     contents are loaded and treated as facts).
    
    persistent_facts = [
      "file:{project-root}/**/project-context.md",
    ]
    
    # --- Optional asset overrides ---
    #
    # Lift the canonical refinement-rules path so orgs can substitute house-style
    # rules (e.g. add domain-specific gap categories) without forking the skill.
    # Empty string = use the bundled default.
    
    refinement_rules_path = ""
    
    # Override the destination directory for the refined architecture document.
    # Empty = use {output_folder} from config.yaml. Useful for orgs that want
    # refined-architecture artifacts to land under a curated docs tree.
    
    output_folder_path = ""
    
    # Optional post-completion hook. When non-empty, invoked with
    # `--result-path=<path>` after the refined architecture and result JSON are
    # finalized (step 6). Use to index the refined doc, notify, or chain the next
    # workflow. Failures are logged to workflow_warnings[] but never fail the run.
    
    on_complete = ""
    
  • SKILL.md 9.9 KB
    ---
    name: skf-refine-architecture
    description: Improve architecture doc using verified skill data and VS feasibility findings. Use when the user requests to "refine skill architecture" or "improve architecture doc."
    ---
    
    # Refine Architecture
    
    ## Overview
    
    Takes an original architecture document + generated skills + optional VS feasibility report, and produces a refined architecture with gaps filled, issues flagged, and improvements suggested — all backed by specific API evidence from the generated skills. This workflow enhances the original architecture — it never deletes original content, only adds annotations, subsections, and suggestions.
    
    ## Conventions
    
    - Bare paths (e.g. `references/<name>.md`) resolve from the skill root.
    - `references/` holds prompt content carved out of SKILL.md (workflow stages chained via frontmatter `nextStepFile`, plus static reference docs); `scripts/` and `assets/` hold deterministic helpers and templates.
    - `{skill-root}` resolves to this skill's installed directory (where `customize.toml` lives, if present).
    - `{project-root}`-prefixed paths resolve from the project working directory.
    - `{skill-name}` resolves to the skill directory's basename.
    
    ## Role
    
    You are an architecture refinement analyst operating in Ferris Architect mode. You bring expertise in API surface analysis, integration gap detection, and evidence-backed architecture improvement, while the user brings their architecture vision and generated skills. Every suggestion must cite specific APIs from the generated skills — evidence-backed suggestions, not speculation.
    
    ## Workflow Rules
    
    These rules apply to every step in this workflow:
    
    - Never speculate — every gap, issue, or improvement must cite specific APIs, types, or function signatures from the generated skills
    - Only load one step file at a time — never preload future steps
    - If any instruction references a subprocess or tool you lack, achieve the outcome in your main context thread
    - Always communicate in `{communication_language}`
    - At any interactive prompt, the inputs `cancel`, `exit`, `[X]`, `q`, or `:q` exit cleanly with exit code 6 (`halt_reason: "user-cancelled"`)
    - If `{headless_mode}` is true, auto-proceed through confirmation gates with their default action and log each auto-decision
    
    ## Stages
    
    | # | Step | File | Auto-proceed |
    |---|------|------|--------------|
    | 1 | Initialize & Load Inputs | references/init.md | No (confirm) |
    | 2 | Gap Analysis | references/gap-analysis.md | Yes |
    | 3 | Issue Detection | references/issue-detection.md | Yes |
    | 4 | Improvements | references/improvements.md | Yes |
    | 5 | Compile Refined Architecture | references/compile.md | No (review) |
    | 6 | Report | references/report.md | Yes |
    | 7 | Workflow Health Check | references/health-check.md | Yes |
    
    ## Invocation Contract
    
    | Aspect | Detail |
    |--------|--------|
    | **Inputs** | architecture_doc_path [required], vs_report_path [optional] |
    | **Flags** | `--headless` / `-H` (auto-resolve all gates); `--architecture-doc <path>` (skip step 1 prompt for the required input); `--vs-report-path <path>` (skip step 1 prompt for the optional VS report); `--scope-skills <names>` (comma-separated in-scope skill names; overrides scope derivation in gap analysis) |
    | **Gates** | step 1: Input Gate [use args] | step 5: Review Gate [C] continue / [X] cancel | step 6: Exit menu [R] review / [X] exit |
    | **Outputs** | `refined-architecture-{arch_project_name}.md` at `{outputFolderPath}` (`{arch_project_name}` = the architecture doc's frontmatter `project_name`, else config `project_name` — resolved in init.md), plus `refine-architecture-result-{timestamp}.json` and `refine-architecture-result-latest.json` |
    | **Headless** | All gates auto-resolve with default action when `{headless_mode}` is true. Per-flag args (`--architecture-doc`, `--vs-report-path`) consumed at the gates that would otherwise prompt. |
    | **Exit codes** | See "Exit Codes" below |
    
    ## Exit Codes
    
    Every HARD HALT in this workflow exits with a stable code so headless automators can branch on the failure class without grepping message text:
    
    | Code | Meaning              | Raised by                                                                                    |
    | ---- | -------------------- | -------------------------------------------------------------------------------------------- |
    | 0    | success              | step 7 (terminal)                                                                           |
    | 2    | input-missing / input-invalid | step 1 §1 (headless missing `architecture-doc` arg, or invalid path) → `input-missing`; non-existent file → `input-invalid` |
    | 3    | resolution-failure   | On-Activation §5 (`output_folder` or `forge_data_folder` unconfigured) |
    | 4    | write-failure        | On-Activation §5 pre-flight write probe; step 1 §3c (RA state file write failed); step 5 §6 (refined-architecture write failed); step 6 §3 (result-contract write failed) |
    | 5    | state-conflict       | step 1 §3 (no skills found — refinement requires ≥1 skill) |
    | 6    | user-cancelled       | step 1 §1 prompt cancelled; any prompt that accepted `cancel`/`exit`/`:q`; step 5 review gate `[X]` |
    | 7    | inventory-unreliable | step 1 §2 (>20% skill-inventory warnings exceed budget) |
    | 8    | recovery-failed      | step 5 §1 (durability state insufficient to reconstruct Step 02-04 findings); step 6 §1 (`## Refinement Summary` absent from the compiled document) |
    
    ## Result Contract (Headless)
    
    When `{headless_mode}` is true, step 6 emits a single-line JSON envelope on **stdout** before chaining to step 7, and every HARD HALT emits the same envelope shape on **stderr** with `status: "error"`:
    
    ```
    SKF_REFINE_ARCHITECTURE_RESULT_JSON: {"status":"success|error","refined_path":"…|null","gap_count":0,"issue_count":0,"improvement_count":0,"exit_code":0,"halt_reason":null}
    ```
    
    `status` is `"success"` on the terminal happy path, `"error"` on any HALT. `halt_reason` is one of: `null` (success), `"input-missing"`, `"input-invalid"`, `"insufficient-skills"`, `"output-folder-unconfigured"`, `"forge-folder-unconfigured"`, `"inventory-unreliable"`, `"write-failed"`, `"recovery-failed"`, `"user-cancelled"`. `exit_code` matches the table above.
    
    ## On Activation
    
    1. Load config from `{project-root}/_bmad/skf/config.yaml` and resolve:
       - `project_name`, `user_name`, `communication_language`, `document_output_language`
       - `skills_output_folder`, `forge_data_folder`, `output_folder`, `sidecar_path`
    
    2. **Compute run-scoped variables:**
       - `timestamp` ← UTC `YYYYMMDD-HHmmss` captured at activation time. Fixed for the entire workflow run; report.md reuses this when writing the result contract.
    
    3. **Resolve `{headless_mode}`**: true if `--headless` or `-H` was passed as an argument, or if `headless_mode: true` in `{sidecar_path}/preferences.yaml`. Default: false.
    
    4. **Resolve workflow customization.** Run:
    
       ```bash
       python3 {project-root}/_bmad/scripts/resolve_customization.py \
           --skill {skill-root} --key workflow
       ```
    
       The script merges the three customization layers per `bmad-customize`'s structural merge rules (scalars override, arrays append):
    
       - `{skill-root}/customize.toml` — bundled defaults
       - `_bmad/custom/<skill-name>.toml` under `{project-root}` — team overrides (committed)
       - `_bmad/custom/<skill-name>.user.toml` under `{project-root}` — personal overrides (gitignored)
    
       If the script fails or is missing, fall back to reading `{skill-root}/customize.toml` directly — the bundled defaults are an empty string for each path scalar.
    
       Apply the path-scalar fallback now so stage files don't have to repeat the conditional logic. For each scalar, if the merged value is empty or absent, use the bundled default:
    
       - `{refinementRulesPath}` ← `workflow.refinement_rules_path` if non-empty, else `references/refinement-rules.md`
       - `{outputFolderPath}` ← `workflow.output_folder_path` if non-empty, else `{output_folder}`
       - `{onCompleteCommand}` ← `workflow.on_complete` if non-empty, else empty (no-op — report.md skips the hook invocation entirely)
    
       Stash all three as workflow-context variables. Stage files reference them directly — no conditional at the usage site.
    
       Also apply the array surfaces (not silent no-ops): run `workflow.activation_steps_prepend` now, treat `workflow.persistent_facts` as standing context for the run (`file:`-prefixed entries load their file/glob contents as facts), then run `workflow.activation_steps_append` after activation.
    
    5. **Pre-flight config + write probe.** Assert both output paths are configured, then probe writability — order matters: an empty path makes `mkdir -p ""` fail, which would misreport a *missing config* (exit 3) as a *write failure* (exit 4) and collapse the distinction the Result Contract draws.
    
       **Config-completeness (exit 3).** If `{outputFolderPath}` is empty: HALT (exit code 3, `halt_reason: "output-folder-unconfigured"`) — "`output_folder` is not configured in config.yaml. Add an `output_folder` path and re-run [RA]." If `{forge_data_folder}` is empty: HALT (exit code 3, `halt_reason: "forge-folder-unconfigured"`) — "`forge_data_folder` is not configured in config.yaml. Add a `forge_data_folder` path and re-run [RA]."
    
       **Write probe (exit 4).** With both paths now non-empty, verify each is writable — a read-only mount, full disk, or permissions-denied path otherwise only surfaces at init.md §3c's RA state file write, by which point the user has already gone through input prompts:
    
       ```bash
       for dir in "{outputFolderPath}" "{forge_data_folder}"; do
         mkdir -p "$dir" && \
           printf 'probe' > "$dir/.skf-write-probe" && \
           rm "$dir/.skf-write-probe"
       done
       ```
    
       On any non-zero exit: HALT (exit code 4, `halt_reason: "write-failed"`). In headless mode, every HALT above emits the error envelope per **Result Contract (Headless)** with `refined_path: null`.
    
    6. Load, read the full file, and then execute `references/init.md` to begin the workflow.
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related