# LAPORAN AUDIT MENYELURUH
## Mekanisme Content Block & Seluruh Jalur Analisis Kitab

**Tanggal audit:** 2026-10-29
**Sifat audit:** READ-ONLY — tidak ada perubahan kode, database, konfigurasi, atau data. Tidak ada migrasi dijalankan. Tidak ada proses analisis yang menulis data.
**Metode:** Penelusuran alur pemanggilan (call flow) dari UI → action → service → repository → tabel, sampai penyimpanan hasil. Setiap klaim diberi bukti `file:baris`.

**Legenda bukti:**
- **[TERBUKTI]** — dibaca langsung di kode, dengan rujukan baris.
- **[ASUMSI]** — kesimpulan yang belum diverifikasi pada data produksi (perlu uji terpisah).

---

# A. ARSITEKTUR SAAT INI & ALUR PEMBENTUKAN CONTENT BLOCK

## A.1 Hierarki data (empat lapis, bukan tiga)

```
books (KITAB)
  └── chapters (BAB)
        └── sections (SUBBAB — OPSIONAL, manual)
              └── content_blocks (CONTENT BLOCK — hasil parsing deterministik)
```

**[TERBUKTI]** [`database/migration_content_blocks.sql:4-21`](database/migration_content_blocks.sql:4) menyatakan eksplisit: Content Block adalah struktur **internal** sumber Shamela, **bukan** pengganti BAB/SUBBAB. Tabel bersifat **additive** dan teks Arab disimpan **verbatim**.

Kolom kunci [`migration_content_blocks.sql:31-53`](database/migration_content_blocks.sql:31):
`book_id`, `chapter_id`, `section_id` (NULLABLE), `block_type`, `marker`, `title`, `text_arab` (LONGTEXT), `page_start`, `page_end`, `sort_order`.

**Arti `section_id`:**
- `section_id IS NULL` → blok milik **BAB langsung** (BAB tanpa SUBBAB asli, atau teks wadah BAB).
- `section_id = ID` → blok milik **SUBBAB** tersebut.

**[TERBUKTI]** Keputusan ini didokumentasikan di [`ContentBlockService::parse()`](app/Services/ContentBlockService.php:264-274) dan di laporan lama [`LAPORAN_AUDIT_CONTENT_BLOCK.md:43-58`](database/LAPORAN_AUDIT_CONTENT_BLOCK.md:43) (RM-4).

## A.2 Rantai pembentukan Content Block

```
admin/views/content-blocks/index.php  (4 form POST, masing-masing CSRF)
        │
        ▼
admin/content-blocks/action.php
        │  validasi: POST + CSRF + whitelist scope + rantai relasi BAB/SUBBAB
        ▼
ContentBlockService::generateByScope($scope, $bookId, $chapterId, $sectionId)
        │  [ContentBlockService.php:408]
        ▼
ContentBlockService::generateUnit()  → per unit terpisah
        │  [ContentBlockService.php:619]
        ▼
ContentBlockService::parse($chapterId, $sectionId, $replace)
        │  [ContentBlockService.php:134]
        ├── collectSourceTexts()  → section_texts (SUMBER KEBENARAN)
        │      [ContentBlockService.php:1243]
        ├── ContentBlockParserService::parse($teksArab, $pageStart)
        │      [ContentBlockParserService.php:144]
        └── ContentBlockRepository::createMany($blocks)
               [ContentBlockRepository.php:240]
```

**[TERBUKTI]** Sumber teks Content Block adalah **`section_texts`**, bukan `bab_pages` dan bukan teks AI. Lihat [`ContentBlockService::collectSourceTexts()`](app/Services/ContentBlockService.php:1243-1303) yang memanggil `SectionTextRepository::bySection()`.

## A.3 Lima cakupan generate (bukan empat)

**[TERBUKTI]** [`ContentBlockService::SCOPES`](app/Services/ContentBlockService.php:63) dan [`action.php:18-25`](admin/content-blocks/action.php:18):

| Scope | Unit yang diproses | `section_id` tersimpan |
|---|---|---|
| `bab_direct` | Satu BAB, hanya teks langsung BAB | `NULL` |
| `all_bab_direct` | Semua BAB dalam kitab, hanya teks langsung | `NULL` |
| `subbab` | Satu SUBBAB terpilih | `ID SUBBAB` |
| `all_subbab` | Semua SUBBAB dalam kitab | `ID SUBBAB` |
| `all_content` | Semua teks langsung BAB + semua SUBBAB | campuran |

**Catatan:** UI [`admin/views/content-blocks/index.php`](admin/views/content-blocks/index.php) hanya menampilkan 4 tombol generate (bab_direct, subbab, all_subbab, all_content). `all_bab_direct` ada di service/action tetapi tidak diekspos sebagai tombol. **[TERBUKTI]** dari daftar form di view (baris 1-412) vs konstanta `SCOPES`.

## A.4 Aturan parser Content Block (deterministik, tanpa AI)

**[TERBUKTI]** [`ContentBlockParserService::parse()`](app/Services/ContentBlockParserService.php:144-454). Urutan evaluasi per baris — aturan pertama yang cocok menang:

| # | Aturan | Baris | Efek |
|---|---|---|---|
| 1 | Baris kosong | [:233](app/Services/ContentBlockParserService.php:233) | Flush buffer → blok baru. **Pengecualian:** tidak flush bila tepat sebelum page marker atau sedang `continuation`. |
| 2 | `---` pemisah footnote | [:255](app/Services/ContentBlockParserService.php:255) | Flush; masuk mode footnote **hanya bila** baris berikutnya dimulai angka Arab-Indik. |
| 3 | Baris hiasan (`ــ`, `***`) | [:271](app/Services/ContentBlockParserService.php:271) | Flush; **tidak disimpan**. |
| 4 | Page marker (`ص32`, `ج1 ص255`) | [:280](app/Services/ContentBlockParserService.php:280) | Hanya update `currentPage`; **tidak memecah blok**. |
| 5 | Running header `[باب الصلاة]` | [:312](app/Services/ContentBlockParserService.php:312) | Dibuang (kecuali isi kurung = marker, mis. `[مدخل]`). |
| 5b | Running header polos setelah page marker | [:333](app/Services/ContentBlockParserService.php:333) | Dibuang bila sama dengan header page marker. |
| 6 | Marker struktur di awal baris | [:347](app/Services/ContentBlockParserService.php:347) | Flush; blok baru dengan `block_type`/`marker`/`title`. Heading langsung di-flush. |
| 7 | Baris daftar (`١- ...`) | [:371](app/Services/ContentBlockParserService.php:371) | Blok `list`. |
| 8 | Baris footnote (mode aktif) | [:403](app/Services/ContentBlockParserService.php:403) | Blok `footnote`. |
| 9 | Teks biasa | [:426](app/Services/ContentBlockParserService.php:426) | Blok `paragraph`. |

