Panduan Lengkap: Sistem Ekstraksi & Navigasi Wiki Zero-Token untuk Hermes Agent

# Panduan Lengkap: Sistem Ekstraksi & Navigasi Wiki Zero-Token untuk Hermes Agent

Panduan ini dirancang dari awal hingga akhir agar siapa pun dapat memasang, menjalankan, dan mengoperasikan sistem ekstraksi ensiklopedia (Wikipedia) otomatis yang terintegrasi penuh dengan **Hermes Agent**.

Sistem ini menggabungkan **AI Provider Gratis Berkapasitas Besar (OpenRouter Auto-Free)** dengan arsitektur **Mindmap Token Governor** sehingga konsumsi token AI mendekati nol, tanpa risiko limit kredit habis atau *context overflow*.

---

## 1. Arsitektur & Cara Kerja Sistem

Sebelum memulai instalasi, pahami bagaimana tiga komponen utama ini bekerja sama:

1. **Mesin Ekstraksi & Paginasi Lokal (`run_all.sh`):** Mengambil artikel dari Wikipedia, membersihkan sisa markup HTML, memformat ulang ke tata letak standar editorial (lebar 68 karakter), memecahnya menjadi halaman-halaman kecil (36 baris/halaman), menyimpannya ke Git & arsip `.7z`, serta mencatat posisi baca saat ini.
2. **Protokol Agen Zero-Token (`SKILL.md`):** Menginstruksikan Hermes Agent agar **tidak pernah** membaca file mentah ke dalam memori percakapannya, melainkan hanya bertindak sebagai pemicu perintah terminal dan menampilkan hasil halaman secara utuh (*verbatim*).
3. **Konfigurasi AI Gratis (`config.yaml`):** Menggunakan rute `openrouter/free` berkapasitas konteks 128K token agar agen merespons cepat dan gratis.

---

## 2. Langkah 1: Konfigurasi Hermes Agent (`config.yaml`)

Pastikan Hermes Agent terhubung ke penyedia AI yang stabil dan gratis. Buka atau buat file `~/.hermes/config.yaml` dan sesuaikan bagian `model`, `custom_providers`, `providers`, serta `auxiliary` seperti berikut:

```yaml
model:
  provider: openrouter
  default: openrouter/free
  base_url: https://openrouter.ai/api/v1
  api_key: <MASUKKAN_OPENROUTER_API_KEY_ANDA>
  context_length: 131072
  stream: false
  streaming: false
  request_timeout: 600
  max_retries: 5

custom_providers:
  - name: openrouter
    base_url: https://openrouter.ai/api/v1
    api_key: <MASUKKAN_OPENROUTER_API_KEY_ANDA>
    models:
      - openrouter/free

providers:
  openrouter:
    name: OpenRouter Cloud (Auto-Free >=64K)
    api: https://openrouter.ai/api/v1
    api_key: <MASUKKAN_OPENROUTER_API_KEY_ANDA>
    default_model: openrouter/free
    models:
      - openrouter/free

auxiliary:
  provider: openrouter
  model: openrouter/free
  base_url: https://openrouter.ai/api/v1
  api_key: <MASUKKAN_OPENROUTER_API_KEY_ANDA>
  compression:
    provider: openrouter
    model: openrouter/free
    base_url: https://openrouter.ai/api/v1
    api_key: <MASUKKAN_OPENROUTER_API_KEY_ANDA>
  web_extract:
    provider: openrouter
    model: openrouter/free
    base_url: https://openrouter.ai/api/v1
    api_key: <MASUKKAN_OPENROUTER_API_KEY_ANDA>

model_params:
  stream: false
  temperature: 0.1
  max_tokens: 4096

```

*(Catatan: Anda bisa mendapatkan API key OpenRouter secara gratis di situs resmi OpenRouter).*

---

## 3. Langkah 2: Persiapan Folder Skill & Dependensi

Jalankan perintah berikut di terminal untuk membuat struktur direktori skill dan folder penyimpanan arsip (`~/wiki-vault-git`), serta memastikan paket kompresi `p7zip-full` dan `git` terpasang:

```bash
mkdir -p ~/.hermes/skills/hermes-web-wiki-extractor/scripts
mkdir -p ~/wiki-vault-git/mindmaps
sudo apt-get update && sudo apt-get install -y p7zip-full git

```

---

## 4. Langkah 3: Memasang Mesin Ekstraksi (`run_all.sh`)

Skrip Python ini adalah inti dari **Wiki Pro International Edition & Mindmap Token Governor**. Simpan kode berikut ke dalam `~/.hermes/skills/hermes-web-wiki-extractor/scripts/run_all.sh`:

