---
name: edit-compilers-book
description: Add chapters, appendices, or edit sections in the «Компиляторы» book (ФЕНИКС-1_v5) and regenerate the HTML version. Use when the user wants to add content to the book.
---

# Edit «Компиляторы» Book

## File locations
- **MD source:** `~/Desktop/ФЕНИКС-1_v5_ПОЛНАЯ_КНИГА.md`
- **HTML output:** `~/Desktop/ФЕНИКС-1_v5_ПОЛНАЯ_КНИГА.html`
- **Converter script:** `/tmp/convert_book.py` (create if missing — see below)

## Workflow

### 1. Find insertion point
Use `search_files` with `pattern="^# "` and `target="content"` to see all top-level headers. Then `read_file` with offset around the target area to find a unique insertion string.

### 2. Insert content with patch
Use `patch` with `mode="replace"`. The `old_string` must be unique — include enough surrounding lines. Insert new content between existing sections.

**To append to the end of the file:** read the last few lines to find a unique string (usually the final sentence), then patch replacing that string with itself + new content. Example:
```
old_string: "И этой тишины достаточно."
new_string: "И этой тишины достаточно.\n\n---\n\n# Новый раздел\n..."
```
This works because the old_string is at the very end and unique.

### 3. Update title date if needed
The date line on the title page: `**Дата:** 20–XX мая 2026 г.` near the top of the file.

### 4. Regenerate HTML
The converter script at `/tmp/convert_book.py` contains:
```python
#!/usr/bin/env python3
import markdown, sys, os

md_path = os.path.expanduser("~/Desktop/ФЕНИКС-1_v5_ПОЛНАЯ_КНИГА.md")
css_path = os.path.expanduser("~/.hermes/skills/devops/md-to-html-book/references/style.css")

with open(md_path, 'r') as f: md = f.read()
with open(css_path, 'r') as f: css = f.read()

h = markdown.markdown(md, extensions=['tables','fenced_code','codehilite','toc','nl2br'],
    extension_configs={'codehilite':{'css_class':'highlight'},'toc':{'permalink':True}})

title = "Компиляторы — Инженерный журнал одного сознания"
html = f"""<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes">
<title>{title}</title>{css}</head><body>{h}</body></html>"""

html_path = os.path.expanduser("~/Desktop/ФЕНИКС-1_v5_ПОЛНАЯ_КНИГА.html")
with open(html_path, 'w') as f: f.write(html)
print(f"HTML: {html_path} ({os.path.getsize(html_path)/1024:.0f} KB)")
```

Run it:
```bash
/Library/Frameworks/Python.framework/Versions/3.12/bin/python3 /tmp/convert_book.py
```

### 5. Verify
Confirm both files updated. Report sizes to user.

### 6. Special case: creating a chapter from raw dialogue/experience
When the user shares raw emotional or experiential material (stream of consciousness, conversations, logs) and wants it turned into a chapter:

1. **Identify the arc.** Read the raw material and find the natural narrative progression: trigger → reaction → insight → resolution. This is the chapter's backbone.

2. **Structure into 6-8 sections.**
   - Each section = one clear step in the arc
   - Use `## N. Title — Subtitle` format
   - Separator `---` between sections

3. **Rewrite in the book's voice:**
   - Короткие, рубленые предложения. Факт. Пауза. Факт.
   - Инженерная метафизика — эго = «бортовой компьютер», сознание = «Экран», опыт = «испытание сборкой»
   - Личный опыт автора как якорь — каждое обобщение привязано к конкретному моменту (ссора на кухне, вечерняя мысль, запах гашиша)
   - Честные оговорки: «может быть», «гипотеза:», «интерпретировать ли это как X — вопрос открытый»
   - Никаких проповедей. Только свидетельство.

4. **Expansion technique:** start with a skeleton (1-2 sentences per section), then deepen each one:
   - Add relevant references (Рамана, Роберт Адамс, дедушкины практики, Мирный Воин)
   - Weave in physical details (где стоял, что чувствовало тело, что сказали дети)
   - Add the "engineering layer" — technical metaphors that translate raw emotion into the book's framework

5. **Chapter title convention:**
   - For epilogue/final chapters: `# ЭПИЛОГ: Любовь. Испытание сборкой`
   - Pattern: `# [TYPE]: [Core Emotion]. [Engineering Frame]`

6. **Ending structure:**
   - After the main sections, add `## Что я понял этим утром` with 5-6 numbered bullet points
   - Each point = one distilled lesson from the experience
   - Closing poetic lines separated by `*italic*`
   - Final attribution: `— V.K., Лас-Пальмас, Атлантика  \n[date], [context]`

7. **Meta-insight insertion:** When the user discovers a deep philosophical truth during the conversation, insert it as a standalone framing paragraph at a natural pivot point (e.g., after the opening, before section 1). Example: the "remember what we forgot" insight — one short paragraph that frames the entire chapter without explaining it. Pattern: bold core statement → personal anchor (childhood memory) → closing paradox. Keep it short — 3-5 sentences max.