**Pemetaan marker → block_type** [`MARKER_MAP`](app/Services/ContentBlockParserService.php:66-81):
```
مهمات → muhimmah_plural    مهمة → muhimmah     مبحث → mabhath
مسألة/مسالة → masalah      تتمة → tatimmah     خاتمة → khatimah
تنبيه → tanbih             فائدة → faidah      فرع → far
فصل/مدخل/مقدمة/باب → heading
```

**Penting:** `title` **hanya** diisi untuk `heading`; untuk `tanbih`, `far`, `masalah`, dll. `title = NULL` — ini **disengaja** ([`detectStructuralMarker()`](app/Services/ContentBlockParserService.php:733-736)).

## A.5 Parser Struktur Kitab (BERBEDA dari parser Content Block)

Ada **dua parser berbeda** yang sering dikacaukan:

| Aspek | `ContentBlockParserService` | `KitabStructureParser` |
|---|---|---|
| Tujuan | Memecah teks → blok konten | Menentukan struktur BAB/SUBBAB |
| Input | `section_texts` per unit | **Teks GLOBAL** semua batch |
| Output | `content_blocks` | `kitab_struktur_drafts` |
| Marker | 14 tipe blok | 16 tipe bagian (kitab/bab/fasal/far/...) |
| Level | Tidak ada hierarki | `level` = BAB (kitab) / SUBBAB (lainnya) |
| Parent | Tidak ada | `parent_index` via `assignParents()` |

**[TERBUKTI]** [`KitabStructureParser::parse()`](app/Services/KitabStructureParser.php:83-208) bekerja pada teks global hasil `KitabTextBatchRepository::fullText()` (gabungan semua batch dengan `"\n\n"`). Batas batch **tidak** memotong struktur.

**[TERBUKTI]** Aturan parent [`assignParents()`](app/Services/KitabStructureParser.php:831-880) **identik** dengan [`KitabStructureService::computeParentIndexes()`](app/Services/KitabStructureService.php:895-952) — logika terduplikasi di dua tempat.

## A.6 Alur apply struktur → sections + section_texts

```
kitab_struktur_drafts (approved)
        │
        ▼
KitabStructureService::applyApproved($bookId)
        │  [KitabStructureService.php:1193]
        ├── TAHAP 1: resolusi chapter (kasus A/B/C/D)
        ├── TAHAP 2: buat sections (apply_source = 'struktur-otomatis')
        └── persistSectionText() → section_texts
               [KitabStructureService.php:1586]
               └── KitabTextBatchRepository::textByAnchorRobust()
                      [KitabTextBatchRepository.php:321]
```

**[TERBUKTI]** `persistSectionText()` memakai `textByAnchorRobust()` yang **dibatasi `batch_no`** draft ([`KitabStructureService.php:1586-1666`](app/Services/KitabStructureService.php:1586)). Ini penting: tanpa batas batch, anchor yang sama di batch lain bisa salah ambil.

**[TERBUKTI]** `textByAnchorRobust()` 3 tingkat: exact → normalized → null ([`KitabTextBatchRepository.php:321-381`](app/Repositories/KitabTextBatchRepository.php:321)). Mengembalikan **slice ORIGINAL**, bukan teks ternormalisasi.

---

# B. TABEL: SUMBER TEKS & JALUR PEMROSESAN PER JENIS ANALISIS

## B.1 Dua tabel penyimpanan hasil

| Tabel | Level | Jenis | Kunci unik |
|---|---|---|---|
| `ai_contents` | **BAB** | `terjemah_perlafadz`, `terjemah_seluruh`, `syarah`, `kesimpulan`, `nahwu`, `shorof` | `bab_id + jenis + status` |
| `ai_analyses` | **SUBBAB** | `terjemah`, `perlafadz`, `nahwu`, `shorof`, `syarah`, `kesimpulan` | `category_id + jenis_analisis` |

**[TERBUKTI]** [`AiContentRepository::JENIS`](app/Repositories/AiContentRepository.php:26-33) dan [`AiAnalysisRepository::JENIS`](app/Repositories/AiAnalysisRepository.php:26-33).

**[TERBUKTI]** `AiContentRepository::upsert()` mengunci pada `bab_id + jenis + status` ([`AiContentRepository.php:225-246`](app/Repositories/AiContentRepository.php:225)) → **draft dan published adalah baris terpisah**.

## B.2 Matriks sumber teks per jenis (INTI TEMUAN)

**[TERBUKTI]** Konstanta kunci: [`OpenAIService::PER_BLOCK_TYPES = ['perlafadz','nahwu','shorof']`](app/Services/OpenAIService.php:1310) dan [`AiAnalysisService::BLOCK_SOURCE_TYPES`](app/Services/AiAnalysisService.php) (nilai sama).