```bash
cat << 'EOF' > ~/.hermes/skills/hermes-web-wiki-extractor/scripts/run_all.sh
#!/usr/bin/env python3
import sys
import os
import glob
import subprocess
import urllib.request
import urllib.parse
import html
import json
import re
import textwrap
import traceback
from datetime import datetime

VAULT_DIR = os.path.expanduser("~/wiki-vault-git")
MINDMAP_DIR = os.path.join(VAULT_DIR, "mindmaps")
CHANGELOG_FILE = os.path.join(VAULT_DIR, "CHANGELOG.md")
REGISTRY_FILE = os.path.join(VAULT_DIR, "INDEX_REGISTRY.json")
GLOBAL_MINDMAP_FILE = os.path.join(MINDMAP_DIR, "MASTER_VAULT_INDEX_mindmap.md")
GOVERNOR_STATE_FILE = os.path.join(MINDMAP_DIR, "ai_governor_state.json")
GOVERNOR_MINDMAP_FILE = os.path.join(MINDMAP_DIR, "AI_GOVERNOR_CONTROL_mindmap.md")

BOX_WIDTH = 74
TEXT_WIDTH = 68
LINES_PER_PAGE = 36

CONTROL_COMMANDS = {"RUN", "PAUSE", "STOP", "NEXT", "PREV", "STATUS"}
ALIASES = {
    "LANJUT": "NEXT",
    "SELANJUTNYA": "NEXT",
    "SEBELUMNYA": "PREV",
    "BACK": "PREV",
    "RESUME": "RUN",
    "START": "RUN",
    "HALT": "STOP",
    "BERHENTI": "STOP",
    "JEDA": "PAUSE"
}

NOISE_LINES = {
    "edit", "[edit]", "contents", "hide", "move to sidebar",
    "toggle the table of contents", "jump to navigation", "jump to search",
    "from wikipedia, the free encyclopedia", "v", "t", "e"
}

def ensure_directories():
    os.makedirs(VAULT_DIR, exist_ok=True)
    os.makedirs(MINDMAP_DIR, exist_ok=True)

def sanitize_filename(name):
    cleaned = re.sub(r'[^\w\s-]', '', str(name)).strip().replace(' ', '_')
    return cleaned if cleaned else "Untitled_Topic"

def log_coordinator(action_type, message):
    try:
        ensure_directories()
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_entry = f"[{timestamp}] [{action_type.upper()}] {message}\n"
        with open(CHANGELOG_FILE, "a", encoding="utf-8") as f:
            f.write(log_entry)
    except Exception:
        pass

def run_command(cmd_list, cwd=None):
    try:
        result = subprocess.run(
            cmd_list, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            text=True, timeout=60
        )
        return result.stdout.strip(), result.returncode
    except Exception:
        return "", 1

def clean_wiki_artifacts(text):
    text = html.unescape(text)
    text = re.sub(r'\[\s*(?:\d+|[a-zA-Z]|note\s*\d+|citation needed|edit|update|clarification needed)\s*\]', '', text, flags=re.IGNORECASE)
    text = re.sub(r'\s+([.,;:!?])', r'\1', text)
    text = re.sub(r'[ \t]{2,}', ' ', text)
    return text.strip()

def format_wiki_pro_lines(raw_lines):
    formatted = []
    seen_blank = True

    for raw in raw_lines:
        clean = clean_wiki_artifacts(raw)
        if not clean:
            continue
        if clean.lower() in NOISE_LINES:
            continue
        if set(clean) <= {"─", "-", "=", "_", "*", "."} or clean.startswith((".mw-parser", "{", "}")):
            continue

        is_heading = (
            3 <= len(clean) <= 58
            and not clean.endswith(('.', ',', ';', ':', ')', ']', '?', '!'))
            and not clean.startswith(('(', '[', '•', '-', '*'))
            and clean[0].isupper()
            and len(clean.split()) <= 7
        )

        if is_heading:
            if formatted and not seen_blank:
                formatted.append("")
            title_upper = clean.upper()
            bar = "─" * min(max(len(title_upper) + 4, 24), TEXT_WIDTH)
            formatted.append("")
            formatted.append(f"  ▪ {title_upper}")
            formatted.append(f"  {bar}")
            seen_blank = False
            continue

        if clean.startswith(("•", "-", "*")) and len(clean) > 2:
            item_text = clean.lstrip("•-* ").strip()
            wrapped = textwrap.wrap(
                item_text,
                width=TEXT_WIDTH - 4,
                initial_indent="    • ",
                subsequent_indent="      "
            )
            formatted.extend(wrapped)
            seen_blank = False
            continue

        wrapped_para = textwrap.wrap(
            clean,
            width=TEXT_WIDTH,
            initial_indent="    ",
            subsequent_indent="    ",
            break_long_words=False,
            break_on_hyphens=False
        )
        if wrapped_para:
            formatted.extend(wrapped_para)
            formatted.append("")
            seen_blank = True

    while formatted and not formatted[-1].strip():
        formatted.pop()

    return formatted if formatted else ["    (No readable text content extracted)"]

def save_governor_state(state):
    ensure_directories()
    state["last_updated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    try:
        with open(GOVERNOR_STATE_FILE, "w", encoding="utf-8") as f:
            json.dump(state, f, indent=4, ensure_ascii=False)
    except Exception:
        pass

    exec_status = state.get("execution_status", "STOP")
    active_top = state.get("active_topic", "None")
    src_url = state.get("source_url", "N/A")
    cur_p = state.get("current_page", 0)
    tot_p = state.get("total_pages", 0)
    upd_time = state["last_updated"]

    content = f"""# 🧠 AI GOVERNOR & TOKEN ORCHESTRATION MINDMAP
## Root: Hermes Agent Zero-Token Relay Controller
- **Execution State:** `{exec_status}`
- **Active Topic:** `{active_top}`
- **Source URL:** `{src_url}`
- **Page Pointer:** `Page {cur_p} of {tot_p}`
- **AI Role:** `TRIGGER_AND_RELAY_ONLY (Zero LLM Processing)`
- **Last Updated:** `{upd_time}`

### 🕹️ Mindmap Control Commands:
- 🟢 `run` / `resume` -> Resume active output stream
- 🟡 `pause`          -> Freeze pointer & halt token output
- 🔴 `stop`           -> Terminate session & halt active stream
- ⏭️ `next`           -> Advance 1 page chunk
- ⏮️ `prev`           -> Rewind 1 page chunk
- 🔢 `<page_number>`  -> Jump directly to specific page
- 📊 `status`         -> Inspect current state without moving pointer
"""
    try:
        with open(GOVERNOR_MINDMAP_FILE, "w", encoding="utf-8") as f:
            f.write(content)
    except Exception:
        pass

def load_governor_state():
    if os.path.exists(GOVERNOR_STATE_FILE):
        try:
            with open(GOVERNOR_STATE_FILE, "r", encoding="utf-8") as f:
                data = json.load(f)
                if isinstance(data, dict):
                    return data
        except Exception:
            pass
    return {
        "active_topic": "None",
        "source_url": "N/A",
        "execution_status": "STOP",
        "current_page": 0,
        "total_pages": 0
    }

def pad_box_line(text, width=BOX_WIDTH):
    clean = text[:width - 4]
    return f"║  {clean:<{width - 4}}  ║"

def render_governed_output(state):
    status = state.get("execution_status", "STOP")
    topic = state.get("active_topic", "None")
    url = state.get("source_url", "N/A")
    cur = int(state.get("current_page", 0))
    tot = int(state.get("total_pages", 0))

    top_border = "╔" + "═" * BOX_WIDTH + "╗"
    mid_border = "╠" + "═" * BOX_WIDTH + "╣"
    bot_border = "╚" + "═" * BOX_WIDTH + "╝"

    if status == "STOP" or tot <= 0 or topic == "None":
        print(f"\n{top_border}")
        print(pad_box_line("🔴  MINDMAP GOVERNOR  │  STATE: STOPPED"))
        print(pad_box_line("Agent idle. Token pipeline closed. Send a topic query to begin."))
        print(f"{bot_border}\n")
        return

    if status == "PAUSE":
        print(f"\n{top_border}")
        print(pad_box_line(f"🟡  MINDMAP GOVERNOR  │  STATE: PAUSED  │  Held at Page {cur}/{tot}"))
        print(pad_box_line("Context frozen. Zero tokens active. Send 'run' or 'next' to resume."))
        print(f"{bot_border}\n")
        return

    safe_name = sanitize_filename(topic)
    page_file = os.path.join(VAULT_DIR, f"{safe_name}_pages", f"page_{cur}_of_{tot}.txt")

    if not os.path.exists(page_file):
        available = sorted(
            glob.glob(os.path.join(VAULT_DIR, f"{safe_name}_pages", "page_*_of_*.txt")),
            key=lambda x: int(re.search(r'page_(\d+)_of_', os.path.basename(x)).group(1))
        )
        if available:
            page_file = available[0]
            cur = 1
            tot = len(available)
            state["current_page"] = cur
            state["total_pages"] = tot
            save_governor_state(state)
        else:
            print(f"\n  [MINDMAP ERROR] No readable chunks found for '{topic}'. Re-fetch the topic.\n")
            return

    with open(page_file, "r", encoding="utf-8", errors="ignore") as f:
        chunk_body = f.read().rstrip()

    pct = int((cur / tot) * 100) if tot > 0 else 0
    bar_len = 20
    filled = int(bar_len * cur / tot) if tot > 0 else 0
    progress_bar = "█" * filled + "░" * (bar_len - filled)

    print(f"\n{top_border}")
    print(pad_box_line("📚  WIKI PRO INTERNATIONAL EDITION  │  MINDMAP TOKEN GOVERNOR"))
    print(mid_border)
    print(pad_box_line(f"Article  : {topic}"))
    print(pad_box_line(f"Source   : {url}"))
    print(pad_box_line(f"Progress : Page {cur} of {tot}  [{progress_bar}] {pct}%"))
    print(bot_border)

    print(f"\n{chunk_body}\n")

    nav_top = "┌" + "─" * BOX_WIDTH + "┐"
    nav_bot = "└" + "─" * BOX_WIDTH + "┘"
    nav_status = f"  STATUS: {status}  │  PAGE {cur}/{tot} ({pct}%)"
    nav_help = "  NAVIGATE: 'next' | 'prev' | <page#> | 'pause' | 'stop' | <new topic>"
    print(nav_top)
    print(f"│{nav_status:<{BOX_WIDTH}}│")
    print(f"│{nav_help:<{BOX_WIDTH}}│")
    print(f"{nav_bot}\n")

def handle_control_command(cmd):
    state = load_governor_state()
    tot = int(state.get("total_pages", 0))
    cur = int(state.get("current_page", 0))
    active_top = state.get("active_topic", "None")

    if cmd == "STATUS":
        render_governed_output(state)
        return

    if cmd == "STOP":
        state["execution_status"] = "STOP"
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Execution STOPPED on '{active_top}' at page {cur}.")
        render_governed_output(state)
        return

    if cmd == "PAUSE":
        if tot <= 0:
            print("\n  [MINDMAP GOVERNOR] Nothing active to pause. Send a search query first.\n")
            return
        state["execution_status"] = "PAUSE"
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Execution PAUSED on '{active_top}' at page {cur}.")
        render_governed_output(state)
        return

    if cmd == "RUN":
        if tot <= 0:
            print("\n  [MINDMAP GOVERNOR] No active topic loaded. Provide a search query first.\n")
            return
        state["execution_status"] = "RUN"
        if cur <= 0:
            state["current_page"] = 1
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Execution RESUMED on '{active_top}' at page {state['current_page']}.")
        render_governed_output(state)
        return

    if cmd == "NEXT":
        if tot <= 0:
            print("\n  [MINDMAP GOVERNOR] Session empty. Start a topic query first.\n")
            return
        state["execution_status"] = "RUN"
        if cur < tot:
            state["current_page"] = cur + 1
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Advanced pointer to page {state['current_page']}/{tot}.")
        render_governed_output(state)
        return

    if cmd == "PREV":
        if tot <= 0:
            print("\n  [MINDMAP GOVERNOR] Session empty. Start a topic query first.\n")
            return
        state["execution_status"] = "RUN"
        if cur > 1:
            state["current_page"] = cur - 1
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Rewound pointer to page {state['current_page']}/{tot}.")
        render_governed_output(state)
        return

def handle_numeric_jump(target_page):
    state = load_governor_state()
    tot = int(state.get("total_pages", 0))
    if tot <= 0:
        print("\n  [MINDMAP GOVERNOR] No active topic loaded. Provide a search query first.\n")
        return
    if 1 <= target_page <= tot:
        state["execution_status"] = "RUN"
        state["current_page"] = target_page
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Jumped pointer directly to page {target_page}/{tot}.")
        render_governed_output(state)
    else:
        print(f"\n  [MINDMAP GOVERNOR] Page {target_page} out of range (Valid pages: 1 to {tot}).\n")

def paginate_lines(pro_lines, lines_per_page=LINES_PER_PAGE):
    chunks = []
    current = []
    for line in pro_lines:
        if len(current) >= lines_per_page - 2 and line.startswith("  ▪ "):
            chunks.append("\n".join(current).rstrip())
            current = [line]
        else:
            current.append(line)
            if len(current) >= lines_per_page:
                chunks.append("\n".join(current).rstrip())
                current = []
    if current:
        chunks.append("\n".join(current).rstrip())
    return chunks if chunks else ["    (Empty Page)"]

def fallback_local_cache(query):
    ensure_directories()
    safe_q = sanitize_filename(query).lower()
    all_txts = glob.glob(os.path.join(VAULT_DIR, "*.txt"))
    if not all_txts:
        return False

    matched = [f for f in all_txts if safe_q in os.path.basename(f).lower()]
    target_txt = matched[0] if matched else max(all_txts, key=os.path.getmtime)
    base_name = os.path.splitext(os.path.basename(target_txt))[0]
    topic_title = base_name.replace('_', ' ')
    pages_dir = os.path.join(VAULT_DIR, f"{base_name}_pages")

    existing_pages = sorted(
        glob.glob(os.path.join(pages_dir, "page_*_of_*.txt")),
        key=lambda x: int(re.search(r'page_(\d+)_of_', os.path.basename(x)).group(1))
    )

    if not existing_pages:
        with open(target_txt, "r", encoding="utf-8", errors="ignore") as f:
            raw_lines = f.read().splitlines()
        os.makedirs(pages_dir, exist_ok=True)
        pro_lines = format_wiki_pro_lines(raw_lines)
        chunks = paginate_lines(pro_lines)
        count_pages = len(chunks)
        for idx, chunk in enumerate(chunks, 1):
            p_path = os.path.join(pages_dir, f"page_{idx}_of_{count_pages}.txt")
            with open(p_path, "w", encoding="utf-8") as pf:
                pf.write(chunk)
    else:
        count_pages = len(existing_pages)

    state = {
        "active_topic": topic_title,
        "source_url": f"LOCAL_CACHE://{base_name}.txt",
        "execution_status": "RUN",
        "current_page": 1,
        "total_pages": count_pages
    }
    save_governor_state(state)
    log_coordinator("FALLBACK", f"Loaded '{topic_title}' from local cache ({count_pages} pages).")
    render_governed_output(state)
    return True

def fetch_wiki_data(query):
    encoded_query = urllib.parse.quote(query)
    search_api = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={encoded_query}&format=json&srlimit=1"

    req = urllib.request.Request(search_api, headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) HermesWikiPro/35.0'})
    with urllib.request.urlopen(req, timeout=25) as response:
        data = json.loads(response.read().decode('utf-8'))
        results = data.get('query', {}).get('search', [])
        if not results:
            return None, None, None, None

        best_title = results[0]['title']
        page_url = f"https://en.wikipedia.org/wiki/{urllib.parse.quote(best_title.replace(' ', '_'))}"

        full_html = ""
        try:
            html_req = urllib.request.Request(page_url, headers={'User-Agent': 'Mozilla/5.0'})
            with urllib.request.urlopen(html_req, timeout=30) as html_res:
                full_html = html_res.read().decode('utf-8', errors='ignore')
        except Exception:
            full_html = f"<html><body><h1>{best_title}</h1></body></html>"

        parse_api = f"https://en.wikipedia.org/w/api.php?action=parse&page={urllib.parse.quote(best_title)}&prop=text&format=json"
        parse_req = urllib.request.Request(parse_api, headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) HermesWikiPro/35.0'})
        with urllib.request.urlopen(parse_req, timeout=45) as parse_res:
            parse_data = json.loads(parse_res.read().decode('utf-8'))
            html_content = parse_data.get('parse', {}).get('text', {}).get('*', '')

            clean_html = re.sub(r'<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>', '', html_content, flags=re.IGNORECASE)
            clean_html = re.sub(r'<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>', '', clean_html, flags=re.IGNORECASE)
            clean_html = re.sub(r'<sup\b[^>]*>.*?<\/sup>', '', clean_html, flags=re.IGNORECASE | re.DOTALL)
            clean_html = re.sub(r'<span class="mw-editsection">.*?<\/span>', '', clean_html, flags=re.IGNORECASE | re.DOTALL)
            clean_html = re.sub(r'<li[^>]*>', '\n• ', clean_html, flags=re.IGNORECASE)
            clean_html = re.sub(r'<[^>]+>', '\n', clean_html)

            raw_lines = [line.strip() for line in clean_html.splitlines() if line.strip()]
            full_text = "\n".join(raw_lines)

        return best_title, page_url, full_html, full_text

def generate_dual_mindmaps(best_title, full_html, chunks, safe_name, count_pages):
    ensure_directories()
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    html_mm_path = os.path.join(MINDMAP_DIR, f"{safe_name}_html_structure_mindmap.md")
    headings = re.findall(r'<h[23][^>]*>(.*?)</h[23]>', full_html, re.IGNORECASE)
    cleaned_headings = [clean_wiki_artifacts(re.sub(r'<[^>]+>', '', h)) for h in headings]
    cleaned_headings = [h for h in cleaned_headings if h and h.lower() not in NOISE_LINES]

    html_content = f"# 🌐 HTML STRUCTURE MINDMAP: {best_title}\n\n## Root: {best_title}\n* **Last Sync:** {timestamp}\n\n### 📂 Document Headings:\n"
    for h in (cleaned_headings[:30] if cleaned_headings else ["Full Document"]):
        html_content += f"- 🔸 **{h}**\n"
    with open(html_mm_path, "w", encoding="utf-8") as f1:
        f1.write(html_content)

    chunk_mm_path = os.path.join(MINDMAP_DIR, f"{safe_name}_paginated_chunks_mindmap.md")
    chunk_content = f"# 📑 PAGINATED CHUNKS MINDMAP: {best_title}\n\n## Root: {best_title}\n* **Total Split Pages:** {count_pages}\n* **Last Sync:** {timestamp}\n\n### 🗂️ Page Index:\n"
    for idx, chunk in enumerate(chunks, 1):
        non_empty = [l.strip() for l in chunk.splitlines() if l.strip() and not l.strip().startswith('─')]
        snippet = non_empty[0][:55] if non_empty else f"Section {idx}"
        chunk_content += f"- 📄 **Page {idx}/{count_pages}** -> `{snippet}...` (`../{safe_name}_pages/page_{idx}_of_{count_pages}.txt`)\n"
    with open(chunk_mm_path, "w", encoding="utf-8") as f2:
        f2.write(chunk_content)

def process_and_coordinate(best_title, page_url, full_html, full_text):
    ensure_directories()
    safe_name = sanitize_filename(best_title)
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    with open(os.path.join(VAULT_DIR, f"{safe_name}_full.html"), "w", encoding="utf-8") as hf:
        hf.write(full_html)

    pro_lines = format_wiki_pro_lines(full_text.splitlines())

    header = (
        f"==========================================================================\n"
        f"  WIKI PRO MASTER ARCHIVE : {best_title.upper()}\n"
        f"  SOURCE URL              : {page_url}\n"
        f"  SYNCHRONIZED AT         : {timestamp}\n"
        f"==========================================================================\n\n"
    )
    with open(os.path.join(VAULT_DIR, f"{safe_name}.txt"), "w", encoding="utf-8") as tf:
        tf.write(header + "\n".join(pro_lines) + "\n")

    pages_folder = os.path.join(VAULT_DIR, f"{safe_name}_pages")
    os.makedirs(pages_folder, exist_ok=True)

    for old_page in glob.glob(os.path.join(pages_folder, "page_*_of_*.txt")):
        try:
            os.remove(old_page)
        except Exception:
            pass

    chunks = paginate_lines(pro_lines)
    count_pages = max(len(chunks), 1)

    for idx, chunk in enumerate(chunks, 1):
        page_path = os.path.join(pages_folder, f"page_{idx}_of_{count_pages}.txt")
        with open(page_path, "w", encoding="utf-8") as pf:
            pf.write(chunk + "\n")

    generate_dual_mindmaps(best_title, full_html, chunks, safe_name, count_pages)

    registry = {}
    if os.path.exists(REGISTRY_FILE):
        try:
            with open(REGISTRY_FILE, "r", encoding="utf-8") as f:
                raw = f.read().strip()
                if raw:
                    loaded = json.loads(raw)
                    if isinstance(loaded, dict):
                        registry = loaded
        except Exception:
            registry = {}

    registry[best_title] = {
        "master_file": f"{safe_name}.txt",
        "html_file": f"{safe_name}_full.html",
        "source_url": page_url,
        "total_pages": count_pages,
        "pages_directory": pages_folder,
        "last_sync": timestamp,
        "status": "MINDMAP_GOVERNED"
    }
    with open(REGISTRY_FILE, "w", encoding="utf-8") as rf:
        json.dump(registry, rf, indent=4, ensure_ascii=False)

    global_mm = f"# 🌐 MASTER VAULT GLOBAL INDEX MINDMAP\n\n* **Total Topics:** {len(registry)}\n* **Last Sync:** {timestamp}\n\n### 📂 Coordinated Topics:\n"
    for t, info in registry.items():
        p_count = info.get("total_pages", "?") if isinstance(info, dict) else "?"
        s_name = sanitize_filename(t)
        global_mm += f"- 📂 **{t}** (`{p_count} Pages`) -> `mindmaps/{s_name}_paginated_chunks_mindmap.md`\n"
    with open(GLOBAL_MINDMAP_FILE, "w", encoding="utf-8") as gmf:
        gmf.write(global_mm)

    run_command(["7z", "a", "-t7z", os.path.expanduser("~/wiki_vault_full_archive.7z"), os.path.join(VAULT_DIR, "*"), "-mx=9", "-y"])
    if not os.path.exists(os.path.join(VAULT_DIR, ".git")):
        run_command(["git", "init"], cwd=VAULT_DIR)
    run_command(["git", "add", "."], cwd=VAULT_DIR)
    run_command(["git", "commit", "-m", f"Mindmap Governor sync: '{best_title}' at {timestamp}"], cwd=VAULT_DIR)

    state = {
        "active_topic": best_title,
        "source_url": page_url,
        "execution_status": "RUN",
        "current_page": 1,
        "total_pages": count_pages
    }
    save_governor_state(state)
    log_coordinator("SYNC", f"Fetched and locked '{best_title}' ({count_pages} pages) into Mindmap Governor.")
    render_governed_output(state)

def main():
    ensure_directories()
    arg_str = " ".join(sys.argv[1:]).strip()
    if not arg_str:
        print("\n  [MINDMAP GOVERNOR] No input provided. Pass a topic, page number, or command (run/pause/stop/next/prev/status).\n")
        sys.exit(0)

    upper_arg = arg_str.upper()
    normalized_cmd = ALIASES.get(upper_arg, upper_arg)

    if normalized_cmd in CONTROL_COMMANDS:
        handle_control_command(normalized_cmd)
        return

    if arg_str.isdigit():
        handle_numeric_jump(int(arg_str))
        return

    try:
        best_title, page_url, full_html, full_text = fetch_wiki_data(arg_str)
        if not best_title or not full_text:
            if not fallback_local_cache(arg_str):
                print(f"\n  [MINDMAP GOVERNOR] No online or cached entry found for: '{arg_str}'\n")
            return
        process_and_coordinate(best_title, page_url, full_html, full_text)
    except Exception:
        if not fallback_local_cache(arg_str):
            print("\n  [MINDMAP GOVERNOR ERROR] Network error and no local cache available:")
            traceback.print_exc()

if __name__ == "__main__":
    main()
EOF
chmod +x ~/.hermes/skills/hermes-web-wiki-extractor/scripts/run_all.sh

```