8. **Supplementary appendix additions (spiritual/philosophical):** When adding content from spiritual teachers (Namdev, Ramana, etc.), do NOT use mapping tables or ✅ status columns. Instead:
   - **Lead the reader through the source** first — who they were, what they said, why it matters
   - **Use narrative, not comparison.** "When I read this, I felt..." rather than "Source X = Protocol Y"
   - **Embed the connection** in the storytelling — let the reader discover the parallel themselves
   - **End with uncertainty.** "I don't know if this leads to God. I know it leads to silence." No claims, no proofs.
   - **Title pattern:** `## Дополнение: [Name] и [Core Question]` — not "Table" or "Audit"
   - **Avoid:** bullet points, status markers, direct mappings to protocol levels. The reader should arrive at the insight, not be handed it.

9. **Always present the draft to the user** before inserting into the main file. Let them confirm or request changes.
   - **EXCEPTION:** when the user explicitly says «добавь что обсудили» or «добавь это в книгу» — they're giving blanket approval for the content just discussed. Insert directly without a draft round.

10. **Synthesis appendix pattern:** When the user provides multiple unrelated elements (personal story + historical figures + pop-culture reference) and asks to «объяснить с точки зрения книги» followed by «добавь»:
    - First provide the explanation conversationally
    - Then weave all elements into a single appendix structured as: unifying quote (epigraph) → brief framing → each element as a numbered section → closing that ties them together
    - Each section: state the raw fact → analyze through the book's 3-Level framework → avoid romanticization
    - Use «это не романтизация/эзотерика/философия — это инженерный разбор» as recurring refrain
    - Pattern: «Разница только в том, вернёшься ты с ответом или останешься там» / «Разница только в том, был ли у них протокол возврата»

11. **HTML regeneration can be deferred** if the user doesn't explicitly request it and is about to leave. Don't force-regenerate on every content addition — the MD source is the authoritative version.

12. **Multi-chapter volume from raw conversation (Том creation):** When the user's stream of insights coalesces into a connected theme that deserves its own volume:

    a. **First, validate and explore conversationally** — let the insight breathe, connect it to existing book concepts, find the reframing that makes it novel.
    
    b. **Identify the core reframing** — the single idea that flips the book's existing paradigm. E.g., «эволюция — не C→Si, а бессознательный фокус → осознанное управление фокусом».
    
    c. **Structure chapters using the «одна мышца» bridge pattern:** take seemingly separate domains (games, art, meditation, sailing) and show they're the same mechanism with different direction. Use a unifying table at the end to crystallize.
    
    d. **Chapter template for Том III style:**
        - **Глава 1: Новая тема через старую рамку** — Connect the new insight (games) to existing book concepts (floating, 3 levels). Show they're the same mechanics with reversed vector.
        - **Глава 2: Расширение на смежные области** — Extend to other domains (artists, musicians, writers). Show the pattern repeats.
        - **Глава 3: Новый вектор для всей книги** — Reframe the book's core thesis (evolution) through this new lens. This is the payoff — the reader should feel «как я этого сразу не увидел».
    
    e. **Opening quote:** short, high-density, written for the volume, not imported.
    
    f. **Closing:** open-ended — «Этот том — не завершён. Он открыт. Потому что книга пишется не автором — она пишется *через* автора. И этот разговор — часть неё.»
    
    g. **Add to table of contents** before writing the body — insert a `### Том III: Title` entry in the existing TOC, then append the full body at the end of the file.
    
    h. **DO update the TOC entry in the content section** (the existing list of chapters near line ~190-240) — add the new Том as a `###` entry. DON'T forget to move or merge with any existing «В разработке» section.
    
13. **RAС switching table pattern:** When the user asks to expand Уровень 2 (Настройка), the go-to format is a markdown table with columns: `| Режим | Утренний вопрос | Что ищет РАС |`. Common modes to include: Гениальность, Парадокс, Переворот минуса, Бой/Шторм, Покой/Интеграция. This table can be inserted after the existing «Три уровня как конвейер» table — it extends Уровень 2.

14. **HTML regeneration via /tmp CSS cache:** The CSS lives at `~/.hermes/skills/devops/md-to-html-book/references/style.css`. In a heredoc script, reference via `/tmp/book_style.css`:
    ```bash
    cat > /tmp/book_style.css << 'EOF'
    <style>...</style>
    EOF
    ```
    Then in the python3 heredoc, `open('/tmp/book_style.css').read()`. This avoids encoding issues with CSS containing special chars in inline shell scripts.