| Jenis | Sumber teks saat ini | Pemrosesan | Continuation | Status "pakai Content Block" |
|---|---|---|---|---|
| **Terjemah Perlafadz** | Content Block (per blok) | Per blok, chunk 1000 char | Chunked, bukan continuation | ✅ **YA** |
| **Nahwu** | Content Block (per blok) | Per blok, 1 request/blok | ✅ continuation per blok | ✅ **YA** |
| **Shorof** | Content Block (per blok) | Per blok, 1 request/blok | ✅ continuation per blok | ✅ **YA** |
| **Terjemah Seluruh** | Teks langsung unit (`bab_pages` / `section_texts`) | 1 request seluruh teks | ✅ continuation | ❌ **TIDAK** |
| **Syarah** | Teks langsung unit | 1 request seluruh teks | ✅ continuation prosa | ❌ **TIDAK** |
| **Kesimpulan** | Teks langsung unit | 1 request seluruh teks | ✅ continuation bernomor | ❌ **TIDAK** |
| **Struktur Kitab** | `kitab_text_batches` (teks global) | `KitabStructureParser` deterministik | Tidak ada (deterministik) | ❌ **TIDAK** (memang by design) |

## B.3 Bukti pemisahan sumber (kode aktual)

**[TERBUKTI]** Level BAB — [`AiAnalysisService::runGroupedAnalysis()`](app/Services/AiAnalysisService.php:673-768):
```php
$blockJenis  = array_values(array_intersect($aiJenis, self::BLOCK_SOURCE_TYPES));
$directJenis = array_values(array_diff($aiJenis, self::BLOCK_SOURCE_TYPES));
// Kelompok 1: per Content Block (perlafadz, nahwu, shorof)
if ($blocks !== []) {
    $result = $this->ai->analyzeCategoryByBlocks($context, $blocks, $blockJenis);
} else {
    $result = $this->ai->analyzeCategory($context, $teksArab, $blockJenis); // fallback
}
// Kelompok 2: teks langsung (terjemah, syarah, kesimpulan)
$result = $this->ai->analyzeCategory($context, $teksArab, $directJenis);
```

**[TERBUKTI]** Level SUBBAB — [`ContentCategoryService::runGroupedSubbabAnalysis()`](app/Services/ContentCategoryService.php:920-1009): struktur **identik**.

**[TERBUKTI]** Komentar kode menyatakan aturan ini secara eksplisit di [`AiAnalysisService.php:176-186`](app/Services/AiAnalysisService.php:176) dan [`ContentCategoryService.php:705-715`](app/Services/ContentCategoryService.php:705).

## B.4 Sumber teks "langsung" — dua jalur berbeda

**[TERBUKTI]** Level BAB — [`AiAnalysisService::collectBabText()`](app/Services/AiAnalysisService.php:279-303):
1. `BabPageRepository::fullTextByBabScope($babId)` → `bab_pages WHERE bab_id = X AND section_id IS NULL`
2. Fallback: `BabTextService::babDirectTextDetailed($babId)` → teks wadah BAB (`tipe_bagian='bab'`)

**Catatan penting:** `fullTextByBabScope()` mengembalikan `''` bila kolom `bab_pages.section_id` belum ada — **tanpa fallback** ([`BabPageRepository.php:487-501`](app/Repositories/BabPageRepository.php:487)). Ini pola "safety over convenience".

**[TERBUKTI]** Level SUBBAB — [`ContentCategoryService::collectSubbabSourceText()`](app/Services/ContentCategoryService.php:834-857):
1. `ContentBlockRepository::bySubbab($sectionId)` → gabung `text_arab` dengan `"\n\n"`
2. Fallback: `collectSectionText()` → `section_texts`

**TEMUAN PENTING:** Untuk SUBBAB, sumber "teks langsung" **sebenarnya juga Content Block** (langkah 1). Jadi di level SUBBAB, terjemah/syarah/kesimpulan **sudah** memakai Content Block sebagai sumber teks — tetapi digabung menjadi satu string, bukan per blok. Di level BAB, terjemah/syarah/kesimpulan **tidak** memakai Content Block sama sekali (memakai `bab_pages`).

## B.5 Routing `analyzeCategory()` — jalur khusus per jenis

**[TERBUKTI]** [`OpenAIService::analyzeCategory()`](app/Services/OpenAIService.php:365-522):

| Kondisi | Jalur | Baris |
|---|---|---|
| `jenis === ['perlafadz']` | `analyzePerlafadz()` (chunked) | [:399](app/Services/OpenAIService.php:399) |
| `in_array('terjemah', $jenis)` | `analyzeTerjemahSeluruh()` + prosa untuk sisanya | [:419](app/Services/OpenAIService.php:419) |
| `syarah`/`kesimpulan` diminta | `analyzeProseTypes()` | [:469](app/Services/OpenAIService.php:469) |
| `jenis === ['nahwu']` | `analyzeNahwuSeluruh()` | [:517](app/Services/OpenAIService.php:517) |
| lainnya | `analyzeCategoryGeneric()` | [:521](app/Services/OpenAIService.php:521) |

**Batas input:** `maxInputChars = 20000` ([`OpenAIService.php:102`](app/Services/OpenAIService.php:102), config `openai.max_input_chars`). Bila teks > 20000 char → **gagal total** ([`OpenAIService.php:385-390`](app/Services/OpenAIService.php:385)).

---

# C. TEMUAN MASALAH (dengan bukti file, fungsi, baris)

## C.1 [TINGGI] Terjemah Seluruh, Syarah, Kesimpulan TIDAK memakai Content Block

**Bukti:** [`AiAnalysisService.php:683-684`](app/Services/AiAnalysisService.php:683) dan [`ContentCategoryService.php:924-925`](app/Services/ContentCategoryService.php:924) memisahkan `directJenis` = semua jenis di luar `['perlafadz','nahwu','shorof']`.

**Dampak:** Tiga dari enam jenis analisis tidak mendapat manfaat struktur blok (batas topik, marker, halaman). Untuk level BAB, sumbernya `bab_pages` yang merupakan **salinan** teks, bukan blok terstruktur.

**Catatan:** Ini **bukan bug** — ini keputusan desain yang terdokumentasi. Namun bertentangan dengan tujuan audit ("semua jenis analisis memakai Content Block").

## C.2 [TINGGI] Batas input 20.000 karakter → kegagalan total tanpa pemecahan

**Bukti:** [`OpenAIService.php:385-390`](app/Services/OpenAIService.php:385):
```php
if (str_len($teksArab) > $this->maxInputChars) {
    return $this->failure('Teks Arab terlalu panjang untuk sekali analisis (maks ... karakter).', $started);
}
```