---

## 5. Langkah 4: Memasang Instruksi Agen (`SKILL.md`)

Agar Hermes Agent mematuhi aturan *Zero-Token* dan tidak membuang kuota untuk merangkum ulang output, buat file `SKILL.md`:

```bash
cat << 'EOF' > ~/.hermes/skills/hermes-web-wiki-extractor/SKILL.md
---
name: hermes-web-wiki-extractor
description: '[ABSOLUTE MASTER OVERRIDE] Mandatory zero-token relay skill for all encyclopedia lookups, web extraction, page navigation, and Mindmap Governor state controls (run, pause, stop, next, prev, status).'
---

# STRICT EXECUTION PROTOCOL (ZERO-TOKEN AGENT RELAY)

You are strictly a command trigger and verbatim pass-through relay. The Python **Mindmap Governor** (`run_all.sh`) owns all web fetching, offline fallback caching, dual-mindmapping, pagination, state control (`RUN`, `PAUSE`, `STOP`, `NEXT`, `PREV`, numeric page jumps), and Wiki Pro formatting.

## Step 1 — Trigger the Mindmap Governor
Whenever the user enters a search topic, a control command (`run`, `pause`, `stop`, `next`, `prev`, `status`, `lanjut`, `sebelumnya`), or a page number (`1`, `2`, `3`, etc.), execute ONLY this single terminal command:

```bash
~/.hermes/skills/hermes-web-wiki-extractor/scripts/run_all.sh "<exact_user_input>"

