---
# model: haiku
# contextOutput: '{output_folder}/_validation_temp/context.yaml'
# grepPatterns: '../data/grep-patterns-srs.yaml'
---

# Step V-01: Discovery — Xác định scope và tạo report skeleton

---

## 1. Xác định SRS files cần validate

Hỏi user:

```
Bạn muốn validate SRS nào?

1. **Single file** — Validate 1 file SRS cụ thể
2. **Batch** — Validate nhiều files SRS (chọn danh sách)
3. **Full** — Validate toàn bộ SRS trong folder output

Chọn (1/2/3):
```

Chờ user chọn.

---

## 2. Scan files

Dựa vào lựa chọn:

### Option 1 — Single file
- User cung cấp file path hoặc FR number
- Đọc file, xác nhận file tồn tại và có nội dung

### Option 2 — Batch
- Liệt kê tất cả SRS files trong `{output_folder}/`
- User chọn files cần validate
- Đọc danh sách files đã chọn

### Option 3 — Full
- Scan toàn bộ `{output_folder}/05-srs*.md`
- Liệt kê cho user confirm

---

## 3. Load Project Context (auto — không cần user input)

Tự động load project context từ VSAF artifacts:

1. Read `graphify-out/graph.json` (nếu tồn tại) → extract document nodes, feature nodes, service nodes
2. For each SRS file in scope:
   - Determine feature name from file path
   - Locate upstream docs trong `.vsaf/docs/features/{feature-name}/`
3. Cross-validation sources (auto-load):
   - PRD: `.vsaf/docs/features/{feature-name}/02-prd.md`
   - Architecture: `.vsaf/docs/features/{feature-name}/03-adr.md`
   - Epics: `.vsaf/docs/features/{feature-name}/04-epics.md` (nếu tồn tại)
   - BRD: tìm trong `.vsaf/docs/` (optional — chỉ khi project có BRD)
   - System SRS: tìm trong `.vsaf/docs/` (optional)

**Token efficiency rule:** PRD và ADR trong VSAF thường nhỏ (<500 lines). Đọc toàn bộ file thay vì dùng line-range optimization.

---

## 3b. Build SRS Section Index and UC Cache

After loading KG context, build two caches to eliminate redundant reads in parallel validation steps.

### 3b-1. SRS Section Index

Load `../data/grep-patterns-srs.yaml` → get `srs_structure` patterns.

For each SRS file in scope:
- Run Grep `^## ` on SRS file, output_mode="content", -n=true → extract all Level-2 section headers with line numbers
- Build `section_index`: list of `{heading, start_line, end_line}` for each `##` header
- Compute `end_line` for each heading = next heading's `start_line - 1` (or file total lines for last section)

### 3b-2. UC Cache

For each SRS file:
- Run Grep `^### .*UC-` with -n=true → extract all UC headers and line numbers
- For each UC found, record:
  - `id`: UC identifier (e.g., UC-CA-01)
  - `title`: UC title text  
  - `start_line`: line of UC header
  - `end_line`: start_line of next UC (or +80 as estimate)
  - `has_gherkin`: run Grep `Given.*When.*Then` within UC line range → true/false
- Build `uc_cache`: list of all UCs across all SRS files in scope

### 3b-3. Extract Glossary Dimension Items

To avoid each parallel agent loading the full glossary:
- From the glossary already loaded in workflow initialization, extract item IDs per dimension:
  - completeness_items: [has_overview, has_use_case_summary, has_glossary, ...]
  - consistency_items: [uc_id_pattern, screen_id_pattern, ...]
  - quality_items: [no_ambiguous_language, acceptance_criteria_format, ...]
  - (etc. for each dimension)

### 3b-4. Write context.yaml

Create directory `{output_folder}/_validation_temp/` if it does not exist.

Write `{output_folder}/_validation_temp/context.yaml`:

```yaml
# SRS Validation session context — auto-generated by step-v-01
# DO NOT EDIT manually
validation_date: "{date}"
scope: "{single|batch|full}"
report_path: "{report_output_path}"
silent_mode: {false}   # set true if --silent invocation arg

# SRS files in scope
srs_files:
  - path: "{srs_file_path}"
    fr_id: "{FR_ID}"
    section_index:    # from Grep ^## with computed end_line
      - heading: "1. Mô tả chung"
        start_line: 39
        end_line: 134      # next heading start_line - 1
      - heading: "2. Đặc tả Use Cases"
        start_line: 135
        end_line: 1318
      # ... all ## headings with computed end_line (last section end_line = total file lines)
    uc_cache:         # from Grep ^### UC-
      - id: "UC-CA-01"
        title: "Đăng ký tài khoản chủ động"
        start_line: 120
        end_line: 200
        has_gherkin: true
      # ... etc

# Project context (VSAF convention)
upstream:
  prd_path: ".vsaf/docs/features/{feature-name}/02-prd.md"
  adr_path: ".vsaf/docs/features/{feature-name}/03-adr.md"
  epics_path: ".vsaf/docs/features/{feature-name}/04-epics.md"
  brd_path: null  # set if project has BRD
  graph_json: "graphify-out/graph.json"  # set if graphify index exists

# Glossary item IDs per dimension (pre-extracted for agent efficiency)
dimension_items:
  business_alignment: []
  completeness: [has_overview, has_use_case_summary, has_glossary, has_references, has_uc_screens, has_uc_sequence, has_uc_flow_table, has_erd, has_error_codes, has_impact, has_business_rules, has_nfrs, has_dependencies, has_state_diagrams, has_traceability, has_edge_cases, has_acceptance_criteria]
  consistency: []
  quality: [no_ambiguous_language, acceptance_criteria_format, no_duplicate_requirements, clear_scope, flow_step_numbering, diagram_syntax_valid]
  system_nfr: []
  delivery_readiness: []
  risk_analysis: []
  user_impact: []
```