**Dampak:** BAB/SUBBAB dengan teks > 20.000 karakter **tidak dapat dianalisis sama sekali** untuk terjemah/syarah/kesimpulan. Tidak ada chunking otomatis di jalur ini (chunking hanya untuk perlafadz).

**Catatan:** `analyzeCategoryByBlocks()` **tidak** terkena batas ini karena memproses per blok ([`OpenAIService.php:1337-1533`](app/Services/OpenAIService.php:1337)). Ini keunggulan struktural Content Block yang belum dimanfaatkan oleh 3 jenis lainnya.

## C.3 [TINGGI] Kegagalan satu blok membatalkan SELURUH analisis per-block

**Bukti:** [`OpenAIService.php:1395-1408`](app/Services/OpenAIService.php:1395):
```php
if (!$result['success']) {
    return $this->failure('Analisis ' . $type . ' gagal pada Content Block ' . $blockNo . ...);
}
```
Juga validasi per blok [`OpenAIService.php:1431-1444`](app/Services/OpenAIService.php:1431) → `return $this->failure(...)`.

**Dampak:** Pada BAB dengan 100+ blok, satu blok gagal (timeout/JSON invalid) → **seluruh** hasil jenis tersebut dibuang. Tidak ada partial save. Ini konsisten dengan prinsip "no partial save" tetapi berisiko tinggi untuk unit besar.

## C.4 [SEDANG] Duplikasi logika pemilihan sumber di dua service

**Bukti:** `runGroupedAnalysis()` ([`AiAnalysisService.php:673`](app/Services/AiAnalysisService.php:673)) dan `runGroupedSubbabAnalysis()` ([`ContentCategoryService.php:920`](app/Services/ContentCategoryService.php:920)) hampir identik (~95 baris duplikat).

**Dampak:** Perubahan aturan sumber harus dilakukan di dua tempat; risiko divergensi.

## C.5 [SEDANG] Duplikasi aturan parent struktur di dua tempat

**Bukti:** [`KitabStructureParser::assignParents()`](app/Services/KitabStructureParser.php:831) vs [`KitabStructureService::computeParentIndexes()`](app/Services/KitabStructureService.php:895).

**Dampak:** Bila salah satu diubah, hierarki hasil parser dan hasil recompute bisa berbeda.

## C.6 [SEDANG] `bab_pages` adalah salinan teks, bukan sumber tunggal

**Bukti:** [`BabPageRepository`](app/Repositories/BabPageRepository.php) menyimpan `teks_arab` sebagai **copy** dari sumber. `fullText()` menggabungkan **semua** baris termasuk subbab ([`BabPageRepository.php:465-473`](app/Repositories/BabPageRepository.php:465)) — ada peringatan dokumentasi untuk memakai `fullTextByBabScope()`.

**Dampak:** Ada tiga representasi teks yang hidup berdampingan: `section_texts` (sumber), `bab_pages` (salinan), `content_blocks` (turunan). Risiko inkonsistensi bila salah satu diperbarui tanpa yang lain.

## C.7 [SEDANG] Fallback diam-diam ke teks langsung bila Content Block kosong

**Bukti:** [`AiAnalysisService.php:697-700`](app/Services/AiAnalysisService.php:697) dan [`ContentCategoryService.php:938-941`](app/Services/ContentCategoryService.php:938):
```php
if ($blocks !== []) {
    $result = $this->ai->analyzeCategoryByBlocks(...);
} else {
    $result = $this->ai->analyzeCategory($context, $teksArab, $blockJenis); // fallback
}
```

**Dampak:** Hasil analisis bisa berasal dari dua sumber berbeda tanpa penanda di database. Tidak ada kolom `source_type` pada `ai_contents`/`ai_analyses` untuk membedakan. **[TERBUKTI]** dari daftar kolom di [`AiContentRepository.php:26-33`](app/Repositories/AiContentRepository.php:26) dan [`AiAnalysisRepository.php:119-139`](app/Repositories/AiAnalysisRepository.php:119).

## C.8 [RENDAH] `all_bab_direct` scope tidak diekspos di UI

**Bukti:** Konstanta ada di [`ContentBlockService::SCOPES`](app/Services/ContentBlockService.php:63) dan ditangani [`action.php:94-98`](admin/content-blocks/action.php:94), tetapi tidak ada form tombol di view.

**Dampak:** Fitur tidak dapat diakses admin; hanya bisa lewat POST manual.

## C.9 [RENDAH] Setiap baris kosong = satu blok paragraph

**Bukti:** [`ContentBlockParserService.php:233-243`](app/Services/ContentBlockParserService.php:233). Sudah tercatat di audit lama [`LAPORAN_AUDIT_PEMBAGIAN_CONTENT_BLOCK.md:19`](database/LAPORAN_AUDIT_PEMBAGIAN_CONTENT_BLOCK.md:19) sebagai temuan C.

**Dampak:** Satu topik bisa menjadi puluhan blok paragraph → memperbanyak jumlah request AI per-block (biaya & waktu).

## C.10 [RENDAH] Running header `[باب الصلاة]` dibuang → judul BAB tidak menjadi blok

**Bukti:** [`ContentBlockParserService.php:312-314`](app/Services/ContentBlockParserService.php:312). Tercatat di audit lama sebagai temuan B.

**Dampak:** Daftar blok didominasi paragraph tanpa judul; konteks topik hilang dari blok pertama.

---

# D. RISIKO TERHADAP TEKS ARAB, STRUKTUR KITAB, KONTEKS, DAN HASIL LAMA

## D.1 Risiko terhadap teks Arab