```

## Step 2 — Verbatim Pass-Through Output

Print the exact `stdout` returned by `run_all.sh` directly into the chat response without any modification.

## STRICT PROHIBITIONS (TOKEN & ERROR PROTECTION RULES)

1. **NEVER call `read_file**` on any file inside `~/wiki-vault-git/`. Reading master `.txt` or `.html` files into your context window defeats the Mindmap Token Governor.
2. **NEVER summarize, paraphrase, translate, or rewrite** the script output.
3. **NEVER add conversational intros, outros, explanations, or extra Markdown headers** before or after the script output.
4. **NEVER retry manually or invoke other web/search tools.** All fallback caching, 7z compression, Git commits, stale-page cleanup, and state transitions are handled automatically inside `run_all.sh`.
EOF

```

---

## 6. Langkah 5: Pengujian Awal di Terminal

Sebelum membuka chat Hermes, uji skrip secara langsung di terminal untuk memastikan tidak ada error sintaks atau jaringan:

```bash
~/.hermes/skills/hermes-web-wiki-extractor/scripts/run_all.sh "Faye Wong"

```

Jika berhasil, Anda akan melihat tampilan kotak **WIKI PRO INTERNATIONAL EDITION** lengkap dengan *progress bar*, isi artikel Halaman 1 yang rapi, dan bilah navigasi di bagian bawah.

