---

# Stage identity per spec Section 6.1
stage: 3
stage_id: "03"
title: "Generate"
workflow: generate-guidelines
status: EXPERIMENTAL
estimated_tokens: 5000

# Context specification
context:
  static:
    persona: "technical writer synthesizing findings into guidelines"
    purpose: "Synthesize findings, resolve conflicts, and generate guideline files"
  dynamic:
    - key: tech_stack
      source: state
    - key: update_mode
      source: state
    - key: document_findings
      source: state
    - key: code_findings
      source: state

# Pre-validation checks
pre_validation:
  - check: stage_02_completed
    condition: "state.generate-guidelines.current_stage == '02-analyze'"
    message: "Stage 02 (Analyze) must be completed first"
    recovery: "civyk-hatch generate-guidelines --stage=2"
  - check: findings_exist
    condition: "document-findings.md and code-findings.md exist"
    message: "Analysis findings must exist from stage 02"
    recovery: "civyk-hatch generate-guidelines --stage=2"

# Execution flow with step types
execution_flow:
  - step: 1
    type: action
    name: load_findings
    instruction: "Load document-findings.md and code-findings.md"
    output_variable: findings
  - step: 2
    type: action
    name: merge_findings
    instruction: "Merge findings by category and identify conflicts"
    output_variable: merged_findings
  - step: 3
    type: input_loop
    id: resolve_conflicts
    instruction: "For each conflict, ask user for resolution"
    prompt: "Conflict: [topic] - Doc says [X], Code shows [Y]. Resolution: [A] Follow doc | [B] Follow code | [C] Other"
    blocking: true
  - step: 4
    type: action
    name: apply_severity
    instruction: "Apply RFC 2119 severity based on source and consensus"
    output_variable: severity_applied
  - step: 5
    type: action
    name: generate_content
    instruction: "Generate guideline content in chunks (4 chunks required)"
    output_variable: guideline_content
  - step: 6
    type: action
    name: apply_update_mode
    instruction: "Apply update mode (ADD, REPLACE, FULL_REGEN, NEW)"
    output_variable: update_applied
  - step: 7
    type: action
    name: write_guideline
    instruction: "Write guideline file in 4 chunks to prevent token limit issues"
    output_variable: guideline_file
  - step: 8
    type: action
    name: generate_report
    instruction: "Generate analysis report with summary and decisions"
    output_variable: analysis_report

# Guardrails
guardrails:
  enforcement: active
  allowed_tools:
    - civyk-repoix
    - Read
    - Write
    - Edit
    - Grep
    - Glob
    - Bash
  forbidden_actions:
    - "Include code examples in guidelines"
    - "Assume conflict resolutions without user input"
    - "Write entire guideline in single chunk"
  file_restrictions:
    allowed_paths:
      - ".guidelines/**"
      - ".guidelines-analysis/**"
    forbidden_paths:
      - ".env"
      - "**/*.key"
  read_only: false

# Post-validation checks
post_validation:
  - check: conflicts_resolved
    description: "All conflicts were resolved with user input"
    severity: error
  - check: guideline_written
    description: "Guideline file was written in chunks"
    severity: error
  - check: report_generated
    description: "Analysis report was generated"
    severity: warning

# Output specification
output:
  artifacts:
    - type: guideline
      path: ".guidelines/{stack}-guidelines.md"
      description: "Corporate guidelines document"
    - type: report
      path: ".guidelines-analysis/{stack}-analysis-report.md"
      description: "Analysis report with decisions"

# Next stage
next:
  stage: 4
  stage_id: "04"
  command: "civyk-hatch generate-guidelines --stage=4"
  is_terminal: false
version: 1.0.0
---

{{include:verification-rules.md}}

{{include:ai-cache-enforcement.md}}

# Stage 3: Generate

## Purpose

Synthesize findings, resolve conflicts, and generate guideline files.

---

## Step 0: Load Base Guideline Templates

Before generating guidelines, check for existing base templates in the `scripts/python/civyk_hatch/assets/guidelines/base/` directory (e.g., `python-base.md`, `nodejs-base.md`, `java-base.md`, `dotnet-base.md`, `reactjs-base.md`). Use these as structural foundations when available for the detected tech stack.

```bash
# Check for base template matching the detected tech stack
base_template="scripts/python/civyk_hatch/assets/guidelines/base/${tech_stack}-base.md"
```

**IF base template exists**: Read it and use its section structure as a scaffold for the generated guideline. Merge findings into the template's structure rather than starting from scratch.

**IF no base template exists**: Proceed with the default section structure defined in Step 4.

---

## Step 1: Load Findings (Technical Writer Persona)

**Switch to Technical Writer & Synthesizer mindset.**

Load findings from analysis stage:

- Read `.guidelines-analysis/document-findings.md` (Phase 1 output)
- Read `.guidelines-analysis/code-findings.md` (Phase 2 output)

---

## Step 2: Merge and Detect Conflicts

**Merge findings by category:**