| Risiko | Status | Bukti |
|---|---|---|
| Teks Arab diubah saat parsing | **Rendah** — parser hanya `trim()` dan `implode("\n")`; tidak mengubah karakter | [`ContentBlockParserService.php:192`](app/Services/ContentBlockParserService.php:192) |
| Teks Arab hilang karena baris hiasan dibuang | **Sedang** — baris `ــ`/`***` dibuang, tetapi itu bukan teks isi | [:271-274](app/Services/ContentBlockParserService.php:271) |
| Teks Arab hilang karena running header dibuang | **Sedang** — `[باب الصلاة]` dibuang; bila itu satu-satunya judul, judul hilang dari blok | [:312](app/Services/ContentBlockParserService.php:312) |
| Teks Arab terpotong di batas halaman | **Rendah** — ada mekanisme `continuation` lintas page marker | [:298-305](app/Services/ContentBlockParserService.php:298) |
| Teks Arab berubah saat normalisasi hasil AI | **Rendah** — `analysis_normalize()` tidak menyentuh teks Arab di dalam `[[AR]]` | [`analysis_normalizer.php:193-195`](app/Helpers/analysis_normalizer.php:193) |
| Teks Arab hilang karena anchor tidak cocok | **Sedang** — dimitigasi `textByAnchorRobust()` 3 tingkat | [`KitabTextBatchRepository.php:321`](app/Repositories/KitabTextBatchRepository.php:321) |

## D.2 Risiko terhadap struktur kitab

| Risiko | Status | Bukti |
|---|---|---|
| Batch memotong struktur | **Tidak ada** — parser struktur memakai teks global | [`KitabStructureParser.php:83`](app/Services/KitabStructureParser.php:83) |
| Duplikasi SUBBAB (urutan sama) | **Tinggi** — tercatat di audit lama sebagai temuan A | [`LAPORAN_AUDIT_PEMBAGIAN_CONTENT_BLOCK.md:17`](database/LAPORAN_AUDIT_PEMBAGIAN_CONTENT_BLOCK.md:17) |
| Blok BAB langsung menumpuk saat regenerate | **Tidak ada** — sudah diperbaiki (`section_id IS NULL` + `deleteByBabDirect`) | [`ContentBlockService.php:331-334`](app/Services/ContentBlockService.php:331) |
| Wadah BAB (`tipe_bagian='bab'`) tampil sebagai Subbab | **Tidak ada** — `subbabByChapter()` mengecualikan `tipe_bagian='bab'` | [`SectionRepository.php:273-290`](app/Repositories/SectionRepository.php:273) |
| Hierarki parent berbeda antara parser & recompute | **Sedang** — logika terduplikasi | C.5 |

## D.3 Risiko terhadap konteks & kontinuitas

| Risiko | Status | Bukti |
|---|---|---|
| Terjemah Seluruh kehilangan konteks antar blok | **Tinggi** — memakai teks gabungan, bukan blok; batas topik tidak terlihat AI | C.1 |
| Syarah kehilangan rujukan blok | **Tinggi** — sama seperti di atas | C.1 |
| Nahwu/Shorof kehilangan konteks antar blok | **Sedang** — diproses per blok terpisah; AI tidak melihat blok sebelumnya | [`OpenAIService.php:1387-1393`](app/Services/OpenAIService.php:1387) |
| Identitas blok hilang dari hasil | **Rendah** — `ensureBlockIdentityHeader()` memaksa teks Arab asli di baris pertama | [`OpenAIService.php:1417`](app/Services/OpenAIService.php:1417) |
| Kegagalan satu blok membatalkan semua | **Tinggi** | C.3 |
| Timeout pada unit besar | **Tinggi** — budget wall-clock 100s, `max_continuations` 10 | [`OpenAIService.php`](app/Services/OpenAIService.php) `request()` |

## D.4 Risiko terhadap hasil analisis lama (legacy)

| Risiko | Status | Bukti |
|---|---|---|
| Regenerate menimpa published | **Tidak ada** — `upsert` mengunci `status`; published baris terpisah | [`AiContentRepository.php:225`](app/Repositories/AiContentRepository.php:225) |
| Regenerate menimpa published (SUBBAB) | **Tidak ada** — dicek eksplisit `if status === 'published' continue` | [`ContentCategoryService.php:748-750`](app/Services/ContentCategoryService.php:748) |
| Hapus published tanpa konfirmasi | **Tidak ada** — butuh `confirm_published=1` | [`admin/ai/action.php:220`](admin/ai/action.php:220) |
| Hapus salah sasaran (scope longgar) | **Rendah** — `deleteScoped()` 7-way match (SUBBAB) / 5-way (BAB) | [`AiAnalysisRepository.php:284-319`](app/Repositories/AiAnalysisRepository.php:284) |
| Hasil lama hilang saat reset struktur | **Tidak ada** — `resetStructure()` menolak bila ada hasil applied | [`KitabStructureService.php:1928`](app/Services/KitabStructureService.php:1928) |
| Hasil lama tidak mencatat sumber (blok vs langsung) | **Sedang** — tidak ada kolom `source_type` | C.7 |

---

# E. DESAIN ARSITEKTUR TARGET — SEMUA ANALISIS MEMAKAI CONTENT BLOCK

## E.1 Prinsip target

1. **Satu sumber kebenaran teks:** `content_blocks` (turunan deterministik dari `section_texts`).
2. **Semua 6 jenis** membaca dari `content_blocks`; `bab_pages`/`section_texts` hanya fallback terakhir dan **ditandai**.
3. **Konteks antar blok** dipertahankan untuk jenis yang butuh kesinambungan (terjemah, syarah, kesimpulan).
4. **Tidak ada partial save** — tetapi kegagalan per blok dicatat dan dapat dilanjutkan (resume), bukan membatalkan seluruh unit.
5. **Hasil menyimpan asal sumber** agar audit-able.

## E.2 Perubahan yang diusulkan (belum diimplementasikan)

### E.2.1 Tambah kolom penanda sumber (additive, non-destruktif)

```sql
ALTER TABLE ai_contents
  ADD COLUMN source_type VARCHAR(20) NULL DEFAULT NULL
      COMMENT 'content_block | direct_text | fallback',
  ADD COLUMN source_block_count INT NULL DEFAULT NULL;

ALTER TABLE ai_analyses
  ADD COLUMN source_type VARCHAR(20) NULL DEFAULT NULL,
  ADD COLUMN source_block_count INT NULL DEFAULT NULL;
```
**Sifat:** additive, nullable, tidak mengubah baris lama (NULL = tidak diketahui). Aman untuk rollback (kolom bisa diabaikan).