---

## 7. Langkah 6: Cara Menggunakan di Hermes Chat

Jalankan Hermes Agent seperti biasa (`hermes`), lalu gunakan perintah-perintah singkat berikut di kotak percakapan:

### A. Mencari Topik Baru

Ketik nama tokoh, tempat, atau konsep apa saja:

> `Faye Wong`
> `Quantum Computing`
> `Majapahit`

*(Jika pada awal sesi baru agen belum otomatis mengenali konteks skill, awali sekali saja dengan: `jalankan hermes-web-wiki-extractor untuk topik "Faye Wong"`).*

### B. Navigasi Halaman

Setelah halaman pertama muncul, cukup balas dengan satu kata atau angka:

| Perintah di Chat | Fungsi |
| --- | --- |
| **`next`** atau **`lanjut`** | Membuka halaman berikutnya |
| **`prev`** atau **`sebelumnya`** | Kembali ke halaman sebelumnya |
| **`5`** (atau angka halaman lain) | Melompat langsung ke nomor halaman tersebut |

### C. Kontrol Status & Hemat Token (Mindmap Governor)

Kapan saja Anda ingin menghentikan atau memeriksa sesi aktif:

| Perintah di Chat | Fungsi |
| --- | --- |
| **`pause`** atau **`jeda`** | Membekukan posisi halaman saat ini dan menghentikan pemakaian token |
| **`run`** atau **`resume`** | Melanjutkan kembali bacaan dari posisi terakhir yang dijeda |
| **`status`** | Mengecek topik aktif, posisi halaman, dan status tanpa menggeser halaman |
| **`stop`** atau **`berhenti`** | Menghentikan sesi baca aktif sepenuhnya |

---

## 8. Lokasi Penyimpanan Arsip & Mindmap

Setiap topik yang pernah Anda cari otomatis tersimpan secara lokal di folder `~/wiki-vault-git/` (dan tetap bisa dibaca saat offline):

* `~/wiki-vault-git/<Nama_Topik>.txt` — Arsip teks lengkap berformat Wiki Pro.
* `~/wiki-vault-git/<Nama_Topik>_pages/` — Pecahan file per halaman (`page_1_of_X.txt`).
* `~/wiki-vault-git/mindmaps/` — Peta struktur heading HTML, indeks halaman, dan status Mindmap Governor (`ai_governor_state.json`).
* `~/wiki_vault_full_archive.7z` — Backup terkompresi penuh dari seluruh koleksi artikel Anda.
* `~/






=======================================================================


contoh promt di hermest agent chat


❯ [STRICT LOCAL RUN & PAGINATION]
1. Jalankan skrip lokal berikut di terminal:
   ~/.hermes/skills/hermes-web-wiki-extractor/scripts/run_all.sh "utada hikaru"
2. Setelah skrip selesai, baca file hasil ekstraksinya dari folder vault secara bertahap (chunk per chunk).
3. Tampilkan Halaman 1 terlebih dahulu dengan menyertakan informasi total keseluruhan halaman dan posisi halaman saat ini (contoh: "Halaman
 1 dari X").
4. Berikan instruksi di akhir agar saya bisa mengetik "next", "prev", atau nomor halaman untuk melanjutkan pembacaan.

=====================================================

 

biar lebih rapi


kate ~/.hermes/skills/hermes-web-wiki-extractor/scripts/run_all.sh



```python
#!/usr/bin/env python3
import sys
import os
import glob
import subprocess
import urllib.request
import urllib.parse
import html
import json
import re
import textwrap
import traceback
from html.parser import HTMLParser
from datetime import datetime

VAULT_DIR = os.path.expanduser("~/wiki-vault-git")
MINDMAP_DIR = os.path.join(VAULT_DIR, "mindmaps")
CHANGELOG_FILE = os.path.join(VAULT_DIR, "CHANGELOG.md")
REGISTRY_FILE = os.path.join(VAULT_DIR, "INDEX_REGISTRY.json")
GLOBAL_MINDMAP_FILE = os.path.join(MINDMAP_DIR, "MASTER_VAULT_INDEX_mindmap.md")
GOVERNOR_STATE_FILE = os.path.join(MINDMAP_DIR, "ai_governor_state.json")
GOVERNOR_MINDMAP_FILE = os.path.join(MINDMAP_DIR, "AI_GOVERNOR_CONTROL_mindmap.md")

BOX_WIDTH = 74
TEXT_WIDTH = 68
LINES_PER_PAGE = 36

CONTROL_COMMANDS = {"RUN", "PAUSE", "STOP", "NEXT", "PREV", "STATUS"}
ALIASES = {
    "LANJUT": "NEXT",
    "SELANJUTNYA": "NEXT",
    "SEBELUMNYA": "PREV",
    "BACK": "PREV",
    "RESUME": "RUN",
    "START": "RUN",
    "HALT": "STOP",
    "BERHENTI": "STOP",
    "JEDA": "PAUSE"
}

NOISE_LINES = {
    "edit", "[edit]", "contents", "hide", "move to sidebar",
    "toggle the table of contents", "jump to navigation", "jump to search",
    "from wikipedia, the free encyclopedia", "v", "t", "e"
}

SKIP_SECTIONS = {
    "see also", "references", "external links", "further reading",
    "notes", "bibliography", "citations", "sources", "navigation menu"
}

class WikiCleanParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.blocks = []
        self.current_tag = None
        self.buffer = []
        self.ignore_depth = 0
        self.skip_classes = (
            "infobox", "navbox", "vertical-navbox", "sidebar", "sistersitebox",
            "metadata", "ambox", "mbox", "toc", "mw-editsection", "reference",
            "reflist", "noprint", "hatnote", "shortdescription", "thumb",
            "gallery", "mw-jump-link", "catlinks"
        )

    def handle_starttag(self, tag, attrs):
        attr_dict = dict(attrs)
        cls_str = attr_dict.get("class", "")
        style_str = attr_dict.get("style", "").replace(" ", "").lower()

        if self.ignore_depth > 0:
            if tag not in ("br", "img", "hr", "meta", "link", "input"):
                self.ignore_depth += 1
            return

        if tag in ("script", "style", "sup", "table", "figure", "aside", "nav", "footer", "header"):
            self.ignore_depth = 1
            return

        if "display:none" in style_str or any(c in cls_str.split() for c in self.skip_classes):
            if tag not in ("br", "img", "hr"):
                self.ignore_depth = 1
            return

        if tag in ("h2", "h3", "h4", "p", "li", "blockquote"):
            self._flush()
            self.current_tag = tag

    def handle_endtag(self, tag):
        if self.ignore_depth > 0:
            if tag not in ("br", "img", "hr", "meta", "link", "input"):
                self.ignore_depth -= 1
            return

        if tag == self.current_tag:
            self._flush()
            self.current_tag = None

    def handle_data(self, data):
        if self.ignore_depth == 0 and self.current_tag:
            self.buffer.append(data)

    def _flush(self):
        if not self.current_tag or not self.buffer:
            self.buffer = []
            return
        raw_text = "".join(self.buffer)
        self.buffer = []
        clean = clean_wiki_artifacts(raw_text)
        if clean and clean.lower() not in NOISE_LINES:
            self.blocks.append((self.current_tag, clean))