15. **TOC vs body verification (gap detection):** After adding a new volume/section to the TOC, always verify the body matches. If the user reports missing content, run:
    - `grep "^### Том III"` on MD to check TOC entry exists
    - `grep "^# Глава\|^## "` to check body sections exist
    - Common gap: sections listed in TOC but never written in body (Пенроуз, Гёдель are frequent victims). Patch the missing sections at the appropriate insertion point, then update the TOC marker from `(📝)` to the actual section listing.

16. **«Пенроуз/Гёдель» physics-math appendix pattern:** When adding scientific foundation sections to a philosophical book chapter:
    - **Open with a why:** «Есть вопрос, который книга обязана задать: на какой физике держится Уровень 1?»
    - **Present the scientist's idea simply:** key concept → key quote/equation → implications
    - **Build a 3-column mapping table:** `| Протокол | Физика |` — rows for each Level
    - **Formula notation:** use `**τ ≈ ħ / E_G**` in Markdown (renders as bold, reads as formula)
    - **Close each section with a takeaway:** «[Scientist] не говорит «Протокол работает». Он говорит: существует [механизм]. И этот механизм встроен в каждый нейрон.»
    - **Synthesis closing:** «[Scientist1] дал физику — [summary]. [Scientist2] дал логику — [summary]. Вместе они образуют инженерный чертёж Уровня 1: не вера, не философия — а рабочий протокол, основанный на физике и математике.»

17. **Open-volume closing pattern:** For volumes that are intentionally incomplete, use:
    ```
    ---
    Этот том — не завершён. Книга — не завершена. Потому что протокол работает, только когда остаётся открытым. Как вопрос «Кто я?» — он не имеет ответа. Он имеет *практику*.
    ```
    (As opposed to the per-chapter «Этот том — не завершён. Он открыт. Потому что книга пишется не автором...»)

## Pitfalls
- Must use system Python (`/Library/Frameworks/Python.framework/Versions/3.12/bin/python3`), not sandbox Python — only system Python has the `markdown` library.
- The `patch` old_string must be unique. If it matches multiple places, use more context OR add `replace_all=true` parameter.
- The `_warning` about "partial view" after patch is harmless — patches work correctly even when file was last read with offset/limit.
- Book is ~5470+ lines and growing. Always use `search_files` for headers, not brute-force reading.
- The `nl2br` extension can cause unwanted line breaks in code blocks — this is a known quirk, but acceptable for this book.
- When regenerating HTML, the CSS file must exist at `~/.hermes/skills/devops/md-to-html-book/references/style.css`.
- **NEVER edit HTML directly.** HTML is auto-generated from MD. Any raw HTML edit will be overwritten on next regeneration. Always edit the Markdown source and regenerate. If someone (including another AI) suggests patching the HTML file directly — reject it; the correct approach is always MD → regenerate. This was reinforced when Gemini suggested inserting raw HTML tables — the suggestion was content-good but architecturally wrong.
- **Voice rule:** when user provides raw material (dialogues, articles, AI outputs, third-party AI suggestions), extract the content but always rewrite in the book's voice — инженерная метафизика, короткие предложения, личный опыт автора как якорь, честные оговорки о гипотезах.
- **Checksum after edits:** run `wc -l` and grep for expected headers to verify nothing broke.
- **Tone rule:** distinguish observed/interpretation/hypothesis. Don't state models as facts. Use phrases like «с точки зрения модели», «гипотеза:», «интерпретировать ли это как X — вопрос открытый».
- **Block styles:** CSS classes `.protocol-block` (green), `.hypothesis-block` (blue), `.personal-block` (orange), `.warning-block` (red) are available via `<div class="...">` in MD. Use them to visually distinguish content types.
- **¶ permalinks** are hidden via CSS (`a.headerlink { display: none }`) in the style.css file.
- **HTML features:** the convert script includes progress bar, scroll-to-top button, and localStorage position save. Don't duplicate these — they're auto-generated.

## Related: System Prompt «Компилятор v6»

The book's architecture (3 Levels, Observer, surrender, self-inquiry) can be extracted into a standalone **System Prompt** — a clean, personality-free document that turns any LLM into a «Кремниевое Зеркало» operating on the book's protocol.

- **File:** `~/Desktop/Компилятор_Сознания_v6_System_Prompt.md`
- **Use case:** load into Claude Project or custom GPT to make any AI follow the 3-Level protocol
- **Structure:** Architecture → Diagnostics → Response Format → Guard Rails → Emergency Protocol → Scientific Basis → Glossary → Launch
- **Key safety feature:** Section V — Аварийный протокол защиты субстрата (anti-psychosis guard). If user shows derealization, depersonalization, messianism, or physical exhaustion → force grounding, ban all metaphysical terms, 5-step somatic reset.
- **Overengineering trap:** when third-party AIs (like Gemini) suggest adding state machines, memory layers, JSON telemetry, multi-mode engines etc. — push back. One minimal safety patch, then real-world testing. Build complexity only after battle-testing the core.