**Token efficiency note:** context.yaml (~100-150 lines) replaces 8+ separate KG file reads across parallel agents. Each agent reads context.yaml once instead of re-loading project artifacts independently.

**Derived-from traceability rule (CRITICAL):**
SRS is a **derived document** — every requirement MUST trace back to PRD, BRD, or Architecture. If SRS contains requirements not in any upstream source, flag as:
- **CRITICAL** if SRS invents new functional requirements not in PRD/BRD
- **HIGH** if SRS adds business rules not traceable to BRD
- **MEDIUM** if SRS adds NFRs/constraints beyond Architecture specs

Upstream chain: `BRD → PRD → SRS`, `Architecture → SRS`

---

## 3c. Regression Check — Load Previous Reports

Scan `.vsaf/docs/features/{feature-name}/05-srs-validation-report*.md` for existing reports.

If previous reports exist:
1. Find the most recent report (by date in filename, excluding the report being created now)
2. Read its frontmatter to get `overall_score`, `overall_status`, `files_reviewed`
3. Read its "Critical & High Findings" section (section 4) — extract finding IDs
4. Write to context.yaml:

```yaml
regression:
  previous_report: "05-srs-validation-report-2026-04-06.md"
  previous_score: 72.3
  previous_status: WARN
  previous_critical_high_ids:
    - {id: C-001, dimension: consistency, summary: "service boundary violation"}
    - {id: DR-002, dimension: delivery, summary: "API specs missing"}
```

If no previous reports exist:
```yaml
regression:
  previous_report: null
  note: "First validation run — no regression baseline"
```

---

## 4. Tạo report skeleton

Tạo file output: `.vsaf/docs/features/{feature-name}/05-srs-validation-report.md`

Viết frontmatter:

```yaml
---
type: srs-validation-report
date: {date}
validator: BA Validate SRS Skill
scope: {scope}
files_reviewed:
  - {list of files}
overall_score: TBD
overall_status: TBD
stepsCompleted:
  - step-v-01-discovery
---
```

Viết section headers (chưa có nội dung):

```markdown
## 1. Executive Summary

_(Sẽ được điền ở Step V-10)_

## 2. Overall Score & Confidence

_(Sẽ được điền ở Step V-10)_

## 3. Heatmap — Score by Dimension

_(Sẽ được điền ở Step V-10)_

## 4. Critical & High Findings

_(Sẽ được điền ở Steps V-02 → V-09)_

## 5. Medium & Low Findings

_(Sẽ được điền ở Steps V-02 → V-09)_

## 6. Top Missing Areas

_(Sẽ được điền ở Step V-10)_

## 7. Unresolved Questions

_(Sẽ được điền ở Steps V-02 → V-09)_

## 8. Action Plan

_(Sẽ được điền ở Step V-10)_

## 9. Appendix: Full Scoring Matrix

_(Sẽ được điền ở Step V-10)_
```

---

## 5. Confirm & Route

Xuất cho user:

```
Scope: {scope}
Files: {count} file(s)
  - {file list}
Cross-validate: PRD=auto, ADR=auto, Epics=auto (if exists), BRD=auto (if exists)
Report: .vsaf/docs/features/{feature-name}/05-srs-validation-report.md
Context: {output_folder}/_validation_temp/context.yaml ✓
UC Cache: {uc_count} UCs indexed ✓
Graph: {graph_json status}

[C] Continue — Bắt đầu validate Business Alignment (Step V-02)
[X] Cancel — Dừng lại
```

**Chờ user chọn.**

Khi user chọn **C** và `{parallel_mode}` là `true`: Hiển thị "Parallel validation mode: launching Round 1..." rồi follow **PARALLEL EXECUTION ROUNDS → Round 1** trong workflow.md
Khi user chọn **C** và `{parallel_mode}` là `false`: đọc fully và follow `./step-v-02-business-alignment.md` (sequential fallback)