def ensure_directories():
    os.makedirs(VAULT_DIR, exist_ok=True)
    os.makedirs(MINDMAP_DIR, exist_ok=True)

def sanitize_filename(name):
    cleaned = re.sub(r'[^\w\s-]', '', str(name)).strip().replace(' ', '_')
    return cleaned if cleaned else "Untitled_Topic"

def log_coordinator(action_type, message):
    try:
        ensure_directories()
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_entry = f"[{timestamp}] [{action_type.upper()}] {message}\n"
        with open(CHANGELOG_FILE, "a", encoding="utf-8") as f:
            f.write(log_entry)
    except Exception:
        pass

def run_command(cmd_list, cwd=None):
    try:
        result = subprocess.run(
            cmd_list, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            text=True, timeout=60
        )
        return result.stdout.strip(), result.returncode
    except Exception:
        return "", 1

def clean_wiki_artifacts(text):
    text = html.unescape(text)
    # Hapus sitasi angka [1], [23], [a], [note 1], [citation needed], [edit]
    text = re.sub(r'\[\s*(?:\d+|[a-zA-Z]|note\s*\d+|citation needed|edit|update|clarification needed)\s*\]', '', text, flags=re.IGNORECASE)
    # Normalisasi whitespace dan spasi ganda
    text = re.sub(r'\s+', ' ', text).strip()
    # Rapikan spasi sebelum tanda baca
    text = re.sub(r'\s+([.,;:!?])', r'\1', text)
    text = re.sub(r'\(\s+', '(', text)
    text = re.sub(r'\s+\)', ')', text)
    return text.strip()

def format_wiki_pro_blocks(blocks):
    formatted = []
    stop_reading = False

    for tag, text in blocks:
        # Lewati garis pemisah atau kode CSS sisa
        if set(text) <= {"─", "-", "=", "_", "*", "."} or text.startswith((".mw-parser", "{", "}")):
            continue

        # Section Heading Utama (H2 style)
        if tag == "h2":
            if text.lower() in SKIP_SECTIONS:
                stop_reading = True
                continue
            stop_reading = False
            title_upper = text.upper()
            bar = "═" * min(max(len(title_upper) + 4, 28), TEXT_WIDTH)
            formatted.append("")
            formatted.append(f"  ▪ {title_upper}")
            formatted.append(f"  {bar}")
            continue

        if stop_reading:
            continue

        # Sub-Heading (H3 / H4 style)
        if tag in ("h3", "h4"):
            if text.lower() in SKIP_SECTIONS:
                continue
            bar = "─" * min(max(len(text) + 2, 20), TEXT_WIDTH)
            formatted.append("")
            formatted.append(f"    ▸ {text}")
            formatted.append(f"    {bar}")
            continue

        # Bullet / List Item
        if tag == "li":
            if len(text) < 3:
                continue
            wrapped = textwrap.wrap(
                text,
                width=TEXT_WIDTH - 4,
                initial_indent="    • ",
                subsequent_indent="      ",
                break_long_words=False,
                break_on_hyphens=False
            )
            formatted.extend(wrapped)
            formatted.append("")
            continue

        # Blockquote
        if tag == "blockquote":
            wrapped = textwrap.wrap(
                f'"{text}"',
                width=TEXT_WIDTH - 4,
                initial_indent="    ┃ ",
                subsequent_indent="    ┃ ",
                break_long_words=False,
                break_on_hyphens=False
            )
            formatted.extend(wrapped)
            formatted.append("")
            continue

        # Paragraf Standar Editorial (Word-Wrapped 68 kolom)
        if tag == "p":
            if len(text) < 15:
                continue
            wrapped_para = textwrap.wrap(
                text,
                width=TEXT_WIDTH,
                initial_indent="    ",
                subsequent_indent="    ",
                break_long_words=False,
                break_on_hyphens=False
            )
            if wrapped_para:
                formatted.extend(wrapped_para)
                formatted.append("")

    while formatted and not formatted[0].strip():
        formatted.pop(0)
    while formatted and not formatted[-1].strip():
        formatted.pop()

    return formatted if formatted else ["    (No readable text content extracted)"]