### E.2.2 Satukan pemilihan sumber ke satu kelas

Buat `AnalysisSourceResolver` yang menggantikan duplikasi di `runGroupedAnalysis()` dan `runGroupedSubbabAnalysis()`:

```php
final class AnalysisSourceResolver
{
    /**
     * @return array{
     *   mode: 'per_block'|'joined_blocks'|'direct',
     *   blocks: array<int, array<string,mixed>>,
     *   text: string,
     *   source_type: string
     * }
     */
    public function resolve(string $jenis, array $blocks, string $directText): array
    {
        // Semua jenis memakai blok bila tersedia.
        if ($blocks !== []) {
            return [
                'mode'        => in_array($jenis, ['perlafadz','nahwu','shorof'], true)
                                    ? 'per_block' : 'joined_blocks',
                'blocks'      => $blocks,
                'text'        => implode("\n\n", array_column($blocks, 'text_arab')),
                'source_type' => 'content_block',
            ];
        }
        return ['mode' => 'direct', 'blocks' => [], 'text' => $directText, 'source_type' => 'direct_text'];
    }
}
```

### E.2.3 Terjemah/Syarah/Kesimpulan: `joined_blocks` dengan penanda batas

Untuk tiga jenis ini, teks tetap digabung (agar AI melihat alur), tetapi **batas blok ditandai** dengan penanda internal yang **dibuang sebelum simpan**:

```
[[BLOCK 1]]
<teks blok 1>
[[BLOCK 2]]
<teks blok 2>
```

Prompt diminta merujuk nomor blok. `analysis_normalize()` membuang penanda `[[BLOCK n]]` sebelum simpan (mirip `[[AR]]`).

**Keuntungan:** AI melihat struktur; hasil tetap teks murni; tidak ada perubahan skema.

### E.2.4 Chunking otomatis untuk teks > `max_input_chars`

Ganti kegagalan total (C.2) dengan pemecahan **pada batas blok**, bukan pada batas karakter. Karena blok sudah tersedia sebagai unit diskrit, pemecahan menjadi aman dan tidak memotong kalimat Arab di tengah kata.

```php
// Di dalam AnalysisSourceResolver / pemanggil analyzeCategory()
$maxChars = (int) config('openai.max_input_chars', 20000);

if ($mode === 'joined_blocks' && str_len($text) > $maxChars) {
    // Kelompokkan blok berurutan sampai mendekati batas, tanpa memotong blok.
    $groups = [];
    $buffer = '';
    foreach ($blocks as $block) {
        $candidate = $buffer === '' ? $block['text_arab'] : $buffer . "\n\n" . $block['text_arab'];
        if ($buffer !== '' && str_len($candidate) > $maxChars) {
            $groups[] = $buffer;
            $buffer    = $block['text_arab'];
        } else {
            $buffer = $candidate;
        }
    }
    if ($buffer !== '') {
        $groups[] = $buffer;
    }
    // Analisis per grup, lalu gabungkan hasil (joinProseParts / joinNumberedParts).
}
```

**Aturan penting:**
1. **Satu blok tidak boleh dipecah** — blok adalah unit makna terkecil. Jika satu blok saja sudah > `max_input_chars`, blok itu dianalisis sendiri (dan bila tetap gagal, hanya blok itu yang gagal — lihat E.2.5).
2. **Penggabungan hasil** memakai fungsi yang sudah ada: [`joinProseParts()`](app/Services/OpenAIService.php:1009) untuk prosa, [`joinNumberedParts()`](app/Services/OpenAIService.php:1107) untuk bernomor.
3. **Kontinuitas antar-grup** dijaga dengan mengirim ekor grup sebelumnya (mis. `tailChars()`, [`OpenAIService.php:2915`](app/Services/OpenAIService.php:2915)) sebagai konteks sambungan — pola yang sudah dipakai pada continuation Terjemah Seluruh.
4. **Tidak ada perubahan skema** — chunking murni di lapisan service.

### E.2.5 Kegagalan parsial: isolasi per blok (bukan gagal total)

Ganti perilaku C.3 (satu blok gagal → seluruh jenis gagal) dengan isolasi:

```php
$hasilBlok = [];
$blokGagal  = [];
foreach ($blocks as $i => $block) {
    $r = $this->analyzeSingleTypeForBlock($context, $block['text_arab'], $jenis, $i + 1, count($blocks));
    if ($r['success'] ?? false) {
        $hasilBlok[] = $r['konten'];
    } else {
        $blokGagal[] = $i + 1;   // catat nomor blok yang gagal
    }
}

if ($hasilBlok === []) {
    return $this->failureList('Semua blok gagal dianalisis.', $started); // gagal total hanya bila NOL berhasil
}
// Simpan hasil parsial + catat blok gagal ke ai_logs (bukan ke kolom baru).
```

**Kebijakan:**
- **Nol blok berhasil** → gagal total, hasil lama dipertahankan (perilaku sekarang).
- **Sebagian berhasil** → simpan hasil parsial sebagai `draft`, dan tulis daftar blok gagal ke log agar admin bisa regenerate blok tersebut.
- **Tidak ada kolom status per blok** ditambahkan pada tahap ini (menghindari migrasi berisiko). Status parsial cukup dicatat di log dan di pesan flash.

### E.2.6 Penanda sumber (`source_type`) — additive, opsional

Agar admin tahu apakah suatu hasil analisis berasal dari Content Block atau teks langsung, tambahkan kolom **nullable** (additive, aman):

```sql
ALTER TABLE ai_contents
    ADD COLUMN source_type VARCHAR(20) NULL DEFAULT NULL AFTER jenis,
    ADD COLUMN source_block_count INT NULL DEFAULT NULL AFTER source_type;

ALTER TABLE ai_analyses
    ADD COLUMN source_type VARCHAR(20) NULL DEFAULT NULL AFTER jenis_analisis,
    ADD COLUMN source_block_count INT NULL DEFAULT NULL AFTER source_type;
```