- Combine document principles + code patterns
- Organize by guideline template sections
- Identify alignments (doc + code agree) and conflicts (doc vs code disagree)

**[STOP: USER_INPUT_REQUIRED]**

For each conflict, ask user:

```text
Conflict: [topic] - Doc says [X], Code shows [Y]
Resolution: [A] Follow doc | [B] Follow code | [C] Other
```

Wait for ALL conflicts to be resolved. NEVER assume resolutions.

---

## Step 3: Apply RFC 2119 Severity

Based on source and consensus:

- **MUST**: Security requirements, compliance mandates, ALL (3/3) code consensus
- **SHOULD**: Best practices, MOST (2/3) code consensus, recommendations
- **MAY/OPTIONAL**: Nice-to-have, SOME (1/3) code patterns
- **NEVER**: Banned libraries, anti-patterns, security violations

---

## Step 4: Generate Guideline Content

For each section, combine relevant principles from documents + code:

- Write in principle-based format (NO CODE EXAMPLES)
- Include rationale for non-obvious requirements
- Use RFC 2119 keywords consistently

**Guideline sections:**

1. Scaffolding
2. Package Registry
3. Mandatory Libraries
4. Banned Libraries
5. Architecture
6. Security
7. Coding Standards
8. Dependency Management
9. Testing
10. Build & Deployment
11. Observability
12. Non-Compliance

---

## Step 5: Apply Update Mode

**IF UPDATE_MODE = ADD:**

- Read existing guideline file
- Append new principles to appropriate sections
- Increment version (MINOR bump)

**IF UPDATE_MODE = REPLACE:**

- Read existing guideline file
- Replace only selected sections
- Keep other sections unchanged
- Increment version (MINOR or MAJOR)

**IF UPDATE_MODE = FULL_REGEN:**

- Create backup: `.guidelines/{stack}-guidelines-vX.Y.Z.md.bak`
- Generate completely new file
- Increment version (MAJOR bump)

**IF UPDATE_MODE = NEW:**

- Backup existing file with version suffix
- Create new guideline file
- Version starts at 1.0.0 or next MAJOR

---

## Step 6: Write Guideline File

**File path**: `.guidelines/{stack}-guidelines.md`

**[!] MANDATORY CHUNKING REQUIREMENT**

The guideline file MUST be written in 4 chunks to prevent token limit issues.

**Chunk 1** - Initial Write:
Use `Write` tool to create file with:

- Header (version, tech stack, auto-detected from)
- Scaffolding section
- Package Registry section
- Mandatory Libraries section

**Chunk 2** - Append:
Use the `Write` tool to create new files, or the `Edit` tool to make targeted string replacements in existing files. To append content, use the `Edit` tool by matching the last line of the existing file and replacing it with that line plus the new content:

- Banned Libraries section
- Architecture section
- Security section

**Chunk 3** - Append:
Use the same approach (Edit tool with targeted string replacement to add to end of file):

- Coding Standards section
- Dependency Management section
- Testing section

**Chunk 4** - Append:
Use the same approach (Edit tool with targeted string replacement to add to end of file):

- Build & Deployment section
- Observability section
- Non-Compliance section

**After each chunk**, display progress:

```text
[ok] Chunk X/4 complete: {sections written}
```

**Structure:**

```markdown
# {Language} Corporate Guidelines

**Tech Stack**: {Language, Frameworks, Use Cases}
**Auto-detected from**: {File patterns}
**Version**: X.Y.Z

---

## Scaffolding

**MUST**:
- {Principle from docs or code}

**NEVER**:
- {Prohibited pattern}

**Rationale**: {Why this matters}

---

## Package Registry

**MUST**:
- Configure package manager with corporate repository

**Registry URL**: {ARTIFACTORY_URL}

**Library Validation Rules**:
- Standard/Built-in: No validation needed
- External/Third-Party: Check Artifactory before use
- Corporate Internal: Use approved versions only

---

[... continue for all sections ...]

---

## Non-Compliance

If corporate library unavailable or causes blocking issue:

1. Document violation in `.guidelines-todo.md` with justification
2. Create ticket to resolve (target: next sprint)
3. Proceed with alternative, mark with comment for tracking
```

---

## Step 7: Generate Analysis Report

**File path**: `.guidelines-analysis/{stack}-analysis-report.md`

**Contents:**

- Summary: Sources analyzed, principles extracted, conflicts resolved
- Document analysis findings
- Code analysis findings
- Synthesis decisions and user resolutions
- Version history and changes made

---

## Output

```text

[ok] Generation complete
  - Guideline file: .guidelines/{{stack}}-guidelines.md
  - Version: {{version}}
  - Principles: {{count}} ({{must}} MUST, {{should}} SHOULD, {{never}} NEVER, {{may}} MAY)
  - Analysis report: .guidelines-analysis/{{stack}}-analysis-report.md
```

---

## NEXT

```bash
civyk-hatch generate-guidelines --stage=4
```