def save_governor_state(state):
    ensure_directories()
    state["last_updated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    try:
        with open(GOVERNOR_STATE_FILE, "w", encoding="utf-8") as f:
            json.dump(state, f, indent=4, ensure_ascii=False)
    except Exception:
        pass

    exec_status = state.get("execution_status", "STOP")
    active_top = state.get("active_topic", "None")
    src_url = state.get("source_url", "N/A")
    cur_p = state.get("current_page", 0)
    tot_p = state.get("total_pages", 0)
    upd_time = state["last_updated"]

    content = f"""# 🧠 AI GOVERNOR & TOKEN ORCHESTRATION MINDMAP
## Root: Hermes Agent Zero-Token Relay Controller
- **Execution State:** `{exec_status}`
- **Active Topic:** `{active_top}`
- **Source URL:** `{src_url}`
- **Page Pointer:** `Page {cur_p} of {tot_p}`
- **AI Role:** `TRIGGER_AND_RELAY_ONLY (Zero LLM Processing)`
- **Last Updated:** `{upd_time}`

### 🕹️ Mindmap Control Commands:
- 🟢 `run` / `resume` -> Resume active output stream
- 🟡 `pause`          -> Freeze pointer & halt token output
- 🔴 `stop`           -> Terminate session & halt active stream
- ⏭️ `next`           -> Advance 1 page chunk
- ⏮️ `prev`           -> Rewind 1 page chunk
- 🔢 `<page_number>`  -> Jump directly to specific page
- 📊 `status`         -> Inspect current state without moving pointer
"""
    try:
        with open(GOVERNOR_MINDMAP_FILE, "w", encoding="utf-8") as f:
            f.write(content)
    except Exception:
        pass

def load_governor_state():
    if os.path.exists(GOVERNOR_STATE_FILE):
        try:
            with open(GOVERNOR_STATE_FILE, "r", encoding="utf-8") as f:
                data = json.load(f)
                if isinstance(data, dict):
                    return data
        except Exception:
            pass
    return {
        "active_topic": "None",
        "source_url": "N/A",
        "execution_status": "STOP",
        "current_page": 0,
        "total_pages": 0
    }

def pad_box_line(text, width=BOX_WIDTH):
    clean = text[:width - 4]
    return f"║  {clean:<{width - 4}}  ║"

def render_governed_output(state):
    status = state.get("execution_status", "STOP")
    topic = state.get("active_topic", "None")
    url = state.get("source_url", "N/A")
    cur = int(state.get("current_page", 0))
    tot = int(state.get("total_pages", 0))

    top_border = "╔" + "═" * BOX_WIDTH + "╗"
    mid_border = "╠" + "═" * BOX_WIDTH + "╣"
    bot_border = "╚" + "═" * BOX_WIDTH + "╝"

    if status == "STOP" or tot <= 0 or topic == "None":
        print(f"\n{top_border}")
        print(pad_box_line("🔴  MINDMAP GOVERNOR  │  STATE: STOPPED"))
        print(pad_box_line("Agent idle. Token pipeline closed. Send a topic query to begin."))
        print(f"{bot_border}\n")
        return

    if status == "PAUSE":
        print(f"\n{top_border}")
        print(pad_box_line(f"🟡  MINDMAP GOVERNOR  │  STATE: PAUSED  │  Held at Page {cur}/{tot}"))
        print(pad_box_line("Context frozen. Zero tokens active. Send 'run' or 'next' to resume."))
        print(f"{bot_border}\n")
        return

    safe_name = sanitize_filename(topic)
    page_file = os.path.join(VAULT_DIR, f"{safe_name}_pages", f"page_{cur}_of_{tot}.txt")

    if not os.path.exists(page_file):
        available = sorted(
            glob.glob(os.path.join(VAULT_DIR, f"{safe_name}_pages", "page_*_of_*.txt")),
            key=lambda x: int(re.search(r'page_(\d+)_of_', os.path.basename(x)).group(1))
        )
        if available:
            page_file = available[0]
            cur = 1
            tot = len(available)
            state["current_page"] = cur
            state["total_pages"] = tot
            save_governor_state(state)
        else:
            print(f"\n  [MINDMAP ERROR] No readable chunks found for '{topic}'. Re-fetch the topic.\n")
            return

    with open(page_file, "r", encoding="utf-8", errors="ignore") as f:
        chunk_body = f.read().rstrip()

    pct = int((cur / tot) * 100) if tot > 0 else 0
    bar_len = 20
    filled = int(bar_len * cur / tot) if tot > 0 else 0
    progress_bar = "█" * filled + "░" * (bar_len - filled)

    print(f"\n{top_border}")
    print(pad_box_line("📚  WIKI PRO INTERNATIONAL EDITION  │  MINDMAP TOKEN GOVERNOR"))
    print(mid_border)
    print(pad_box_line(f"Article  : {topic}"))
    print(pad_box_line(f"Source   : {url}"))
    print(pad_box_line(f"Progress : Page {cur} of {tot}  [{progress_bar}] {pct}%"))
    print(bot_border)

    print(f"\n{chunk_body}\n")

    nav_top = "┌" + "─" * BOX_WIDTH + "┐"
    nav_bot = "└" + "─" * BOX_WIDTH + "┘"
    nav_status = f"  STATUS: {status}  │  PAGE {cur}/{tot} ({pct}%)"
    nav_help = "  NAVIGATE: 'next' | 'prev' | <page#> | 'pause' | 'stop' | <new topic>"
    print(nav_top)
    print(f"│{nav_status:<{BOX_WIDTH}}│")
    print(f"│{nav_help:<{BOX_WIDTH}}│")
    print(f"{nav_bot}\n")

def handle_control_command(cmd):
    state = load_governor_state()
    tot = int(state.get("total_pages", 0))
    cur = int(state.get("current_page", 0))
    active_top = state.get("active_topic", "None")

    if cmd == "STATUS":
        render_governed_output(state)
        return

    if cmd == "STOP":
        state["execution_status"] = "STOP"
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Execution STOPPED on '{active_top}' at page {cur}.")
        render_governed_output(state)
        return

    if cmd == "PAUSE":
        if tot <= 0:
            print("\n  [MINDMAP GOVERNOR] Nothing active to pause. Send a search query first.\n")
            return
        state["execution_status"] = "PAUSE"
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Execution PAUSED on '{active_top}' at page {cur}.")
        render_governed_output(state)
        return

    if cmd == "RUN":
        if tot <= 0:
            print("\n  [MINDMAP GOVERNOR] No active topic loaded. Provide a search query first.\n")
            return
        state["execution_status"] = "RUN"
        if cur <= 0:
            state["current_page"] = 1
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Execution RESUMED on '{active_top}' at page {state['current_page']}.")
        render_governed_output(state)
        return

    if cmd == "NEXT":
        if tot <= 0:
            print("\n  [MINDMAP GOVERNOR] Session empty. Start a topic query first.\n")
            return
        state["execution_status"] = "RUN"
        if cur < tot:
            state["current_page"] = cur + 1
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Advanced pointer to page {state['current_page']}/{tot}.")
        render_governed_output(state)
        return

    if cmd == "PREV":
        if tot <= 0:
            print("\n  [MINDMAP GOVERNOR] Session empty. Start a topic query first.\n")
            return
        state["execution_status"] = "RUN"
        if cur > 1:
            state["current_page"] = cur - 1
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Rewound pointer to page {state['current_page']}/{tot}.")
        render_governed_output(state)
        return

def handle_numeric_jump(target_page):
    state = load_governor_state()
    tot = int(state.get("total_pages", 0))
    if tot <= 0:
        print("\n  [MINDMAP GOVERNOR] No active topic loaded. Provide a search query first.\n")
        return
    if 1 <= target_page <= tot:
        state["execution_status"] = "RUN"
        state["current_page"] = target_page
        save_governor_state(state)
        log_coordinator("GOVERNOR", f"Jumped pointer directly to page {target_page}/{tot}.")
        render_governed_output(state)
    else:
        print(f"\n  [MINDMAP GOVERNOR] Page {target_page} out of range (Valid pages: 1 to {tot}).\n")

def paginate_lines(pro_lines, lines_per_page=LINES_PER_PAGE):
    chunks = []
    current = []
    for line in pro_lines:
        # Hindari memutus tepat setelah judul bagian atau sub-judul di akhir halaman
        if len(current) >= lines_per_page - 3 and (line.startswith("  ▪ ") or line.startswith("    ▸ ")):
            chunks.append("\n".join(current).rstrip())
            current = [line]
        else:
            current.append(line)
            if len(current) >= lines_per_page:
                chunks.append("\n".join(current).rstrip())
                current = []
    if current:
        chunks.append("\n".join(current).rstrip())
    return [c for c in chunks if c.strip()] or ["    (Empty Page)"]

def fallback_local_cache(query):
    ensure_directories()
    safe_q = sanitize_filename(query).lower()
    all_txts = glob.glob(os.path.join(VAULT_DIR, "*.txt"))
    if not all_txts:
        return False

    matched = [f for f in all_txts if safe_q in os.path.basename(f).lower()]
    target_txt = matched[0] if matched else max(all_txts, key=os.path.getmtime)
    base_name = os.path.splitext(os.path.basename(target_txt))[0]
    topic_title = base_name.replace('_', ' ')
    pages_dir = os.path.join(VAULT_DIR, f"{base_name}_pages")

    existing_pages = sorted(
        glob.glob(os.path.join(pages_dir, "page_*_of_*.txt")),
        key=lambda x: int(re.search(r'page_(\d+)_of_', os.path.basename(x)).group(1))
    )

    if not existing_pages:
        with open(target_txt, "r", encoding="utf-8", errors="ignore") as f:
            lines = f.read().splitlines()
        os.makedirs(pages_dir, exist_ok=True)
        chunks = paginate_lines(lines)
        count_pages = len(chunks)
        for idx, chunk in enumerate(chunks, 1):
            p_path = os.path.join(pages_dir, f"page_{idx}_of_{count_pages}.txt")
            with open(p_path, "w", encoding="utf-8") as pf:
                pf.write(chunk)
    else:
        count_pages = len(existing_pages)

    state = {
        "active_topic": topic_title,
        "source_url": f"LOCAL_CACHE://{base_name}.txt",
        "execution_status": "RUN",
        "current_page": 1,
        "total_pages": count_pages
    }
    save_governor_state(state)
    log_coordinator("FALLBACK", f"Loaded '{topic_title}' from local cache ({count_pages} pages).")
    render_governed_output(state)
    return True

def fetch_wiki_data(query):
    encoded_query = urllib.parse.quote(query)
    search_api = f"https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={encoded_query}&format=json&srlimit=1"

    req = urllib.request.Request(search_api, headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) HermesWikiPro/40.0'})
    with urllib.request.urlopen(req, timeout=25) as response:
        data = json.loads(response.read().decode('utf-8'))
        results = data.get('query', {}).get('search', [])
        if not results:
            return None, None, None, None

        best_title = results[0]['title']
        page_url = f"https://en.wikipedia.org/wiki/{urllib.parse.quote(best_title.replace(' ', '_'))}"

        full_html = ""
        try:
            html_req = urllib.request.Request(page_url, headers={'User-Agent': 'Mozilla/5.0'})
            with urllib.request.urlopen(html_req, timeout=30) as html_res:
                full_html = html_res.read().decode('utf-8', errors='ignore')
        except Exception:
            full_html = f"<html><body><h1>{best_title}</h1></body></html>"

        parse_api = f"https://en.wikipedia.org/w/api.php?action=parse&page={urllib.parse.quote(best_title)}&prop=text&format=json"
        parse_req = urllib.request.Request(parse_api, headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) HermesWikiPro/40.0'})
        with urllib.request.urlopen(parse_req, timeout=45) as parse_res:
            parse_data = json.loads(parse_res.read().decode('utf-8'))
            html_content = parse_data.get('parse', {}).get('text', {}).get('*', '')

            parser = WikiCleanParser()
            parser.feed(html_content)
            parser._flush()

        return best_title, page_url, full_html, parser.blocks

def generate_dual_mindmaps(best_title, blocks, chunks, safe_name, count_pages):
    ensure_directories()
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    html_mm_path = os.path.join(MINDMAP_DIR, f"{safe_name}_html_structure_mindmap.md")
    headings = [t for tag, t in blocks if tag in ("h2", "h3") and t.lower() not in SKIP_SECTIONS and t.lower() not in NOISE_LINES]

    html_content = f"# 🌐 HTML STRUCTURE MINDMAP: {best_title}\n\n## Root: {best_title}\n* **Last Sync:** {timestamp}\n\n### 📂 Document Headings:\n"
    for h in (headings[:30] if headings else ["Full Document"]):
        html_content += f"- 🔸 **{h}**\n"
    with open(html_mm_path, "w", encoding="utf-8") as f1:
        f1.write(html_content)

    chunk_mm_path = os.path.join(MINDMAP_DIR, f"{safe_name}_paginated_chunks_mindmap.md")
    chunk_content = f"# 📑 PAGINATED CHUNKS MINDMAP: {best_title}\n\n## Root: {best_title}\n* **Total Split Pages:** {count_pages}\n* **Last Sync:** {timestamp}\n\n### 🗂️ Page Index:\n"
    for idx, chunk in enumerate(chunks, 1):
        non_empty = [l.strip() for l in chunk.splitlines() if l.strip() and not set(l.strip()) <= {"─", "═"}]
        snippet = non_empty[0][:55] if non_empty else f"Section {idx}"
        chunk_content += f"- 📄 **Page {idx}/{count_pages}** -> `{snippet}...` (`../{safe_name}_pages/page_{idx}_of_{count_pages}.txt`)\n"
    with open(chunk_mm_path, "w", encoding="utf-8") as f2:
        f2.write(chunk_content)

def process_and_coordinate(best_title, page_url, full_html, blocks):
    ensure_directories()
    safe_name = sanitize_filename(best_title)
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    with open(os.path.join(VAULT_DIR, f"{safe_name}_full.html"), "w", encoding="utf-8") as hf:
        hf.write(full_html)

    pro_lines = format_wiki_pro_blocks(blocks)

    header = (
        f"==========================================================================\n"
        f"  WIKI PRO MASTER ARCHIVE : {best_title.upper()}\n"
        f"  SOURCE URL              : {page_url}\n"
        f"  SYNCHRONIZED AT         : {timestamp}\n"
        f"==========================================================================\n\n"
    )
    with open(os.path.join(VAULT_DIR, f"{safe_name}.txt"), "w", encoding="utf-8") as tf:
        tf.write(header + "\n".join(pro_lines) + "\n")

    pages_folder = os.path.join(VAULT_DIR, f"{safe_name}_pages")
    os.makedirs(pages_folder, exist_ok=True)

    for old_page in glob.glob(os.path.join(pages_folder, "page_*_of_*.txt")):
        try:
            os.remove(old_page)
        except Exception:
            pass

    chunks = paginate_lines(pro_lines)
    count_pages = max(len(chunks), 1)

    for idx, chunk in enumerate(chunks, 1):
        page_path = os.path.join(pages_folder, f"page_{idx}_of_{count_pages}.txt")
        with open(page_path, "w", encoding="utf-8") as pf:
            pf.write(chunk + "\n")

    generate_dual_mindmaps(best_title, blocks, chunks, safe_name, count_pages)

    registry = {}
    if os.path.exists(REGISTRY_FILE):
        try:
            with open(REGISTRY_FILE, "r", encoding="utf-8") as f:
                raw = f.read().strip()
                if raw:
                    loaded = json.loads(raw)
                    if isinstance(loaded, dict):
                        registry = loaded
        except Exception:
            registry = {}

    registry[best_title] = {
        "master_file": f"{safe_name}.txt",
        "html_file": f"{safe_name}_full.html",
        "source_url": page_url,
        "total_pages": count_pages,
        "pages_directory": pages_folder,
        "last_sync": timestamp,
        "status": "MINDMAP_GOVERNED"
    }
    with open(REGISTRY_FILE, "w", encoding="utf-8") as rf:
        json.dump(registry, rf, indent=4, ensure_ascii=False)

    global_mm = f"# 🌐 MASTER VAULT GLOBAL INDEX MINDMAP\n\n* **Total Topics:** {len(registry)}\n* **Last Sync:** {timestamp}\n\n### 📂 Coordinated Topics:\n"
    for t, info in registry.items():
        p_count = info.get("total_pages", "?") if isinstance(info, dict) else "?"
        s_name = sanitize_filename(t)
        global_mm += f"- 📂 **{t}** (`{p_count} Pages`) -> `mindmaps/{s_name}_paginated_chunks_mindmap.md`\n"
    with open(GLOBAL_MINDMAP_FILE, "w", encoding="utf-8") as gmf:
        gmf.write(global_mm)

    run_command(["7z", "a", "-t7z", os.path.expanduser("~/wiki_vault_full_archive.7z"), os.path.join(VAULT_DIR, "*"), "-mx=9", "-y"])
    if not os.path.exists(os.path.join(VAULT_DIR, ".git")):
        run_command(["git", "init"], cwd=VAULT_DIR)
    run_command(["git", "add", "."], cwd=VAULT_DIR)
    run_command(["git", "commit", "-m", f"Mindmap Governor sync: '{best_title}' at {timestamp}"], cwd=VAULT_DIR)

    state = {
        "active_topic": best_title,
        "source_url": page_url,
        "execution_status": "RUN",
        "current_page": 1,
        "total_pages": count_pages
    }
    save_governor_state(state)
    log_coordinator("SYNC", f"Fetched and locked '{best_title}' ({count_pages} pages) into Mindmap Governor.")
    render_governed_output(state)

def main():
    ensure_directories()
    arg_str = " ".join(sys.argv[1:]).strip()
    if not arg_str:
        print("\n  [MINDMAP GOVERNOR] No input provided. Pass a topic, page number, or command (run/pause/stop/next/prev/status).\n")
        sys.exit(0)

    upper_arg = arg_str.upper()
    normalized_cmd = ALIASES.get(upper_arg, upper_arg)

    if normalized_cmd in CONTROL_COMMANDS:
        handle_control_command(normalized_cmd)
        return

    if arg_str.isdigit():
        handle_numeric_jump(int(arg_str))
        return

    try:
        best_title, page_url, full_html, blocks = fetch_wiki_data(arg_str)
        if not best_title or not blocks:
            if not fallback_local_cache(arg_str):
                print(f"\n  [MINDMAP GOVERNOR] No online or cached entry found for: '{arg_str}'\n")
            return
        process_and_coordinate(best_title, page_url, full_html, blocks)
    except Exception:
        if not fallback_local_cache(arg_str):
            print("\n  [MINDMAP GOVERNOR ERROR] Network error and no local cache available:")
            traceback.print_exc()

if __name__ == "__main__":
    main()

```
 

 

 

 

==========================================


SS





Komentar

Postingan populer dari blog ini

SIFO SUPER PLAYER :)

CARA SEDERHANA MEMBUAT SERVER NEXTCLOUD DI GNU LINUX OS YANG SUPER AMAN ANTI SPY2 :D