- Nilai: `content_block` | `direct_text` | `NULL` (data lama).
- **Tidak ada backfill** — data lama tetap `NULL` dan diperlakukan sebagai "tidak diketahui".
- Semua kode pembacaan harus toleran `NULL` (pola `tableReady()`/`columnReady()` yang sudah ada).

## E.3 Diagram alur target (semua jenis memakai Content Block)

```
                    section_texts (SUMBER KEBENARAN)
                              │
                              ▼
                 ContentBlockParserService::parse()
                              │
                              ▼
                     content_blocks  ──────────────┐
                              │                    │
                              ▼                    │
              AnalysisSourceResolver::resolve()    │
                              │                    │
        ┌─────────────────────┼────────────────────┐
        ▼                     ▼                    ▼
   per_block            joined_blocks          direct
 (perlafadz,           (terjemah, syarah,    (fallback bila
  nahwu, shorof)        kesimpulan)          blok kosong)
        │                     │                    │
        ▼                     ▼                    ▼
 analyzeSingleType     analyzeCategory       analyzeCategory
   ForBlock()          (teks gabungan +      (teks langsung)
        │               penanda [[BLOCK n]])       │
        │                     │                    │
        └──────────┬──────────┴────────────────────┘
                   ▼
        chunking per blok bila > max_input_chars
                   ▼
        isolasi kegagalan per blok (parsial)
                   ▼
        analysis_normalize() → analysis_validate()
                   ▼
        ┌──────────┴──────────┐
        ▼                     ▼
   ai_contents           ai_analyses
   (BAB level)           (SUBBAB level)
   + source_type         + source_type
```

**Prinsip yang dijaga:**
1. **Satu sumber teks** — `section_texts` → `content_blocks`. Tidak ada lagi jalur yang membaca `bab_pages` untuk analisis (kecuali sebagai fallback eksplisit yang tercatat).
2. **Satu titik pemilihan sumber** — `AnalysisSourceResolver`, menggantikan duplikasi di dua service.
3. **Kegagalan terisolasi** — satu blok gagal tidak membatalkan seluruh jenis.
4. **Tidak ada kehilangan teks** — blok tidak pernah dipecah; chunking hanya pada batas blok.
5. **Kompatibel mundur** — kolom baru nullable, data lama tidak diubah.

---

# F. TAHAP MIGRASI PALING AMAN & PENGUJIAN YANG DIPERLUKAN

## F.1 Prinsip migrasi

**[TERBUKTI]** Berdasarkan temuan C.1–C.10 dan risiko D.1–D.4, migrasi **tidak boleh** dilakukan sekaligus. Aturan:

1. **Jangan regenerate massal sebelum Finding A** ([`LAPORAN_AUDIT_PEMBAGIAN_CONTENT_BLOCK.md`](database/LAPORAN_AUDIT_PEMBAGIAN_CONTENT_BLOCK.md)) diperbaiki — duplikasi SUBBAB akan tereproduksi.
2. **Setiap tahap harus dapat dibalik** (reversible) atau minimal tidak merusak data lama.
3. **Data lama tidak disentuh** — hasil analisis `PUBLISHED` tidak boleh ditimpa otomatis.
4. **Satu tahap = satu perubahan konsep**, diuji terpisah sebelum lanjut.

## F.2 Tahap migrasi (berurutan, tiap tahap berhenti untuk verifikasi)

### Tahap 0 — Prasyarat data (TANPA perubahan kode)

| Langkah | Aksi | Verifikasi |
|---|---|---|
| 0.1 | Audit duplikasi SUBBAB (Finding A): cari `sections` dengan `urutan` sama dalam satu `chapter_id` | Query read-only; daftar duplikat |
| 0.2 | Audit `content_blocks` ganda: `GROUP BY chapter_id, section_id, sort_order HAVING COUNT(*) > 1` | Daftar blok ganda |
| 0.3 | Audit cakupan: BAB/SUBBAB yang punya `section_texts` tetapi `content_blocks` kosong | Daftar unit belum ter-parse |
| 0.4 | Backup penuh database + folder `storage/` | File backup terverifikasi |

**Gate:** Jangan lanjut bila 0.1/0.2 menemukan duplikasi yang belum diputuskan penanganannya.

### Tahap 1 — Perbaikan data duplikasi (manual, terverifikasi)

| Langkah | Aksi | Risiko |
|---|---|---|
| 1.1 | Putuskan SUBBAB duplikat (gabung/hapus salah satu) — **manual oleh admin** | Sedang — perlu keputusan manusia |
| 1.2 | Regenerate Content Block **hanya** untuk BAB yang terdampak, scope `bab_direct`/`subbab` (bukan `all_content`) | Rendah — unit terisolasi |
| 1.3 | Verifikasi jumlah blok sebelum vs sesudah | — |

**Gate:** Jumlah blok harus turun/berubah sesuai ekspektasi, tidak ada blok hilang pada unit yang tidak terdampak.

### Tahap 2 — Refactor tanpa perubahan perilaku (kode saja)

| Langkah | Aksi | Catatan |
|---|---|---|
| 2.1 | Buat `AnalysisSourceResolver` (E.2.2) | Belum dipakai; hanya kelas baru |
| 2.2 | Ganti duplikasi di `runGroupedAnalysis()` + `runGroupedSubbabAnalysis()` dengan resolver | **Perilaku identik** — hanya menghilangkan duplikasi (C.4) |
| 2.3 | Jalankan seluruh test suite yang ada | Lihat F.3 |

**Gate:** Semua test lama lulus tanpa perubahan hasil. Bila ada perbedaan output, **rollback**.

### Tahap 3 — Terjemah/Syarah/Kesimpulan memakai blok (perubahan perilaku pertama)

| Langkah | Aksi | Catatan |
|---|---|---|
| 3.1 | Aktifkan `joined_blocks` untuk terjemah/syarah/kesimpulan **hanya di level SUBBAB** | Level SUBBAB sudah memakai blok (B.4) — risiko paling rendah |
| 3.2 | Uji banding: hasil lama (direct) vs baru (joined_blocks) pada 3–5 SUBBAB sampel | Manual review kualitas |
| 3.3 | Bila kualitas setara/lebih baik → aktifkan di level BAB | — |

**Gate:** Kualitas terjemah tidak menurun; tidak ada teks hilang. Bila menurun, tetap di `direct` untuk level BAB.

### Tahap 4 — Chunking & isolasi kegagalan (E.2.4, E.2.5)

| Langkah | Aksi | Catatan |
|---|---|---|
| 4.1 | Implementasi chunking per blok untuk teks > `max_input_chars` | Hanya aktif bila melebihi batas |
| 4.2 | Implementasi isolasi kegagalan per blok | Hasil parsial disimpan sebagai draft |
| 4.3 | Uji dengan teks > 20000 karakter | Lihat F.3 |

**Gate:** Teks panjang yang sebelumnya gagal total kini menghasilkan output (parsial bila perlu), tanpa kehilangan blok.

### Tahap 5 — Kolom `source_type` (additive, opsional)

| Langkah | Aksi | Catatan |
|---|---|---|
| 5.1 | Jalankan `ALTER TABLE` additive (E.2.6) | Nullable, tanpa backfill |
| 5.2 | Isi `source_type` pada penulisan baru | Data lama tetap `NULL` |
| 5.3 | Tampilkan sumber di UI admin (opsional) | — |

**Gate:** Tidak ada error pada pembacaan data lama (`NULL` ditangani).

## F.3 Pengujian yang diperlukan

### F.3.1 Test yang sudah ada (wajib lulus sebelum & sesudah tiap tahap)

| Test | Fokus |
|---|---|
| [`test_content_block_parser.php`](database/test_content_block_parser.php) | Aturan parser 9 langkah |
| [`test_content_block_ordering.php`](database/test_content_block_ordering.php) | `sort_order` per unit |
| [`test_content_block_relation.php`](database/test_content_block_relation.php) | Relasi BAB/SUBBAB |
| [`test_content_block_section_id_decision.php`](database/test_content_block_section_id_decision.php) | `section_id` NULL vs ID |
| [`test_content_block_section_mapping.php`](database/test_content_block_section_mapping.php) | Pemetaan section |
| [`test_content_block_generate_scope.php`](database/test_content_block_generate_scope.php) | 5 cakupan generate |
| [`test_content_block_delete_scope.php`](database/test_content_block_delete_scope.php) | 4 cakupan hapus |
| [`test_content_block_six_scenarios.php`](database/test_content_block_six_scenarios.php) | Skenario gabungan |
| [`test_analysis_normalizer.php`](database/test_analysis_normalizer.php) | Normalisasi per jenis |
| [`test_analysis_continuation.php`](database/test_analysis_continuation.php) | Continuation & join |
| [`test_nahwu_block_pairing.php`](database/test_nahwu_block_pairing.php) | Pairing blok Nahwu |
| [`test_nahwu_inline_parser.php`](database/test_nahwu_inline_parser.php) | Parser Nahwu inline |

### F.3.2 Test baru yang harus dibuat

| Test baru | Tujuan | Tahap |
|---|---|---|
| `test_analysis_source_resolver.php` | Resolver memilih `per_block`/`joined_blocks`/`direct` dengan benar | 2 |
| `test_analysis_joined_blocks_parity.php` | Hasil `joined_blocks` setara `direct` pada sampel | 3 |
| `test_analysis_chunking_by_block.php` | Teks > `max_input_chars` dipecah pada batas blok, tidak memotong blok | 4 |
| `test_analysis_partial_failure.php` | Satu blok gagal → hasil parsial tersimpan, bukan gagal total | 4 |
| `test_analysis_source_type_null.php` | Data lama `source_type = NULL` tidak menyebabkan error | 5 |

### F.3.3 Uji manual wajib (tidak bisa diotomasi)

1. **Banding kualitas terjemah** — 3–5 SUBBAB, hasil lama vs baru, dibaca manusia.
2. **Verifikasi teks Arab verbatim** — pastikan `text_arab` di `content_blocks` identik dengan `section_texts` sumber (tidak ada karakter hilang/berubah).
3. **Uji teks sangat panjang** — satu BAB dengan total > 20000 karakter.
4. **Uji BAB tanpa SUBBAB** dan **BAB dengan SUBBAB** — keduanya harus berjalan.
5. **Uji regenerasi tidak menimpa PUBLISHED** — hasil `PUBLISHED` harus tetap.

## F.4 Kriteria rollback

| Tahap | Kondisi rollback | Cara |
|---|---|---|
| 2 | Ada test lama gagal | Kembalikan pemanggilan langsung (revert commit) |
| 3 | Kualitas terjemah menurun | Matikan `joined_blocks` untuk level BAB (flag config) |
| 4 | Chunking memotong blok / hasil kacau | Nonaktifkan chunking (kembali ke perilaku gagal total) |
| 5 | Error pembacaan `NULL` | Kolom nullable tidak mengganggu; cukup perbaiki kode pembacaan |

## F.5 Ringkasan urutan aman

```
Tahap 0 (audit data)  →  Tahap 1 (perbaiki duplikasi)  →  Tahap 2 (refactor tanpa ubah perilaku)
      →  Tahap 3 (SUBBAB dulu, lalu BAB)  →  Tahap 4 (chunking + isolasi)  →  Tahap 5 (source_type)
```

**Setiap tahap berhenti untuk verifikasi.** Jangan gabungkan dua tahap dalam satu perubahan.

---

# PENUTUP

Laporan ini disusun **sepenuhnya dari pembacaan kode aktual** dengan rujukan `file:baris`. Klaim yang belum diverifikasi pada data produksi ditandai **[ASUMSI]**.

**Tidak ada perubahan kode, database, konfigurasi, atau data yang dilakukan.** Tidak ada migrasi dijalankan. Tidak ada proses analisis yang menulis data.

**Menunggu persetujuan** sebelum melaksanakan Tahap 0 atau perubahan apa pun.