# obsidian-life-memory

Adopt this skill: https://proskills.md/skills/other/georgeantonopoulos-obsidian-life-memory-skill

Page: https://proskills.md/skills/other/georgeantonopoulos-obsidian-life-memory-skill
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 7605
sha: 9c514843150c7e8ce6ad8442a8ba30e5d30b360b
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/SKILL.md

````text
---
name: obsidian-life-memory
description: Manage an Obsidian-backed personal memory system for an agent: resolve vault, read/search recent context, append daily events, organize notes into a stable taxonomy, distill daily notes into long-term memory, and run graph health audits.
---

# Obsidian Life Memory

Use this skill when the user wants persistent personal memory in an Obsidian vault.

## Core Rules

- Use `obsidian-cli` for **all** note operations — never raw file tools on vault files.
- Read before writing: retrieve recent context first when the request depends on prior facts or decisions.
- Keep edits reversible: prefer `append` or `edit` over full `create` overwrites.
- Preserve privacy: do not publish or exfiltrate vault content unless explicitly requested.

## CLI Setup

The `obsidian-cli` command at `/usr/local/bin/obsidian-cli` is a **compatibility adapter** over the **official Obsidian CLI** (1.12.7+).
- Runtime requires the **official Obsidian app** to be installed and running
- Adapter forwards note operations to the official CLI while preserving the older OpenClaw command shape
- Vault resolves to `/root/.openclaw/workspace` in this deployment
- Daily notes live in `memory/YYYY-MM-DD.md` via Obsidian daily-notes config
- Source: `bin/obsidian-cli` in this skill repo

## Essential Commands

### Reading notes
```bash
obsidian-cli read path="MEMORY.md"
obsidian-cli read path="People/george.md"
obsidian-cli daily:read                        # today's daily note
```

### Writing & editing notes
```bash
# Append — \n and \t are interpreted (printf %b)
obsidian-cli daily:append content="## 14:30 UTC\n- Thing happened"
obsidian-cli append path="MEMORY.md" content="\n## New section\n- fact"

# Create — errors if file exists (use force=true to overwrite)
obsidian-cli create path="People/carla.md" content="# Carla\nMortgage broker"
obsidian-cli create path="People/carla.md" content="# Updated" force=true

# Daily create/overwrite
obsidian-cli daily:create content="# Daily Note — $(date -u +%Y-%m-%d)\n\n"

# Find & replace within a note
obsidian-cli edit path="MEMORY.md" find="🟡 PENDING" replace="✅ DONE"
obsidian-cli edit path="MEMORY.md" find="status: (open)" replace="status: closed" regex=true
```

### Browsing the vault
```bash
obsidian-cli list folder="People"              # list .md files in a folder
obsidian-cli list folder="Projects"
obsidian-cli list folder="."                   # vault root
obsidian-cli status                            # vault overview + folder counts
```

### Moving & deleting
```bash
# Move + updates [[wikilinks]] across the vault when filename changes
obsidian-cli move path="old/note.md" to="new/note.md"

# Delete
obsidian-cli delete path="Archive/stale.md"
```

### Searching
```bash
obsidian-cli search query="Athens"             # search by filename
obsidian-cli search-content query="Moraitis"   # full-text with context lines
obsidian-cli search-content query="lease" max=5 context=5
```

### Vault path
```bash
obsidian-cli print-default                     # workspace (/path/to/vault)
obsidian-cli print-default --path-only         # /path/to/vault
```

## Workflow

### 1) Session startup
```bash
obsidian-cli read path="SOUL.md"
obsidian-cli read path="USER.md"
obsidian-cli daily:read
obsidian-cli read path="MEMORY.md"   # main sessions only
```

### 2) Log events
```bash
obsidian-cli daily:append content="## $(date -u +%H:%M) UTC\n- <event>"
```

### 3) Update long-term notes
```bash
obsidian-cli append path="MEMORY.md" content="\n## New section\n- fact"
# or targeted edit:
obsidian-cli edit path="MEMORY.md" find="old status" replace="new status"
```

### 4) Maintain knowledge graph
```bash
obsidian-cli list folder="People"              # check coverage
obsidian-cli search-content query="[[Person]]" # find references
obsidian-cli move path="People/old.md" to="People/correct-name.md"
```

## Note on `\n` in content

All write commands (`append`, `create`, `daily:append`, `daily:create`) use `printf '%b'` internally, which interprets:
- `\n` → newline
- `\t` → tab

So pass multi-line content as: `content="## Heading\n- item one\n- item two"`

## Resources

- CLI binary: `/usr/local/bin/obsidian-cli`
- Source: `bin/obsidian-cli` (this repo)
- Vault path: `/root/.openclaw/workspace`
- Daily notes: `/root/.openclaw/workspace/memory/YYYY-MM-DD.md`

## Auto-Categorisation: gizmo-curate

`gizmo-curate` extends the skill with LLM-powered auto-categorisation. Instead of manually deciding where to file new knowledge, pass raw text and the tool decides path, title, tags, and whether to create or append.

### Usage
```bash
# File a person, project, place, or fact automatically
gizmo-curate "Alice Smith is a contractor at Acme Corp, alice@acme.com"

# Preview decision without writing
gizmo-curate --dry-run "some text"

# Pipe mode
echo "some text" | gizmo-curate
```

### How it works
1. Sends text + vault folder structure to Gemini Flash (~1.2s)
2. Gets back: `action` (create/append), `path`, `title`, `tags`, formatted markdown
3. Writes to vault via `obsidian-cli`

### Decision rules
| Content type | Target path |
|---|---|
| Person | `People/firstname-lastname.md` |
| Project fact | `Projects/project-name.md` (appends if exists) |
| Place | `Places/place-name.md` |
| Financial | `Finance/` |
| Vendor/service | `Vendors/` |
| Unsure | `Notes/` |

### Integration points
- **Nightly Memory cron (3am)**: auto-curates up to 3 new entities found in daily note
- **Manual**: call `gizmo-curate` any time during a session for instant filing
- **Coding agents**: `gizmo-curate` available on PATH for Codex/Claude Code to save project context

### Binary
- `/usr/local/bin/gizmo-curate`
- Source: `/root/gizmo_curate.py`
- Requires: `GEMINI_API_KEY` env var (pre-configured in OpenClaw runtime)

---

## Wiki Pattern (Karpathy llm-wiki)

Three workflows for building a compounding personal knowledge base.

### Ingest workflow
When user sends a source (URL/PDF/text) to add to the wiki:
```bash
# 1. Read source (web_fetch, pdf tool, etc.)
# 2. Discuss with user
# 3. Create source summary page
obsidian-cli create path="Sources/YYYY-MM-DD_slug.md" content="# Title

- **Source**: URL
- **Ingested**: date

## Summary
..."

# 4. Update relevant entity pages
obsidian-cli append path="Projects/relevant.md" content="
## Source update YYYY-MM-DD
- key takeaway"

# 5. Update index
obsidian-cli edit path="index.md" find="## Sources" replace="## Sources
- [[Sources/YYYY-MM-DD_slug]] — one-line summary"

# 6. Log it
obsidian-cli append path="log.md" content="
## [YYYY-MM-DD] ingest | Source Title
Pages updated: list"
```

### Query → file back
After producing substantive synthesis (analysis, comparison, research):
```bash
# Offer to file, then:
obsidian-cli create path="Projects/analysis-slug.md" content="# Analysis Title

..."
obsidian-cli append path="log.md" content="
## [YYYY-MM-DD] query | Analysis Title
Filed from conversation."
# Update index.md entry
```

### Lint workflow
```bash
# Check for dead wikilinks, orphan pages, stale MEMORY.md entries
obsidian-cli search-content query="<!-- Stub"  # find stub pages needing content
obsidian-cli read path="index.md"               # audit for missing pages
obsidian-cli append path="log.md" content="
## [YYYY-MM-DD] lint | Weekly health check
Issues: ..."
```

### Key files
| File | Purpose |
|------|---------|
| `index.md` | Catalog of all wiki pages with one-line descriptions |
| `log.md` | Append-only history of ingests/queries/lint passes |
| `Sources/` | One page per external source ingested |
````

## File: plugins/obsidian-cli-tool/README.md
size: 528
sha: 289a4c15b37ff9937cd1a1804bc4a62e5045706a
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/plugins/obsidian-cli-tool/README.md

```text
# obsidian-cli-tool

First-class OpenClaw plugin tools for Obsidian vault access backed by `obsidian-cli`.

## Tools
- `obsidian_read`
- `obsidian_search`
- `obsidian_search_content`
- `obsidian_create`
- `obsidian_append`
- `obsidian_move`
- `obsidian_list`
- `obsidian_daily_read`
- `obsidian_daily_append`

## Purpose
This lives inside `obsidian-life-memory-skill` because it is the hard-capability complement to the skill's existing guidance: use `obsidian-cli` for vault operations and avoid raw file tools on vault notes.
```

## File: README.md
size: 10132
sha: 55fa1ca0defdb30c3733ee31f9c0168ce5c766dd
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/README.md

````text
# obsidian-life-memory-skill

Transform your OpenClaw workspace into a **structured, navigable memory system** using plain Markdown, with **official Obsidian desktop + official Obsidian CLI** as the runtime path.

> ⚠️ **Important:** This skill now assumes the **official Obsidian app is installed and running**.
>
> The shipped `bin/obsidian-cli` is **not** a standalone vault editor anymore — it is a thin **compatibility adapter** for OpenClaw that forwards commands to the **official Obsidian 1.12.7+ CLI** while preserving the older command shape (`read path=...`, `daily:read`, `search-content`, etc.).

This skill provides persistent personal memory for AI agents through wikilinked notes, daily logs, backlink traversal, and graph-based context retrieval.

---

## What It Does

This skill helps agents maintain continuity across sessions by organizing information into an Obsidian vault with:

- **Daily notes** — Timestamped logs of events, decisions, and context
- **Wikilinked entities** — People, projects, and concepts as connected nodes (`[[Project Name]]`, `[[Person]]`)
- **Long-term memory** — Distilled summaries from daily noise
- **Automatic context injection** — Pre-prompt hook loads relevant context at session start
- **Auto-categorisation** — `gizmo-curate` files raw text into the right vault location automatically

---

## gizmo-curate: Auto-Categorisation

`gizmo-curate` is a companion tool that uses an LLM to auto-categorise raw text and file it into the correct vault location. Pass raw text → LLM decides path, title, and tags → writes via `obsidian-cli`. No manual path decisions needed.

```bash
# File a person automatically
gizmo-curate "Alice Smith is a contractor at Acme Corp, alice@acme.com"
# → creates People/alice-smith.md ✅

# Append to an existing project note
gizmo-curate "Project Alpha: v2 integration in progress, review scheduled Friday"
# → appends to Projects/project-alpha.md ✅

# Preview without writing
gizmo-curate --dry-run "some text"

# Pipe mode
echo "some text" | gizmo-curate
```

**Speed:** ~1.2s per call.

### Decision rules

| Content type | Target path |
|---|---|
| Person | `People/firstname-lastname.md` |
| Project fact | `Projects/project-name.md` (appends if file exists) |
| Place | `Places/place-name.md` |
| Financial | `Finance/` |
| Vendor/service | `Vendors/` |
| Unsure | `Notes/` |

### Integration points
- **Nightly cron** — auto-curates new entities found in daily notes
- **Manual** — call `gizmo-curate` any time for instant filing
- **Coding agents** — available on PATH so agents can save project context

**Binary:** `/usr/local/bin/gizmo-curate` · **Requires:** LLM API key (configured in OpenClaw runtime env)

---

## `obsidian-cli` — Compatibility Adapter over the Official CLI

The skill ships `bin/obsidian-cli` and installs it to `/usr/local/bin/obsidian-cli`, but that file is now a **compatibility adapter**.

Under the hood it calls the **official Obsidian CLI** from the desktop installer (tested with **1.12.7**) and preserves the older OpenClaw-friendly command shape used throughout the vault and hooks.

**The golden rule: all vault reads and writes go through `obsidian-cli`. Never use raw file tools on vault files.**

### Runtime requirements

- **Official Obsidian desktop installed** (1.12.7+ recommended)
- **Official Obsidian CLI available** (bundled with the installer)
- Obsidian app **running**
- In root/headless environments: start Obsidian with `--no-sandbox` and usually `DISPLAY=:99`

### Installation

```bash
cp bin/obsidian-cli /usr/local/bin/obsidian-cli
chmod +x /usr/local/bin/obsidian-cli
```

### Command Reference

#### Reading

```bash
obsidian-cli read path="MEMORY.md"
obsidian-cli read path="People/alice.md"
obsidian-cli daily:read                         # today's daily note
```

#### Writing & Editing

> **`\n` is interpreted** — all write commands use `printf '%b'` internally, so `\n` becomes a real newline.

```bash
obsidian-cli daily:append content="## 14:30 UTC\n- Meeting notes here"
obsidian-cli append path="MEMORY.md" content="\n## New section\n- important fact"
obsidian-cli create path="People/alice.md" content="# Alice\nEngineer at Acme Corp"
obsidian-cli edit path="MEMORY.md" find="🟡 PENDING" replace="✅ DONE"
```

#### Browsing & Searching

```bash
obsidian-cli list folder="People"
obsidian-cli search query="project"             # filename search
obsidian-cli search-content query="invoice"     # full-text with context lines
obsidian-cli status                             # vault overview
```

#### Moving

```bash
# Renames file AND updates [[wikilinks]] across the vault
obsidian-cli move path="People/old-name.md" to="People/correct-name.md"
```

---

## Vault Taxonomy

```
workspace/
├── IDENTITY.md              # Who the agent is (name, vibe, emoji)
├── USER.md                  # Who the human is (preferences, context)
├── SOUL.md                  # Behavioral guidelines and boundaries
├── MEMORY.md                # Long-term distilled knowledge
├── HEARTBEAT.md             # System status and maintenance config
├── AGENTS.md                # Workspace rules and tool usage
│
├── memory/                  # Daily notes (YYYY-MM-DD.md)
├── People/                  # Real people the human interacts with
├── Projects/                # Active projects with backlinks
├── Places/                  # Real locations
├── Finance/                 # Financial facts, mortgages, investments
├── Vendors/                 # Companies and services
├── Notes/                   # Loose notes and catch-all
└── Archives/                # Completed/cold projects
```

---

## Session Startup Sequence

```bash
obsidian-cli read path="SOUL.md"
obsidian-cli read path="USER.md"
obsidian-cli daily:read
# Main sessions only:
obsidian-cli read path="MEMORY.md"
```

---

## Wiki Pattern (Karpathy llm-wiki)

The vault implements the [llm-wiki pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) — a persistent, compounding knowledge base maintained by the LLM. Instead of re-deriving answers from raw sources on every query, the agent incrementally builds and maintains a structured wiki of interlinked Markdown pages.

### Three workflows

**Ingest** — You send a URL, PDF, or text. The agent reads it, creates a `Sources/YYYY-MM-DD_slug.md` summary page, updates relevant entity pages (`Projects/`, `People/`, `Places/`), updates `index.md`, and appends to `log.md`. A single source can touch 5–15 pages.

**Query → file back** — When the agent produces a substantive synthesis (analysis, comparison, research summary), it offers to file the result as a wiki page. Your explorations compound in the knowledge base, not just disappear into chat history.

**Lint** — Weekly (or on-demand) health check: dead wikilinks, orphan pages, important stubs, stale status items. Runs as a scheduled cron job.

### Key files

| File | Purpose |
|------|---------|
| `index.md` | Catalog of every wiki page with one-line descriptions. Loaded at every session bootstrap so the agent always knows what exists. |
| `log.md` | Append-only record of ingests/queries/lint passes. Format: `## [YYYY-MM-DD] action | title`. Parseable: `grep "^## [" log.md | tail -5` |
| `Sources/` | One Markdown page per ingested external source. Immutable summaries. |

### Vault taxonomy (extended)
```
workspace/
├── index.md                 # Wiki catalog — all pages with one-liners
├── log.md                   # Append-only ingest/query/lint history
├── Sources/                 # External source summaries (one per source)
├── Projects/                # Active projects
├── People/                  # Real people
├── Places/                  # Real locations
...
```

---

## Token-Optimized Pre-Prompt Hook

`hooks/obsidian-preprompt.js` handles two injection paths:

**Session start (`agent:bootstrap`):** injects governance files + daily snapshot once per session. It also automatically loads any files specified in the `OBSIDIAN_OPTIONAL_CONTEXT_FILES` environment variable (e.g., `Context/retrieval_policy.md`) to enforce mandatory system behaviors like active graph traversal and wikilink resolution.

**Per-turn retrieval (`before_prompt_build`):** derives 1–3 queries from the current message, retrieves a small bounded set of snippets, injects as targeted context. Never auto-writes to the vault.

---

## Heartbeat Gardening

A heartbeat cron maintains a lightweight knowledge graph:
- reads recent daily notes
- updates/creates nodes under `Projects/`, `People/`, `Places/`
- silent unless something urgent surfaces
- never auto-edits governance files (`SOUL.md`, `AGENTS.md`, etc.)

---

## Repository Layout

```
obsidian-life-memory-skill/
├── SKILL.md                           # Agent-facing skill definition
├── README.md                          # This file
├── bin/
│   └── obsidian-cli                   # Compatibility adapter
├── hooks/
│   └── obsidian-preprompt.js          # Pre-prompt injection hook
├── scripts/
│   ├── life_memory.py                 # Python vault helper
│   ├── sync_live_copy.sh              # Deploy skill updates safely
│   ├── auto_sync_from_origin.sh       # Auto-pull from git origin
│   └── fix_deadends.py                # Fix broken [[wikilinks]]
├── agents/                            # Agent prompt fragments
├── templates/                         # Note templates
├── tests/                             # Tests
└── references/
    ├── life-patterns.md               # Daily note patterns
    └── obsidian-cli-notes.md          # CLI usage notes
```

## Requirements

- Official Obsidian desktop 1.12.7+
- Official Obsidian CLI (bundled with the installer)
- bash (for the compatibility adapter)
- Python 3.10+ (optional helper scripts)
- Node.js 18+ (pre-prompt hook)
- LLM API key (for `gizmo-curate` only)

## License

MIT
````

## File: scripts/auto_sync_from_origin.sh
size: 476
sha: 17b4f8899f931f7b221a563da2717641f84bb917
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/scripts/auto_sync_from_origin.sh

```text
#!/usr/bin/env bash
set -euo pipefail

REPO_DIR="$(cd "$(dirname "$0")/.." && pwd)"
SYNC_SCRIPT="$REPO_DIR/scripts/sync_live_copy.sh"
LOG_DIR="/root/.openclaw/workspace/logs"
LOG_FILE="$LOG_DIR/obsidian-skill-sync.log"

mkdir -p "$LOG_DIR"

{
  echo "[$(date -u +%FT%TZ)] starting sync"
  cd "$REPO_DIR"
  git fetch origin
  git pull --ff-only origin "$(git rev-parse --abbrev-ref HEAD)"
  bash "$SYNC_SCRIPT"
  echo "[$(date -u +%FT%TZ)] sync complete"
} >> "$LOG_FILE" 2>&1
```

## File: scripts/fix_deadends.py
size: 12492
sha: 384e14cbd3e8ecbda95e2ff8fe3cbe2004942366
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/scripts/fix_deadends.py

```text
#!/usr/bin/env python3
"""
fix_deadends.py — Intelligent vault dead-end resolver

For each broken [[wikilink]], asks Moonshot AI:
  CREATE → link represents real content worth a note → writes a stub
  REMOVE → speculative/noise → replaces [[Link]] with plain text

Usage:
  python3 fix_deadends.py              # dry run, shows verdicts only
  python3 fix_deadends.py --apply      # make the changes
  python3 fix_deadends.py --apply --limit 30   # process up to 30 links
"""

import argparse
import json
import os
import re
import subprocess
import sys
import time
from pathlib import Path
from typing import List, Tuple
import urllib.request

# ── Config ────────────────────────────────────────────────────────────────────

def _get_moonshot_key() -> str:
    # 1. env override
    if os.environ.get("MOONSHOT_API_KEY"):
        return os.environ["MOONSHOT_API_KEY"]
    # 2. openclaw auth-profiles
    profiles_path = Path.home() / ".openclaw/agents/main/agent/auth-profiles.json"
    if profiles_path.exists():
        try:
            data = json.loads(profiles_path.read_text())
            for k, v in data.get("profiles", {}).items():
                if "moonshot" in k.lower():
                    key = v.get("key", "")
                    if key:
                        return key
        except Exception:
            pass
    raise RuntimeError("No Moonshot API key found. Set MOONSHOT_API_KEY or configure in OpenClaw.")

MOONSHOT_BASE_URL = "https://api.moonshot.ai/v1"
MOONSHOT_MODEL    = "moonshot-v1-8k"   # cheapest; just needs yes/no judgement

# ── Vault ─────────────────────────────────────────────────────────────────────

def get_vault() -> Path:
    store = Path.home() / ".life_memory_store.json"
    if store.exists():
        data = json.loads(store.read_text())
        v = data.get("vault")
        if v:
            return Path(v)
    return Path("/root/.openclaw/workspace")

SKIP_DIRS = {".git", ".obsidian", "node_modules", "__pycache__", ".trash",
             "obsidian-life-memory-skill", "dashboard_project", "Archives", "skills"}

def get_markdown_files(vault: Path) -> List[Path]:
    files = []
    for f in vault.rglob("*.md"):
        if not any(p in SKIP_DIRS for p in f.parts):
            files.append(f)
    return files

# ── Wikilink helpers ──────────────────────────────────────────────────────────

WIKILINK_RE = re.compile(r"\[\[([^|\]]+)(?:\|([^\]]+))?\]\]")

def extract_links_with_context(text: str) -> List[Tuple[str, str]]:
    """Return (link_target, surrounding_context) for each wikilink in text."""
    results = []
    lines = text.split("\n")
    for i, line in enumerate(lines):
        for m in WIKILINK_RE.finditer(line):
            link = m.group(1).strip()
            start, end = max(0, i - 1), min(len(lines), i + 2)
            ctx = " ".join(lines[start:end]).strip()[:400]
            results.append((link, ctx))
    return results

def resolve_link(link: str, vault: Path) -> Path:
    slug = link.replace(" ", "-").lower()
    if "/" in link:
        return vault / f"{slug}.md"
    for folder in ["", "Projects", "People", "Places", "Vendors",
                   "Events", "Daily", "Context", "Identity", "Finance"]:
        # exact slug match
        candidate = vault / folder / f"{slug}.md"
        if candidate.exists():
            return candidate
        # case-insensitive fallback (catches HEARTBEAT.md, SOUL.md etc.)
        parent = vault / folder if folder else vault
        if parent.exists():
            for f in parent.iterdir():
                if f.suffix == ".md" and f.stem.lower() == slug:
                    return f
    return vault / f"{slug}.md"

def remove_wikilink(text: str, link: str) -> str:
    """Replace [[link]] or [[link|alias]] with the alias or plain link name."""
    def _sub(m: re.Match) -> str:
        return m.group(2) if m.group(2) else m.group(1)
    pattern = re.compile(
        r"\[\[" + re.escape(link) + r"(?:\|([^\]]+))?\]\]"
    )
    return pattern.sub(lambda m: m.group(1) if m.group(1) else link, text)

# ── Moonshot verdict ──────────────────────────────────────────────────────────

def ask_moonshot(link: str, context: str, source: str, api_key: str) -> Tuple[str, str]:
    """Returns ('CREATE'|'REMOVE', reason_string)."""
    prompt = (
        f"You are a personal knowledge graph curator.\n"
        f"A markdown vault has a broken wikilink [[{link}]] in '{source}'.\n\n"
        f"Context:\n\"{context}\"\n\n"
        f"Should this become a real note?\n"
        f"- CREATE if: it's a real person, project, place, vendor, or recurring concept "
        f"that will accumulate information over time.\n"
        f"- REMOVE if: it's vague, a one-off mention, or doesn't warrant its own note.\n\n"
        f"Reply in exactly this format (two lines, nothing else):\n"
        f"DECISION: CREATE or REMOVE\n"
        f"REASON: one sentence"
    )

    payload = json.dumps({
        "model": MOONSHOT_MODEL,
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 80,
        "temperature": 0,
    }).encode()

    req = urllib.request.Request(
        f"{MOONSHOT_BASE_URL}/chat/completions",
        data=payload,
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}",
        },
    )

    try:
        with urllib.request.urlopen(req, timeout=20) as resp:
            data = json.loads(resp.read())
            content = data["choices"][0]["message"]["content"].strip()
    except Exception as e:
        return "SKIP", f"API error: {e}"

    decision, reason = "REMOVE", "no reason given"
    for line in content.splitlines():
        if line.startswith("DECISION:"):
            val = line.split(":", 1)[1].strip().upper()
            decision = "CREATE" if "CREATE" in val else "REMOVE"
        elif line.startswith("REASON:"):
            reason = line.split(":", 1)[1].strip()
    return decision, reason

# ── Stub creator ──────────────────────────────────────────────────────────────

_PEOPLE_HINTS  = {"george", "maya", "elpi", "carla", "christina", "ryan", "agis",
                  "miss", "mr", "mrs", "dr"}
_PROJECT_HINTS = {"sequency", "dashboard", "orsett", "athens", "moraitis",
                  "project", "app", "bmw", "revolut"}

def create_stub(link: str, vault: Path, source: str, reason: str) -> Path:
    ll = link.lower()
    if any(h in ll for h in _PEOPLE_HINTS):
        folder = vault / "People"
    elif any(h in ll for h in _PROJECT_HINTS):
        folder = vault / "Projects"
    else:
        folder = vault

    folder.mkdir(parents=True, exist_ok=True)
    slug = re.sub(r"[^\w\-]", "-", link.lower()).strip("-")
    note_path = folder / f"{slug}.md"

    if not note_path.exists():
        note_path.write_text(
            f"# {link}\n\n"
            f"<!-- Stub created by fix_deadends.py -->\n"
            f"<!-- Source: {source} | Reason: {reason} -->\n\n"
            f"## Notes\n\n"
        )
    return note_path

# ── Main ──────────────────────────────────────────────────────────────────────

def main():
    ap = argparse.ArgumentParser(description="Intelligent vault dead-end resolver")
    ap.add_argument("--apply",  action="store_true", help="Apply changes (default: dry run)")
    ap.add_argument("--limit",  type=int, default=60, help="Max unique broken links to process (default 60)")
    ap.add_argument("--delay",  type=float, default=0.25, help="Seconds between API calls (default 0.25)")
    args = ap.parse_args()

    dry_run = not args.apply
    vault   = get_vault()
    api_key = _get_moonshot_key()

    print(f"Vault : {vault}")
    print(f"Mode  : {'DRY RUN — no files will be changed' if dry_run else 'APPLY'}")
    print()

    files = get_markdown_files(vault)
    print(f"Scanning {len(files)} markdown files…")

    # Build broken-link list: {link: [(source_rel, context), ...]}
    broken: dict[str, list[tuple[str, str]]] = {}
    for f in files:
        try:
            text = f.read_text(encoding="utf-8", errors="ignore")
        except Exception:
            continue
        rel = str(f.relative_to(vault))
        for link, ctx in extract_links_with_context(text):
            if not resolve_link(link, vault).exists():
                broken.setdefault(link, []).append((rel, ctx))

    print(f"Found  {sum(len(v) for v in broken.values())} broken occurrences "
          f"across {len(broken)} unique links\n")

    to_process = list(broken.items())[:args.limit]
    created = removed = skipped = errors = 0
    verdicts: list[tuple[str, str, str, str]] = []   # link, source, decision, reason

    for i, (link, occurrences) in enumerate(to_process, 1):
        primary_source, primary_ctx = occurrences[0]
        print(f"[{i:>3}/{len(to_process)}] [[{link}]]  ({len(occurrences)} occurrence{'s' if len(occurrences)>1 else ''})")
        print(f"         in: {primary_source}")

        decision, reason = ask_moonshot(link, primary_ctx, primary_source, api_key)
        verdicts.append((link, primary_source, decision, reason))
        print(f"         → {decision}: {reason}")

        if not dry_run:
            if decision == "SKIP":
                print(f"         ⏭️  skipped: {reason}")
                continue
            elif decision == "CREATE":
                try:
                    p = create_stub(link, vault, primary_source, reason)
                    print(f"         ✅ stub → {p.relative_to(vault)}")
                    created += 1
                except Exception as e:
                    print(f"         ❌ create failed: {e}")
                    errors += 1
            else:  # REMOVE — apply to every file that contains this link
                for f in files:
                    try:
                        text = f.read_text(encoding="utf-8", errors="ignore")
                        if f"[[{link}" in text or f"[[{link}|" in text:
                            new_text = remove_wikilink(text, link)
                            if new_text != text:
                                f.write_text(new_text)
                    except Exception as e:
                        print(f"         ⚠️  {f.name}: {e}")
                        errors += 1
                print(f"         🗑️  removed from {len(occurrences)} file(s)")
                removed += 1

        if i < len(to_process):
            time.sleep(args.delay)

    # ── Summary ──────────────────────────────────────────────────────────────
    print()
    print("─" * 60)
    create_n = sum(1 for _, _, d, _ in verdicts if d == "CREATE")
    remove_n = sum(1 for _, _, d, _ in verdicts if d == "REMOVE")

    skip_n  = sum(1 for _, _, d, _ in verdicts if d == "SKIP")

    if dry_run:
        print(f"DRY RUN: would CREATE {create_n} stubs, REMOVE {remove_n} links, SKIP {skip_n}")
        print("\nFull verdict list:")
        for link, src, dec, reason in verdicts:
            print(f"  {'✅ CREATE' if dec=='CREATE' else '🗑️  REMOVE'}  [[{link}]]  — {reason}")
        print("\nRun with --apply to execute.")
    else:
        print(f"Done: {created} stubs created · {removed} links removed · {skipped} skipped · {errors} errors")
        try:
            result = subprocess.run(
                ["python3", str(Path(__file__).parent / "life_memory.py"), "audit", "--summary"],
                capture_output=True, text=True, cwd=str(vault)
            )
            print("New vault health:", result.stdout.strip())
        except Exception:
            pass

if __name__ == "__main__":
    main()
```

## File: scripts/life_memory.py
size: 19514
sha: e15e618bcfabcad56374d8a9128a45cd801acadb
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/scripts/life_memory.py

```text
#!/usr/bin/env python3
"""Obsidian Life Memory CLI.

Portable helper for managing a personal memory vault with Obsidian CLI.
Includes server-safe "ghost mode" file fallback, compact distillation,
and automatic wikilink weaving for known entities.
"""

from __future__ import annotations

import argparse
import json
import os
import re
import shlex
import subprocess
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Iterable, List

DEFAULT_VAULT = Path.home() / ".openclaw" / "workspace"
DEFAULT_STATE_DIR = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local" / "state")) / "obsidian-life-memory"
STATE_FILE = DEFAULT_STATE_DIR / "vault_config.json"

IDENTITY_FILES = {"SOUL.md", "IDENTITY.md", "USER.md"}
CONTEXT_FILES = {"LIFE_CONTEXT.md", "TOOLS.md", "AGENTS.md", "HEARTBEAT.md", "MEMORY.md"}
DAILY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}\.md$")

class LifeMemoryError(RuntimeError):
    pass

@dataclass
class ConfigStore:
    state_file: Path = STATE_FILE

    def load(self) -> dict:
        if not self.state_file.exists():
            return {"vault_path": str(DEFAULT_VAULT)}
        return json.loads(self.state_file.read_text(encoding="utf-8"))

    def save(self, data: dict) -> None:
        self.state_file.parent.mkdir(parents=True, exist_ok=True)
        self.state_file.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")

@dataclass
class ObsidianCLI:
    vault_path: Path
    # Server-safe default; override with OBSIDIAN_BIN if needed.
    binary: str = os.environ.get("OBSIDIAN_BIN", "obsidian-cli")

    def run(self, command: str, *args: str) -> str:
        cmd = [self.binary, command, *args]

        env = os.environ.copy()
        if env.get("DISPLAY") is None:
            env["DISPLAY"] = ":99"

        try:
            proc = subprocess.run(
                cmd,
                cwd=self.vault_path,
                env=env,
                text=True,
                capture_output=True,
                check=False,
            )
        except FileNotFoundError as exc:
            raise LifeMemoryError("Obsidian CLI binary not found. Install `obsidian-cli` (or set OBSIDIAN_BIN).") from exc

        if proc.returncode != 0:
            raise LifeMemoryError(proc.stderr.strip() or f"Obsidian command failed: {' '.join(map(shlex.quote, cmd))}")
        return proc.stdout.strip()

@dataclass
class VaultIO:
    vault: Path

    def _resolve_inside(self, rel: str) -> Path:
        p = (self.vault / rel).resolve()
        if not str(p).startswith(str(self.vault.resolve())):
            raise LifeMemoryError("Path escapes vault")
        return p

    def read(self, rel: str) -> str:
        p = self._resolve_inside(rel)
        if not p.exists() or not p.is_file():
            raise LifeMemoryError(f"File not found: {rel}")
        return p.read_text(encoding="utf-8", errors="ignore")

    def today_file(self) -> Path:
        d = self.vault / "Daily"
        d.mkdir(parents=True, exist_ok=True)
        f = d / f"{datetime.now().strftime('%Y-%m-%d')}.md"
        if not f.exists():
            f.write_text(f"# {f.stem}\n\n", encoding="utf-8")
        return f

    def daily_append(self, content: str) -> None:
        f = self.today_file()
        with f.open("a", encoding="utf-8") as fh:
            if not content.startswith("\n"):
                fh.write("\n")
            fh.write(content)
            if not content.endswith("\n"):
                fh.write("\n")

    def search(self, query: str, limit: int = 200) -> str:
        pat = re.compile(re.escape(query), re.IGNORECASE)
        out: list[str] = []
        for md in self.vault.rglob("*.md"):
            if "/.obsidian/" in str(md):
                continue
            try:
                txt = md.read_text(encoding="utf-8", errors="ignore")
            except Exception:
                continue
            for i, line in enumerate(txt.splitlines(), start=1):
                if pat.search(line):
                    out.append(f"{md.relative_to(self.vault)}:{i}:{line}")
                    if len(out) >= limit:
                        return "\n".join(out)
        return "\n".join(out)

@dataclass
class Organizer:
    vault: Path
    apply: bool = False

    def _move(self, src: Path, dst: Path) -> None:
        action = "MOVE" if self.apply else "DRY-RUN"
        print(f"[{action}] {src.relative_to(self.vault)} -> {dst.relative_to(self.vault)}")
        if self.apply:
            dst.parent.mkdir(parents=True, exist_ok=True)
            src.rename(dst)

    def _iter_root_files(self) -> Iterable[Path]:
        for path in self.vault.iterdir():
            if path.is_file():
                yield path

    def run(self) -> None:
        for folder in ["Identity", "Context", "Daily", "Archives"]:
            target = self.vault / folder
            if self.apply:
                target.mkdir(exist_ok=True)

        for item in self._iter_root_files():
            name = item.name
            if name in IDENTITY_FILES:
                self._move(item, self.vault / "Identity" / name)
            elif name in CONTEXT_FILES:
                self._move(item, self.vault / "Context" / name)
            elif DAILY_RE.match(name):
                self._move(item, self.vault / "Daily" / name)

        memory_dir = self.vault / "memory"
        if memory_dir.exists() and memory_dir.is_dir():
            for item in memory_dir.iterdir():
                if item.is_file() and DAILY_RE.match(item.name):
                    self._move(item, self.vault / "Daily" / item.name)

        self._update_obsidianignore()

    def _update_obsidianignore(self) -> None:
        rules = [
            ".git/",
            "node_modules/",
            "__pycache__/",
            "*.pyc",
            "*.sqlite",
            "*.db",
            "*_env/",
            "venv/",
            ".venv/",
            "Archives/",
        ]
        path = self.vault / ".obsidianignore"
        existing = []
        if path.exists():
            existing = [line.strip() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]

        merged = sorted(set(existing + rules))
        action = "WRITE" if self.apply else "DRY-RUN"
        print(f"[{action}] .obsidianignore ({len(merged)} rules)")
        if self.apply:
            path.write_text("\n".join(merged) + "\n", encoding="utf-8")

def _store_and_vault() -> tuple[ConfigStore, Path]:
    store = ConfigStore()
    config = store.load()
    vault_path = Path(config.get("vault_path", str(DEFAULT_VAULT))).expanduser().resolve()
    return store, vault_path

def _parse_now_entities(vault: Path) -> list[str]:
    entities: set[str] = set()
    now_file = vault / "Context" / "now.md"
    if now_file.exists():
        text = now_file.read_text(encoding="utf-8", errors="ignore")
        for m in re.finditer(r"\[\[(?:[^\]|]+\|)?([^\]]+)\]\]", text):
            label = m.group(1).strip()
            if label and len(label) > 2:
                entities.add(label)

    for folder in ["Projects", "People", "Places", "Vendors", "Events"]:
        d = vault / folder
        if d.exists():
            for f in d.glob("*.md"):
                entities.add(f.stem.replace("-", " ").title())

    return sorted(entities, key=len, reverse=True)

def _autoweave(text: str, entities: list[str]) -> str:
    if not entities:
        return text

    placeholders: list[str] = []

    def _hold(m: re.Match[str]) -> str:
        placeholders.append(m.group(0))
        return f"__WL_{len(placeholders)-1}__"

    tmp = re.sub(r"\[\[[^\]]+\]\]", _hold, text)

    for ent in entities:
        pat = re.compile(rf"\b({re.escape(ent)})\b", re.IGNORECASE)

        def repl(m: re.Match[str]) -> str:
            s = m.group(1)
            if s.startswith("[["):
                return s
            return f"[[{s}]]"

        tmp = pat.sub(repl, tmp)

    for i, original in enumerate(placeholders):
        tmp = tmp.replace(f"__WL_{i}__", original)

    return tmp

def cmd_set_vault(args: argparse.Namespace) -> None:
    store = ConfigStore()
    path = Path(args.vault_path).expanduser().resolve()
    store.save({"vault_path": str(path)})
    print(path)

def cmd_show_vault(_: argparse.Namespace) -> None:
    _, vault = _store_and_vault()
    print(vault)

def cmd_search(args: argparse.Namespace) -> None:
    _, vault = _store_and_vault()
    io = VaultIO(vault)
    try:
        cli = ObsidianCLI(vault)
        print(cli.run("search", f"query={args.query}", "matches"))
    except LifeMemoryError:
        print(io.search(args.query))

def cmd_read(args: argparse.Namespace) -> None:
    _, vault = _store_and_vault()
    io = VaultIO(vault)
    if bool(args.file) == bool(args.path):
        raise LifeMemoryError("Provide exactly one of --file or --path.")

    rel = args.file or args.path
    try:
        cli = ObsidianCLI(vault)
        key = "file" if args.file else "path"
        print(cli.run("read", f"{key}={rel}"))
    except LifeMemoryError:
        print(io.read(rel))

def cmd_log_event(args: argparse.Namespace) -> None:
    _, vault = _store_and_vault()
    io = VaultIO(vault)

    entities = _parse_now_entities(vault)
    event_text = _autoweave(args.event.strip(), entities)
    details_text = _autoweave(args.details.strip(), entities) if args.details.strip() else ""

    timestamp = datetime.now().strftime("%H:%M")
    tags = " ".join(f"#{tag.strip()}" for tag in args.tags.split(",") if tag.strip())
    details = f": {details_text}" if details_text else ""
    content = f"\n- **{timestamp}** [{args.category}] {event_text}{details} {tags}".rstrip()

    try:
        cli = ObsidianCLI(vault)
        cli.run("daily:append", f"content={content}", "silent")
    except LifeMemoryError:
        io.daily_append(content)
    print("logged")

def cmd_organize(args: argparse.Namespace) -> None:
    _, vault = _store_and_vault()
    if not vault.exists():
        raise LifeMemoryError(f"Vault path does not exist: {vault}")
    Organizer(vault=vault, apply=args.apply).run()

def _extract_event_lines(text: str) -> List[str]:
    lines = []
    in_events = False
    for raw in text.splitlines():
        line = raw.strip()
        if line.lower().startswith("## "):
            in_events = line.lower() == "## events"
            continue
        if in_events and line.startswith("-"):
            lines.append(line)
    return lines

def _compress_events(event_lines: list[str]) -> list[str]:
    if not event_lines:
        return []

    keepers: list[str] = []
    high_signal = re.compile(
        r"(decision|decided|deadline|due|meeting|appointment|assessment|payment|paid|moved|move|booked|confirm|urgent|call)",
        re.IGNORECASE,
    )

    for line in event_lines:
        if "[[" in line or high_signal.search(line):
            keepers.append(line)

    if not keepers:
        keepers = event_lines[:6]

    # dedupe + cap
    out: list[str] = []
    seen: set[str] = set()
    for line in keepers:
        key = line.strip().lower()
        if key in seen:
            continue
        seen.add(key)
        out.append(line)
        if len(out) >= 12:
            break
    return out

def cmd_distill(args: argparse.Namespace) -> None:
    _, vault = _store_and_vault()
    date = args.date
    daily_candidates = [vault / "memory" / f"{date}.md", vault / "Daily" / f"{date}.md"]
    daily_file = next((p for p in daily_candidates if p.exists()), daily_candidates[0])
    if not daily_file.exists():
        raise LifeMemoryError(f"Daily note not found: {daily_candidates[0]} or {daily_candidates[1]}")

    daily_text = daily_file.read_text(encoding="utf-8")
    event_lines = _extract_event_lines(daily_text)
    compact = _compress_events(event_lines)
    if not compact:
        print("no-events")
        return

    memory_file = vault / "MEMORY.md"
    if not memory_file.exists():
        memory_file.write_text("# MEMORY\n\n", encoding="utf-8")

    existing_memory = memory_file.read_text(encoding="utf-8")
    section_header = f"## Distilled {date}"
    if section_header in existing_memory:
        # Replace existing section instead of appending a duplicate
        pattern = re.compile(
            rf"^{re.escape(section_header)}$.*?(?=^## |\Z)",
            re.MULTILINE | re.DOTALL,
        )
        existing_memory = pattern.sub("", existing_memory).rstrip() + "\n"
        memory_file.write_text(existing_memory, encoding="utf-8")
        print(f"replaced existing distill for {date}")

    stamp = datetime.now().strftime("%Y-%m-%d %H:%M")
    block = [
        f"## Distilled {date}",
        f"- Source: [[memory/{date}]]",
        f"- Updated: {stamp}",
        f"- Compression: kept {len(compact)}/{len(event_lines)} high-signal events",
        "- Highlights:",
    ]
    block.extend([f"  {line}" if not line.startswith("  ") else line for line in compact])
    memory_file.write_text(memory_file.read_text(encoding="utf-8") + "\n" + "\n".join(block) + "\n", encoding="utf-8")
    print(f"distilled {len(compact)} high-signal events")

def _get_all_markdown_files(vault: Path) -> List[Path]:
    """Get all markdown files in vault, excluding hidden folders."""
    files: List[Path] = []
    for md in vault.rglob("*.md"):
        # Skip hidden folders like .git, .obsidian
        if any(part.startswith(".") for part in md.relative_to(vault).parts):
            continue
        files.append(md)
    return files

def _extract_wikilinks(text: str) -> List[str]:
    """Extract wikilinks from text, handling aliases."""
    links: List[str] = []
    # Match [[Page]] or [[Page|Alias]]
    for m in re.finditer(r"\[\[([^|\]]+)(?:\|[^\]]+)?\]\]", text):
        link = m.group(1).strip()
        if link:
            links.append(link)
    return links

def _resolve_link(link: str, vault: Path) -> Path:
    """Resolve a wikilink to a potential file path."""
    # Handle subfolder links like "Projects/athens-move"
    link_path = link.replace(" ", "-").lower()
    if "/" in link:
        return vault / f"{link_path}.md"
    # Try common folders
    for folder in ["", "Projects", "People", "Places", "Vendors", "Events", "Daily", "Context", "Identity"]:
        candidate = vault / folder / f"{link_path}.md"
        if candidate.exists():
            return candidate
        # Case-insensitive fallback (catches HEARTBEAT.md, SOUL.md etc.)
        parent = vault / folder if folder else vault
        if parent.exists():
            for f in parent.iterdir():
                if f.suffix == ".md" and f.stem.lower() == link_path:
                    return f
    # Default to root
    return vault / f"{link_path}.md"

def cmd_audit(args: argparse.Namespace) -> None:
    _, vault = _store_and_vault()

    if not vault.exists():
        raise LifeMemoryError(f"Vault does not exist: {vault}")
    
    files = _get_all_markdown_files(vault)
    
    # Build graph
    all_links: dict[str, List[str]] = {}
    all_notes: set[str] = set()
    link_targets: set[str] = set()
    
    for f in files:
        rel_path = f.relative_to(vault)
        note_name = rel_path.stem
        all_notes.add(str(rel_path))
        
        try:
            text = f.read_text(encoding="utf-8", errors="ignore")
            links = _extract_wikilinks(text)
            all_links[str(rel_path)] = links
            for link in links:
                resolved = _resolve_link(link, vault)
                link_targets.add(str(resolved.relative_to(vault)))
        except Exception:
            all_links[str(rel_path)] = []
    
    # orphans: notes not referenced by any other note
    referenced = set()
    for source, targets in all_links.items():
        for link in targets:
            resolved = _resolve_link(link, vault)
            try:
                referenced.add(str(resolved.relative_to(vault)))
            except ValueError:
                pass
    
    orphans = sorted(all_notes - referenced)
    
    # deadends: notes that don't reference any other notes
    deadends = sorted([f for f in all_notes if not all_links.get(f, [])])
    
    # unresolved: links pointing to non-existent files
    unresolved = []
    for source, targets in all_links.items():
        for link in targets:
            resolved = _resolve_link(link, vault)
            if not resolved.exists():
                unresolved.append((source, link))
    
    # Output
    if args.summary:
        # Compact summary mode for cron/monitoring
        total_notes = len(all_notes)
        print(f"vault_health: orphans={len(orphans)} deadends={len(deadends)} unresolved={len(unresolved)} total_notes={total_notes}")
        return

    print(f"## orphans ({len(orphans)} notes with no incoming links)")
    if orphans:
        for o in orphans[:20]:  # Limit output
            print(f"  - {o}")
        if len(orphans) > 20:
            print(f"  ... and {len(orphans) - 20} more")
    else:
        print("  (none found)")

    print(f"\n## deadends ({len(deadends)} notes with no outgoing links)")
    if deadends:
        for d in deadends[:20]:
            print(f"  - {d}")
        if len(deadends) > 20:
            print(f"  ... and {len(deadends) - 20} more")
    else:
        print("  (none found)")

    print(f"\n## unresolved ({len(unresolved)} broken links)")
    if unresolved:
        for source, link in unresolved[:20]:
            print(f"  - {source} -> [[{link}]]")
        if len(unresolved) > 20:
            print(f"  ... and {len(unresolved) - 20} more")
    else:
        print("  (none found)")

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Obsidian Life Memory CLI")
    sub = parser.add_subparsers(dest="command", required=True)

    p = sub.add_parser("set-vault", help="Persist the vault path")
    p.add_argument("--vault-path", required=True)
    p.set_defaults(func=cmd_set_vault)

    p = sub.add_parser("show-vault", help="Print the current vault path")
    p.set_defaults(func=cmd_show_vault)

    p = sub.add_parser("search", help="Search the vault")
    p.add_argument("--query", required=True)
    p.set_defaults(func=cmd_search)

    p = sub.add_parser("read", help="Read a note via Obsidian CLI")
    p.add_argument("--file")
    p.add_argument("--path")
    p.set_defaults(func=cmd_read)

    p = sub.add_parser("log-event", help="Append an event to today's daily note")
    p.add_argument("--category", required=True)
    p.add_argument("--event", required=True)
    p.add_argument("--details", default="")
    p.add_argument("--tags", default="")
    p.set_defaults(func=cmd_log_event)

    p = sub.add_parser("organize", help="Normalize vault layout")
    p.add_argument("--apply", action="store_true", help="Apply changes (default is dry-run)")
    p.set_defaults(func=cmd_organize)

    p = sub.add_parser("distill", help="Promote daily events to MEMORY.md")
    p.add_argument("--date", required=True, help="YYYY-MM-DD")
    p.set_defaults(func=cmd_distill)

    p = sub.add_parser("audit", help="Run graph health checks")
    p.add_argument("--summary", action="store_true", help="Show compact summary for monitoring")
    p.set_defaults(func=cmd_audit)

    return parser

def main() -> int:
    parser = build_parser()
    args = parser.parse_args()
    try:
        args.func(args)
        return 0
    except LifeMemoryError as exc:
        print(f"error: {exc}")
        return 2

if __name__ == "__main__":
    raise SystemExit(main())
```

## File: scripts/sync_live_copy.sh
size: 622
sha: 1280cb500a1044f51b86d663b1aabced39c70ab4
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/scripts/sync_live_copy.sh

```text
#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CANONICAL_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
SRC="${1:-$CANONICAL_ROOT/}"
DST="${2:-/root/.openclaw/workspace/skills/obsidian-life-memory/}"

mkdir -p "$DST"

SRC_REAL="$(realpath "$SRC")"
DST_REAL="$(realpath "$DST")"

if [[ "$SRC_REAL" == "$DST_REAL" ]]; then
  echo "Sync skipped: source and destination are the same ($SRC_REAL)"
  exit 0
fi

rsync -a --delete \
  --exclude '.git/' \
  --exclude 'local-overrides/' \
  --exclude 'scripts/__pycache__/' \
  "$SRC" "$DST"

echo "Synced $(date -u +%FT%TZ): $SRC -> $DST"
```

## File: references/life-patterns.md
size: 848
sha: 4ce75f0e64f59b4f61080bf8f91ab40bfaf6cca7
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/references/life-patterns.md

````text
# Life Memory Patterns

## Daily Note

Path: `memory/YYYY-MM-DD.md`

```markdown
---
type: daily-log
created: 2026-02-15
tags: [daily, log]
---

# 2026-02-15

## Events
- **09:10** [Planning] Finalized school shortlist [[Athens Move]] [[Sxoli Moraiti]]
- **13:40** [Health] Appointment confirmed [[Maya]] [[Doctor Follow-up]]

## Connectors
- [[SOUL]]
- [[USER]]
- [[LIFE_CONTEXT]]
```

## Long-Term Memory Pattern

Path: `MEMORY.md`

```markdown
## Distilled 2026-02-15
- Source: [[memory/2026-02-15]]
- Updated: 2026-02-15 21:00
- **09:10** [Planning] Finalized school shortlist [[Athens Move]] [[Sxoli Moraiti]]
```

## Graph Hygiene

- Every new event should link to at least one stable hub note.
- Prefer reusable entities (`[[Athens Move]]`, `[[Maya]]`) over plain text.
- Keep internal tool clutter out of the graph using `.obsidianignore`.
````

## File: references/obsidian-cli-notes.md
size: 866
sha: edcfc2d9444f137b3bfc1476088502f101f5d5d2
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/references/obsidian-cli-notes.md

```text
# Obsidian CLI Notes

This skill assumes the official Obsidian CLI is available and that OpenClaw calls it through the compatibility adapter at `/usr/local/bin/obsidian-cli`.

## Commands used by this skill

- `obsidian read path=<note.md>` / `obsidian read file=<name>`
- `obsidian daily:read`, `obsidian daily:append content=<text>`
- `obsidian search query=<q>` and `obsidian search:context query=<q>`
- Graph checks when available: `unresolved`, `orphans`, `deadends`

## Runtime notes

- When running as root, Obsidian should be started with `--no-sandbox`.
- In headless environments, a display such as `:99` is often required for the app process.
- Obsidian 1.12.7 changed the CLI socket path on macOS/Linux; use the matching official app+CLI pair.
- Override binary path with `OBSIDIAN_BIN=/full/path/to/obsidian-cli` when calling the official CLI directly.
```

## File: .gitignore
size: 36
sha: c0870e9fe59d5875c9b2cc7287b928317ea68bd8
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/.gitignore

```text
__pycache__/
*.pyc
state/
.DS_Store
```

## File: agents/openai.yaml
size: 490
sha: 226d8e75ba9b62d3d400cbe6775a417a98ba046f
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/agents/openai.yaml

```text
schema_version: v1
name_for_human: Obsidian Life Memory
name_for_model: obsidian-life-memory
description_for_human: Maintain an Obsidian life-memory vault with daily logging and distillation.
description_for_model: Use this skill to manage an Obsidian-backed personal memory vault, including context retrieval, daily event logging, organization, and memory distillation.
default_prompt: Help me maintain my Obsidian life memory vault and keep long-term memory synchronized from daily logs.
```

## File: bin/obsidian-cli
size: 4225
sha: 346d2505576fdeab8a0dc1d5b7ca998ad3f0705a
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/bin/obsidian-cli

```text
#!/usr/bin/env bash
set -euo pipefail

OFFICIAL_CLI="${OBSIDIAN_OFFICIAL_CLI:-/opt/obsidian-1.12.7/obsidian-cli}"
VAULT_NAME="${OBSIDIAN_VAULT_NAME:-workspace}"
VAULT_PATH="${OBSIDIAN_VAULT_PATH:-/root/.openclaw/workspace}"

cmd="${1:-}"
shift || true

declare -A ARGS
for arg in "$@"; do
  key="${arg%%=*}"
  val="${arg#*=}"
  val="${val%\"}"
  val="${val#\"}"
  val="${val%\'}"
  val="${val#\'}"
  ARGS["$key"]="$val"
done

call_official() {
  "$OFFICIAL_CLI" vault="$VAULT_NAME" "$@"
}

resolve_path() {
  local p="${ARGS[path]:-}"
  if [[ -z "$p" ]]; then
    printf '%s' ""
    return
  fi
  if [[ "$p" == "$VAULT_PATH/"* ]]; then
    p="${p#$VAULT_PATH/}"
  fi
  printf '%s' "$p"
}

case "$cmd" in
  read)
    PATH_ARG="$(resolve_path)"
    call_official read path="$PATH_ARG"
    ;;

  append)
    PATH_ARG="$(resolve_path)"
    CONTENT="${ARGS[content]:-}"
    call_official append path="$PATH_ARG" content="$CONTENT"
    ;;

  create)
    PATH_ARG="$(resolve_path)"
    CONTENT="${ARGS[content]:-}"
    if [[ "${ARGS[force]:-false}" == "true" ]]; then
      call_official create path="$PATH_ARG" content="$CONTENT" overwrite
    else
      call_official create path="$PATH_ARG" content="$CONTENT"
    fi
    ;;

  list)
    FOLDER="${ARGS[folder]:-}"
    if [[ "$FOLDER" == "$VAULT_PATH/"* ]]; then
      FOLDER="${FOLDER#$VAULT_PATH/}"
    fi
    call_official files folder="$FOLDER"
    ;;

  move)
    SRC="$(resolve_path)"
    DST="${ARGS[to]:-}"
    if [[ "$DST" == "$VAULT_PATH/"* ]]; then
      DST="${DST#$VAULT_PATH/}"
    fi
    call_official move path="$SRC" to="$DST"
    ;;

  delete)
    PATH_ARG="$(resolve_path)"
    call_official delete path="$PATH_ARG" permanent
    ;;

  edit)
    PATH_ARG="$(resolve_path)"
    FIND="${ARGS[find]:-}"
    REPLACE="${ARGS[replace]:-}"
    REGEX="${ARGS[regex]:-false}"
    TMP="$(mktemp)"
    call_official read path="$PATH_ARG" > "$TMP"
    python3 - "$TMP" "$FIND" "$REPLACE" "$REGEX" <<'PY'
import re, sys, pathlib
p = pathlib.Path(sys.argv[1])
find = sys.argv[2]
replace = sys.argv[3]
regex = sys.argv[4].lower() == 'true'
text = p.read_text()
if regex:
    new, n = re.subn(find, replace, text, count=1, flags=re.MULTILINE)
else:
    n = 1 if find in text else 0
    new = text.replace(find, replace, 1)
if n == 0:
    print('obsidian-cli: edit find text not found', file=sys.stderr)
    sys.exit(1)
p.write_text(new)
PY
    call_official create path="$PATH_ARG" content="$(cat "$TMP")" overwrite >/dev/null
    rm -f "$TMP"
    echo "Edited: $PATH_ARG"
    ;;

  daily:read)
    call_official daily:read
    ;;

  daily:append)
    CONTENT="${ARGS[content]:-}"
    call_official daily:append content="$CONTENT"
    ;;

  daily:create)
    CONTENT="${ARGS[content]:-}"
    DAILY_PATH="$(call_official daily:path)"
    call_official create path="$DAILY_PATH" content="$CONTENT" overwrite
    ;;

  search)
    QUERY="${ARGS[query]:-${1:-}}"
    call_official search query="$QUERY"
    ;;

  search-content)
    QUERY="${ARGS[query]:-${1:-}}"
    MAX="${ARGS[max]:-8}"
    CONTEXT="${ARGS[context]:-3}"
    call_official search:context query="$QUERY" limit="$MAX" context="$CONTEXT"
    ;;

  backlinks)
    PATH_ARG="$(resolve_path)"
    call_official backlinks path="$PATH_ARG"
    ;;

  query)
    KEY="${ARGS[key]:-}"
    VALUE="${ARGS[value]:-}"
    if [[ -n "$VALUE" ]]; then
      call_official search:context query="$KEY: $VALUE" limit="20" context="1"
    else
      call_official search:context query="$KEY:" limit="20" context="1"
    fi
    ;;

  tags)
    TAG="${ARGS[tag]:-}"
    if [[ -n "$TAG" ]]; then
      call_official search query="#$TAG"
    else
      call_official tags
    fi
    ;;

  print-default)
    if [[ "${1:-}" == "--path-only" ]]; then
      printf '%s\n' "$VAULT_PATH"
    else
      printf '%s\n' "$VAULT_NAME"
    fi
    ;;

  status)
    printf 'Vault:  %s\n' "$VAULT_PATH"
    printf 'CLI:    %s\n' "$OFFICIAL_CLI"
    printf 'Daily:  %s\n' "$(call_official daily:path)"
    printf 'Version:%s\n' " $(call_official version)"
    ;;

  vaults|version|files|properties|property:read|search:context|daily:path)
    call_official "$cmd" "$@"
    ;;

  *)
    exec "$OFFICIAL_CLI" vault="$VAULT_NAME" "$cmd" "$@"
    ;;
esac
```

## File: bin/obsidian-life-memory.js
size: 10866
sha: 38840b791c79a9a108a3d623b9422bd79077af72
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/bin/obsidian-life-memory.js

```text
#!/usr/bin/env node
import fs from 'fs';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import { spawnSync } from 'child_process';
import readline from 'readline/promises';
import { stdin as input, stdout as output } from 'process';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const DEFAULT_WORKSPACE = '/root/.openclaw/workspace';
const LIVE_SKILL_DIR = path.join(DEFAULT_WORKSPACE, 'skills', 'obsidian-life-memory');
const LIVE_HOOK_PATH = path.join(DEFAULT_WORKSPACE, 'hooks', 'obsidian-preprompt.js');
const LOCAL_INSTALL_STATE = path.join(DEFAULT_WORKSPACE, 'Context', 'skill-installs', 'obsidian-life-memory-install.json');

function run(cmd, args, opts = {}) {
  const res = spawnSync(cmd, args, { encoding: 'utf8', ...opts });
  if (res.status !== 0) {
    throw new Error((res.stderr || res.stdout || `command failed: ${cmd}`).trim());
  }
  return (res.stdout || '').trim();
}

function runSafe(cmd, args, opts = {}) {
  const res = spawnSync(cmd, args, { encoding: 'utf8', ...opts });
  return {
    ok: res.status === 0,
    out: (res.stdout || '').trim(),
    err: (res.stderr || '').trim(),
    code: res.status,
  };
}

function ensureDir(p) {
  fs.mkdirSync(p, { recursive: true });
}

function writeJsonAtomic(filePath, obj) {
  ensureDir(path.dirname(filePath));
  const tmp = `${filePath}.tmp`;
  fs.writeFileSync(tmp, `${JSON.stringify(obj, null, 2)}\n`, 'utf8');
  fs.renameSync(tmp, filePath);
}

function parseArgs(argv) {
  const [cmd = 'help', ...rest] = argv;
  const flags = new Set(rest.filter((x) => x.startsWith('--')));
  const values = {};
  for (let i = 0; i < rest.length; i += 1) {
    if (rest[i].startsWith('--') && rest[i + 1] && !rest[i + 1].startsWith('--')) {
      values[rest[i]] = rest[i + 1];
      i += 1;
    }
  }
  return { cmd, flags, values };
}

function usage() {
  console.log(`obsidian-life-memory CLI\n\nCommands:\n  init [--yes] [--dry-run] [--enable-heartbeat] [--timezone <tz>] [--every <expr>]\n  sync\n  doctor\n  rollback [--dry-run]\n\nExamples:\n  npx obsidian-life-memory init\n  npx obsidian-life-memory init --yes --enable-heartbeat --timezone Europe/Athens\n  npx obsidian-life-memory doctor\n  npx obsidian-life-memory rollback\n`);
}

function getConfig(pathKey) {
  return runSafe('openclaw', ['config', 'get', pathKey]);
}

function setConfig(pathKey, value, dryRun = false) {
  if (dryRun) {
    console.log(`[dry-run] openclaw config set ${pathKey} ${value}`);
    return;
  }
  run('openclaw', ['config', 'set', pathKey, value]);
}

function snapshotConfig(keys) {
  const snap = { createdAt: new Date().toISOString(), keys: {} };
  for (const key of keys) {
    const r = getConfig(key);
    snap.keys[key] = r.ok ? r.out : null;
  }
  return snap;
}

function restoreConfig(snapshot, dryRun = false) {
  for (const [key, value] of Object.entries(snapshot?.keys || {})) {
    if (value === null || value === '') {
      if (dryRun) console.log(`[dry-run] openclaw config unset ${key}`);
      else runSafe('openclaw', ['config', 'unset', key]);
    } else {
      setConfig(key, value, dryRun);
    }
  }
}

function installHookAndSync(dryRun = false) {
  const syncScript = path.join(ROOT, 'scripts', 'sync_live_copy.sh');
  const adapterSrc = path.join(ROOT, 'bin', 'obsidian-cli');
  const adapterDst = '/usr/local/bin/obsidian-cli';
  if (dryRun) {
    console.log(`[dry-run] bash ${syncScript} ${ROOT}/ ${LIVE_SKILL_DIR}/`);
    console.log(`[dry-run] copy hook -> ${LIVE_HOOK_PATH}`);
    console.log(`[dry-run] install adapter -> ${adapterDst}`);
    return;
  }
  run('bash', [syncScript, `${ROOT}/`, `${LIVE_SKILL_DIR}/`]);
  ensureDir(path.dirname(LIVE_HOOK_PATH));
  fs.copyFileSync(path.join(ROOT, 'hooks', 'obsidian-preprompt.js'), LIVE_HOOK_PATH);
  fs.copyFileSync(adapterSrc, adapterDst);
  fs.chmodSync(adapterDst, 0o755);
}

function applyHeartbeat({ timezone, every, dryRun }) {
  setConfig('hooks.internal.entries.obsidian-preprompt.env.OBSIDIAN_OPTIONAL_CONTEXT_FILES', 'Context/retrieval_policy.md,Context/now.md', dryRun);
  setConfig('agents.defaults.heartbeat.every', every, dryRun);
  setConfig('agents.defaults.heartbeat.activeHours.timezone', timezone, dryRun);
  setConfig('agents.defaults.heartbeat.model', 'google-antigravity/gemini-3-flash', dryRun);
  setConfig('agents.defaults.heartbeat.target', 'none', dryRun);
  setConfig('agents.defaults.heartbeat.prompt', 'Read HEARTBEAT.md strictly and follow it. Nudge-only: if nothing meaningful changed, reply HEARTBEAT_OK only. If you create/update meaningful nodes or detect an urgent action/deadline, send a short Telegram DM to 7874264051 via the message tool, then finish (do not include HEARTBEAT_OK).', dryRun);
}

async function cmdInit({ flags, values }) {
  const dryRun = flags.has('--dry-run');
  const yes = flags.has('--yes');
  let enableHeartbeat = flags.has('--enable-heartbeat');
  let timezone = values['--timezone'] || 'UTC';
  let every = values['--every'] || '30m';

  const keys = [
    'hooks.internal.entries.obsidian-preprompt.env.OBSIDIAN_OPTIONAL_CONTEXT_FILES',
    'agents.defaults.heartbeat.every',
    'agents.defaults.heartbeat.activeHours.timezone',
    'agents.defaults.heartbeat.model',
    'agents.defaults.heartbeat.target',
    'agents.defaults.heartbeat.prompt',
  ];

  if (!yes) {
    const rl = readline.createInterface({ input, output });
    const hb = (await rl.question('Enable Heartbeat Gardening setup? (y/N): ')).trim().toLowerCase();
    enableHeartbeat = hb === 'y' || hb === 'yes';
    if (enableHeartbeat) {
      const tz = (await rl.question(`Timezone [${timezone}]: `)).trim();
      const ev = (await rl.question(`Heartbeat interval [${every}]: `)).trim();
      if (tz) timezone = tz;
      if (ev) every = ev;
    }
    rl.close();
  }

  const snapshot = snapshotConfig(keys);

  console.log('Planned actions:');
  console.log('- Sync canonical skill to live copy');
  console.log('- Install/update obsidian preprompt hook');
  if (enableHeartbeat) {
    console.log(`- Configure heartbeat gardener (every=${every}, timezone=${timezone})`);
  } else {
    console.log('- Leave heartbeat config unchanged');
  }

  if (!yes && !dryRun) {
    const rl2 = readline.createInterface({ input, output });
    const ok = (await rl2.question('Apply these changes? (y/N): ')).trim().toLowerCase();
    rl2.close();
    if (!(ok === 'y' || ok === 'yes')) {
      console.log('Cancelled.');
      return;
    }
  }

  installHookAndSync(dryRun);

  // install templates only if missing
  const ctxDir = path.join(DEFAULT_WORKSPACE, 'Context');
  ensureDir(ctxDir);
  const tplNow = path.join(ROOT, 'templates', 'Context', 'now.example.md');
  const tplPolicy = path.join(ROOT, 'templates', 'Context', 'retrieval_policy.example.md');
  const nowPath = path.join(ctxDir, 'now.md');
  const policyPath = path.join(ctxDir, 'retrieval_policy.md');
  if (!fs.existsSync(nowPath)) {
    if (dryRun) console.log(`[dry-run] create ${nowPath}`);
    else fs.copyFileSync(tplNow, nowPath);
  }
  if (!fs.existsSync(policyPath)) {
    if (dryRun) console.log(`[dry-run] create ${policyPath}`);
    else fs.copyFileSync(tplPolicy, policyPath);
  }

  if (enableHeartbeat) {
    applyHeartbeat({ timezone, every, dryRun });
  }

  if (!dryRun) {
    writeJsonAtomic(LOCAL_INSTALL_STATE, {
      ...snapshot,
      lastAppliedAt: new Date().toISOString(),
      options: { enableHeartbeat, timezone, every },
    });
  }

  console.log(`\nDone.${dryRun ? ' (dry-run)' : ''}`);
  console.log('Run `obsidian-life-memory doctor` to validate setup.');
}

function cmdSync() {
  installHookAndSync(false);
  console.log('Synced skill and hook.');
}

function cmdDoctor() {
  const checks = [];
  checks.push(['canonical repo exists', fs.existsSync(path.join(ROOT, '.git'))]);
  checks.push(['live skill exists', fs.existsSync(LIVE_SKILL_DIR)]);
  checks.push(['live hook exists', fs.existsSync(LIVE_HOOK_PATH)]);
  checks.push(['template now exists', fs.existsSync(path.join(ROOT, 'templates', 'Context', 'now.example.md'))]);
  checks.push(['template policy exists', fs.existsSync(path.join(ROOT, 'templates', 'Context', 'retrieval_policy.example.md'))]);

  // Check if context files are deployed to workspace
  const ctxDir = path.join(DEFAULT_WORKSPACE, 'Context');
  checks.push(['context now.md deployed', fs.existsSync(path.join(ctxDir, 'now.md'))]);
  checks.push(['context retrieval_policy.md deployed', fs.existsSync(path.join(ctxDir, 'retrieval_policy.md'))]);

  // Check vault path configuration
  const vaultConfigPath = path.join(os.homedir(), '.local', 'state', 'obsidian-life-memory', 'vault_config.json');
  let vaultPathConfigured = false;
  let vaultPathExists = false;
  if (fs.existsSync(vaultConfigPath)) {
    try {
      const vaultConfig = JSON.parse(fs.readFileSync(vaultConfigPath, 'utf8'));
      vaultPathConfigured = Boolean(vaultConfig.vault_path);
      if (vaultPathConfigured) {
        vaultPathExists = fs.existsSync(vaultConfig.vault_path);
      }
    } catch {
      // Config file exists but is invalid
    }
  }
  checks.push(['vault path configured', vaultPathConfigured]);
  checks.push(['vault path exists', vaultPathExists]);

  const oc = runSafe('openclaw', ['status']);
  checks.push(['openclaw reachable', oc.ok]);

  const hb = getConfig('agents.defaults.heartbeat.every');
  checks.push(['heartbeat configured', hb.ok && Boolean(hb.out)]);

  let failed = 0;
  for (const [name, ok] of checks) {
    console.log(`${ok ? '✅' : '❌'} ${name}`);
    if (!ok) failed += 1;
  }
  if (failed > 0) process.exitCode = 1;
}

async function cmdRollback({ flags }) {
  const dryRun = flags.has('--dry-run');
  if (!fs.existsSync(LOCAL_INSTALL_STATE)) {
    throw new Error(`No install snapshot found at ${LOCAL_INSTALL_STATE}`);
  }
  const data = JSON.parse(fs.readFileSync(LOCAL_INSTALL_STATE, 'utf8'));
  if (!dryRun) {
    const rl = readline.createInterface({ input, output });
    const ok = (await rl.question('Restore saved OpenClaw config values now? (y/N): ')).trim().toLowerCase();
    rl.close();
    if (!(ok === 'y' || ok === 'yes')) {
      console.log('Cancelled.');
      return;
    }
  }
  restoreConfig(data, dryRun);
  console.log(`Rollback ${dryRun ? 'dry-run ' : ''}complete.`);
}

(async () => {
  try {
    const { cmd, flags, values } = parseArgs(process.argv.slice(2));
    if (cmd === 'help' || cmd === '--help' || cmd === '-h') {
      usage();
      return;
    }
    if (cmd === 'init') return cmdInit({ flags, values });
    if (cmd === 'sync') return cmdSync();
    if (cmd === 'doctor') return cmdDoctor();
    if (cmd === 'rollback') return cmdRollback({ flags });

    usage();
    process.exitCode = 1;
  } catch (err) {
    console.error(`error: ${err.message}`);
    process.exitCode = 1;
  }
})();
```

## File: hooks/obsidian-preprompt.js
size: 19322
sha: 35cfb1ecb49bdff9394410798b1ce78c6ef2f4ff
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/hooks/obsidian-preprompt.js

```text
import { execSync } from 'child_process';
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';

const OBSIDIAN_CLI_BIN = process.env.OBSIDIAN_CLI_BIN || '/usr/local/bin/obsidian-cli';
const OBSIDIAN_DAILY_CMD = `${OBSIDIAN_CLI_BIN} daily:read`;
const OBSIDIAN_READ_PREFIX = `${OBSIDIAN_CLI_BIN} read path=`;
const CLI_TIMEOUT_MS = 3000;
const MAX_SNAPSHOT_CHARS = 12000;
const MAX_SNAPSHOT_TOKENS = Math.ceil(MAX_SNAPSHOT_CHARS / 4);
const MAX_STATE_DAYS = 14;

const GOVERNANCE_FILES = [
  'SOUL.md',
  'MEMORY.md',
  'AGENTS.md',
  'TOOLS.md',
];

const OPTIONAL_CONTEXT_FILES = [
  'Context/security_policy.md',
  'Context/job_routing_policy.md',
  ...String(process.env.OBSIDIAN_OPTIONAL_CONTEXT_FILES || '')
    .split(',')
    .map((value) => value.trim())
    .filter(Boolean),
];

const GOVERNANCE_TOKEN_BUDGET = Math.floor(MAX_SNAPSHOT_TOKENS * 0.4);
const DAILY_TOKEN_BUDGET = Math.floor(MAX_SNAPSHOT_TOKENS * 0.6);

const MAX_RETRIEVAL_SNIPPETS = 4;
const MAX_RETRIEVAL_CHARS = 4500;
const MAX_QUERY_TERMS = 6;
const STOP_WORDS = new Set([
  'a','an','and','are','as','at','be','but','by','for','from','how','i','if','in','into','is','it','its','me','my',
  'of','on','or','our','please','should','so','that','the','their','them','there','this','to','we','what','when',
  'where','which','who','why','with','would','you','your','about','just','tell','show','draft','message','email'
]);
const WRITE_AWARE_PATTERNS = [
  /\bactually\b/i,
  /\bupdate\b/i,
  /\bchanged?\b/i,
  /\bcorrection\b/i,
  /\bpaid\b/i,
  /\bconfirmed?\b/i,
  /\bno longer\b/i,
  /\bnow\b/i,
  /\bnew\b/i,
  /\buse this\b/i,
  /\bshould be\b/i,
  /\bisn't\b/i,
  /\bwasn't\b/i,
  /\bwrong\b/i,
];
const SEARCH_EXCLUDE_DIRS = new Set(['.git','node_modules','hooks','skills','dashboard_project','Archives','.openclaw']);

function resolveVaultRoot() {
  if (process.env.OBSIDIAN_VAULT_PATH) {
    return process.env.OBSIDIAN_VAULT_PATH;
  }

  try {
    const homedir = process.env.HOME || process.env.USERPROFILE || '/root';
    const configPath = path.join(
      homedir,
      '.local',
      'state',
      'obsidian-life-memory',
      'vault_config.json',
    );
    if (fs.existsSync(configPath)) {
      const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
      if (config.vault_path) {
        return config.vault_path;
      }
    }
  } catch {
    // Fall through.
  }

  return process.cwd();
}

function getTodayDateString(now = new Date()) {
  const yyyy = String(now.getFullYear());
  const mm = String(now.getMonth() + 1).padStart(2, '0');
  const dd = String(now.getDate()).padStart(2, '0');
  return `${yyyy}-${mm}-${dd}`;
}

function estimateTokens(text) {
  return Math.ceil(String(text || '').length / 4);
}

function trimTextToTokenBudget(text, tokenBudget) {
  const normalized = String(text || '').replace(/\r\n?/g, '\n').trim();
  if (!normalized || tokenBudget <= 0) {
    return '';
  }

  if (estimateTokens(normalized) <= tokenBudget) {
    return normalized;
  }

  const lines = normalized.split('\n');
  const kept = [];
  let used = 0;

  for (const line of lines) {
    const cost = estimateTokens(`${line}\n`);
    if (used + cost > tokenBudget) {
      break;
    }
    kept.push(line);
    used += cost;
  }

  return kept.join('\n').trim();
}

function computeSha256(text) {
  return crypto.createHash('sha256').update(String(text || ''), 'utf8').digest('hex');
}

function getStateFilePath() {
  return path.join(resolveVaultRoot(), '.obsidian-bootstrap-state.json');
}

function readBootstrapState() {
  const statePath = process.env.OBSIDIAN_BOOTSTRAP_STATE_PATH || getStateFilePath();
  if (!fs.existsSync(statePath)) {
    return {};
  }

  try {
    const parsed = JSON.parse(fs.readFileSync(statePath, 'utf8'));
    return parsed && typeof parsed === 'object' ? parsed : {};
  } catch {
    return {};
  }
}

function writeBootstrapState(state) {
  const statePath = process.env.OBSIDIAN_BOOTSTRAP_STATE_PATH || getStateFilePath();
  const dir = path.dirname(statePath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }

  const entries = Object.entries(state || {}).sort((a, b) => String(b[0]).localeCompare(String(a[0])));
  const trimmed = Object.fromEntries(entries.slice(0, MAX_STATE_DAYS));

  const tmpPath = `${statePath}.tmp`;
  fs.writeFileSync(tmpPath, `${JSON.stringify(trimmed, null, 2)}\n`, 'utf8');
  fs.renameSync(tmpPath, statePath);
}

function readDailyViaCli() {
  return execSync(OBSIDIAN_DAILY_CMD, {
    encoding: 'utf8',
    timeout: CLI_TIMEOUT_MS,
  });
}

function readDailyViaFileFallback() {
  const filename = `${getTodayDateString()}.md`;
  const vaultRoot = resolveVaultRoot();
  const possiblePaths = [
    path.join(vaultRoot, 'Daily', filename),
    path.join(vaultRoot, 'memory', filename),
    path.join(vaultRoot, filename),
  ];

  for (const dailyPath of possiblePaths) {
    if (fs.existsSync(dailyPath)) {
      return fs.readFileSync(dailyPath, 'utf8');
    }
  }

  return '';
}

function readVaultFile(filename) {
  try {
    return execSync(`${OBSIDIAN_READ_PREFIX}${JSON.stringify(filename)}`, {
      encoding: 'utf8',
      timeout: CLI_TIMEOUT_MS,
    });
  } catch {
    const vaultRoot = path.resolve(resolveVaultRoot());
    const filePath = path.resolve(vaultRoot, filename);
    if (!filePath.startsWith(`${vaultRoot}${path.sep}`) && filePath !== vaultRoot) {
      return '';
    }
    if (fs.existsSync(filePath)) {
      return fs.readFileSync(filePath, 'utf8');
    }
    return '';
  }
}

function readGovernanceFiles() {
  const governance = {};
  for (const filename of [...GOVERNANCE_FILES, ...OPTIONAL_CONTEXT_FILES]) {
    const content = readVaultFile(filename);
    if (content) {
      governance[filename] = content;
    }
  }
  return governance;
}

function extractCriticalConstraints(text) {
  if (!text) return '';

  const criticalKeywords = [
    'boundaries',
    'protocol',
    'critical',
    'violation',
    'safety',
    'security',
    'never',
    'always',
    'mandatory',
    'prohibited',
    'banned',
    'warning',
    '⚠️',
    '🚫',
    '❌',
  ];

  const lines = text.split('\n');
  const sections = [];
  let currentContent = [];
  let inCriticalSection = false;

  for (const line of lines) {
    const lower = line.toLowerCase();
    const isHeading = /^#{1,6}\s/.test(line);

    if (isHeading) {
      if (inCriticalSection && currentContent.length > 0) {
        sections.push(currentContent.join('\n').trim());
      }
      currentContent = [line];
      inCriticalSection = criticalKeywords.some((keyword) => lower.includes(keyword));
      continue;
    }

    if (/^\s*[-*]\s+/.test(line) && criticalKeywords.some((keyword) => lower.includes(keyword))) {
      if (!inCriticalSection) {
        currentContent = ['## Critical Rules'];
        inCriticalSection = true;
      }
    }

    if (inCriticalSection) {
      currentContent.push(line);
    }
  }

  if (inCriticalSection && currentContent.length > 0) {
    sections.push(currentContent.join('\n').trim());
  }

  return sections.join('\n\n').trim();
}

function buildGovernanceContext(governanceFiles) {
  const fileLabels = {
    'SOUL.md': 'Behavioral Constraints (SOUL)',
    'MEMORY.md': 'Long-Term Rules & Protocols (MEMORY)',
    'AGENTS.md': 'Operational Protocols (AGENTS)',
    'TOOLS.md': 'Tool Usage Patterns (TOOLS)',
  };

  const sections = [];
  for (const [filename, content] of Object.entries(governanceFiles)) {
    const critical = extractCriticalConstraints(content);
    if (critical) {
      sections.push(`## ${fileLabels[filename] || filename}\n${critical}`);
    }
  }

  return sections.join('\n\n');
}

function findHeadingContext(lines, startIdx) {
  const headings = [];
  for (let index = 0; index <= startIdx; index += 1) {
    if (/^#{1,6}\s/.test(lines[index])) {
      headings.push(lines[index]);
    }
  }
  return headings;
}

function buildObsidianSafeSnapshot(raw, maxChars) {
  const text = String(raw || '').replace(/\r\n?/g, '\n').trim();
  if (!text) {
    return '';
  }
  if (text.length <= maxChars) {
    return text;
  }

  const lines = text.split('\n');
  const picked = [];
  let used = 0;

  for (let index = lines.length - 1; index >= 0; index -= 1) {
    const cost = lines[index].length + 1;
    if (used + cost > Math.floor(maxChars * 0.65)) {
      continue;
    }
    picked.push(index);
    used += cost;
  }

  if (picked.length === 0) {
    return text.slice(-maxChars);
  }

  picked.sort((a, b) => a - b);
  const headingContext = findHeadingContext(lines, picked[0]);
  const output = [...headingContext, ...picked.map((index) => lines[index])];
  return output.join('\n').trim().slice(0, maxChars);
}

function buildTokenAwareDailySnapshot(rawDaily, previousState) {
  const normalized = String(rawDaily || '').replace(/\r\n?/g, '\n');
  const lines = normalized ? normalized.split('\n') : [];
  const lineCount = lines.length;
  const fullSnapshot = buildObsidianSafeSnapshot(normalized, MAX_SNAPSHOT_CHARS);

  let deltaText = '';
  if (previousState && Number.isInteger(previousState.lastLineCount) && lineCount > previousState.lastLineCount) {
    deltaText = lines.slice(previousState.lastLineCount).join('\n').trim();
  }

  const parts = [];
  let remaining = DAILY_TOKEN_BUDGET;

  if (deltaText) {
    const deltaBlock = trimTextToTokenBudget(`Since you last spoke:\n${deltaText}`, remaining);
    if (deltaBlock) {
      parts.push(deltaBlock);
      remaining -= estimateTokens(deltaBlock);
    }
  }

  if (remaining > 0) {
    const summaryBlock = trimTextToTokenBudget(fullSnapshot, remaining);
    if (summaryBlock) {
      parts.push(summaryBlock);
    }
  }

  return {
    dailyText: trimTextToTokenBudget(parts.join('\n\n---\n\n'), DAILY_TOKEN_BUDGET),
    lineCount,
    normalized,
  };
}

function buildOrientationSnapshot({ governanceContext, dailyText }) {
  const parts = [];
  let remaining = MAX_SNAPSHOT_TOKENS;

  if (governanceContext) {
    const governance = trimTextToTokenBudget(governanceContext, GOVERNANCE_TOKEN_BUDGET);
    if (governance) {
      parts.push(`# Behavioral Governance\n${governance}`);
      remaining -= estimateTokens(governance);
    }
  }

  if (dailyText && remaining > 0) {
    const daily = trimTextToTokenBudget(dailyText, Math.min(remaining, DAILY_TOKEN_BUDGET));
    if (daily) {
      parts.push(`# Session Orientation (daily/open items)\n${daily}`);
    }
  }

  return parts.join('\n\n---\n\n').trim();
}

function isLikelyWriteAwarePrompt(prompt) {
  const text = String(prompt || '').trim();
  return WRITE_AWARE_PATTERNS.some((rx) => rx.test(text));
}

function deriveFocusedQueries(prompt) {
  const text = String(prompt || '').replace(/[`*_#>\[\](){}]/g, ' ').replace(/\s+/g, ' ').trim();
  if (!text) return [];

  const quoted = Array.from(text.matchAll(/"([^"]{3,80})"|'([^']{3,80})'/g))
    .map((m) => (m[1] || m[2] || '').trim())
    .filter(Boolean)
    .slice(0, 2);

  const capitalizedPhrases = Array.from(text.matchAll(/\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,3})\b/g))
    .map((m) => m[1].trim())
    .filter((v) => v.length >= 4)
    .slice(0, 3);

  const terms = text.toLowerCase().split(/[^a-z0-9]+/)
    .filter(Boolean)
    .filter((t) => t.length >= 3 && !STOP_WORDS.has(t));
  const uniqTerms = [...new Set(terms)].slice(0, MAX_QUERY_TERMS);

  const queries = [];
  for (const q of [...quoted, ...capitalizedPhrases]) {
    if (!queries.includes(q)) queries.push(q);
  }
  if (uniqTerms.length) {
    const dense = uniqTerms.slice(0, 3).join(' ');
    if (dense && !queries.includes(dense)) queries.push(dense);
  }
  for (const t of uniqTerms.slice(0, 3)) {
    if (!queries.includes(t)) queries.push(t);
  }
  return queries.slice(0, 3);
}

function listVaultTextFiles(root) {
  const out = [];
  function walk(dir, rel='') {
    let entries = [];
    try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
    for (const entry of entries) {
      const relPath = rel ? path.join(rel, entry.name) : entry.name;
      if (entry.isDirectory()) {
        if (SEARCH_EXCLUDE_DIRS.has(entry.name)) continue;
        walk(path.join(dir, entry.name), relPath);
        continue;
      }
      if (!entry.isFile()) continue;
      if (!/\.(md|txt|json)$/i.test(entry.name)) continue;
      out.push(relPath);
    }
  }
  walk(root);
  return out;
}

function scoreCandidate(relPath, content, queries) {
  const hay = `${relPath}\n${String(content || '').slice(0, 4000)}`.toLowerCase();
  let score = 0;
  for (const q of queries) {
    const needle = q.toLowerCase();
    if (!needle) continue;
    if (relPath.toLowerCase().includes(needle)) score += 8;
    if (hay.includes(needle)) score += needle.includes(' ') ? 6 : 3;
  }
  if (score > 0 && /^(memory|Projects|People|Places|Context)\//.test(relPath)) score += 1;
  return score;
}

function buildSnippet(relPath, content, queries) {
  const text = String(content || '').replace(/\r\n?/g, '\n');
  const lines = text.split('\n');
  let best = -1;
  for (let i = 0; i < lines.length; i += 1) {
    const lower = lines[i].toLowerCase();
    if (queries.some((q) => lower.includes(q.toLowerCase()))) { best = i; break; }
  }
  if (best === -1) {
    for (let i = 0; i < lines.length; i += 1) {
      if (/^#{1,3}\s|^-\s|^\|/.test(lines[i])) { best = i; break; }
    }
  }
  if (best === -1) best = 0;
  const start = Math.max(0, best - 3);
  const end = Math.min(lines.length, best + 7);
  const body = lines.slice(start, end).join('\n').trim();
  return `- ${relPath}\n${body}`.trim();
}

function retrieveTargetedVaultContext(prompt) {
  const vaultRoot = path.resolve(resolveVaultRoot());
  const queries = deriveFocusedQueries(prompt);
  if (!queries.length) return { queries: [], snippets: [], writeTargets: [] };

  const files = listVaultTextFiles(vaultRoot);
  const scored = [];
  for (const relPath of files) {
    let content = '';
    try { content = readVaultFile(relPath); } catch { continue; }
    const score = scoreCandidate(relPath, content, queries, prompt);
    if (score > 0) scored.push({ relPath, score, content });
  }
  scored.sort((a, b) => b.score - a.score || a.relPath.localeCompare(b.relPath));
  const top = scored.slice(0, MAX_RETRIEVAL_SNIPPETS);
  const snippets = top.map((item) => buildSnippet(item.relPath, item.content, queries));
  const writeTargets = top.slice(0, 3).map((item) => item.relPath);
  return { queries, snippets, writeTargets };
}

function buildBeforePromptContext(prompt) {
  const retrieval = retrieveTargetedVaultContext(prompt);
  if (!retrieval.snippets.length) return '';

  const parts = [];
  parts.push('# Obsidian Targeted Retrieval');
  parts.push('');
  parts.push(`Focus: ${String(prompt || '').trim().slice(0, 220)}`);
  parts.push(`Queries: ${retrieval.queries.map((q) => JSON.stringify(q)).join(', ')}`);
  parts.push('');
  parts.push('Relevant snippets:');
  parts.push(retrieval.snippets.join('\n\n'));

  if (isLikelyWriteAwarePrompt(prompt) && retrieval.writeTargets.length) {
    parts.push('');
    parts.push('Possible write targets / edit hints:');
    for (const target of retrieval.writeTargets) {
      parts.push(`- ${target} — already mentions this topic; likely place to update if the retrieved snippet is stale.`);
    }
    parts.push('Hook note: no vault write was performed. Decide explicitly later if an obsidian edit/append/create call is warranted.');
  }

  return String(parts.join('\n')).slice(0, MAX_RETRIEVAL_CHARS).trim();
}

function readThrottleWarning() {
  try {
    const flagFile = '/root/.openclaw/workspace/.claude_usage_flag';
    if (!fs.existsSync(flagFile)) {
      return '';
    }

    const flagContent = fs.readFileSync(flagFile, 'utf8');
    const throttle = flagContent.match(/CLAUDE_THROTTLE=(\d)/)?.[1];
    const weekly = flagContent.match(/CLAUDE_USAGE_WEEKLY=(\d+)/)?.[1];
    const sonnet = flagContent.match(/CLAUDE_USAGE_SONNET=(\d+)/)?.[1];
    if (throttle === '1' || (weekly && parseInt(weekly, 10) >= 70)) {
      return `⚠️ CLAUDE USAGE HIGH: ${weekly}% weekly / ${sonnet}% Sonnet used.\nTHROTTLE MODE: Minimise tool calls, combine operations, and skip redundant fetches.\n`;
    }
  } catch {
    // Non-fatal.
  }

  return '';
}

export default async function handler(event, context) {
  if (event.type === 'before_prompt_build') {
    try {
      const injected = buildBeforePromptContext(event.prompt || '');
      if (injected) {
        return { prependContext: injected };
      }
    } catch (error) {
      console.error('Obsidian before_prompt_build hook failure:', error.message);
    }
    return;
  }

  if (event.type !== 'agent:bootstrap') {
    return;
  }

  context.bootstrapFiles = context.bootstrapFiles || {};

  try {
    const today = getTodayDateString();
    const state = readBootstrapState();
    const dayState = state[today] || null;

    let rawDaily = '';
    try {
      rawDaily = readDailyViaCli();
    } catch {
      rawDaily = readDailyViaFileFallback();
    }

    const governanceFiles = readGovernanceFiles();
    const governanceContext = buildGovernanceContext(governanceFiles);
    const { dailyText, lineCount, normalized } = buildTokenAwareDailySnapshot(rawDaily, dayState);

    const governanceHash = computeSha256(governanceContext);
    const dailyHash = computeSha256(normalized);
    const combinedHash = computeSha256(`${governanceHash}:${dailyHash}`);

    let orientationSnapshot = '';
    if (dayState && dayState.combinedHash === combinedHash && dayState.snapshot) {
      orientationSnapshot = dayState.snapshot;
    } else {
      orientationSnapshot = buildOrientationSnapshot({ governanceContext, dailyText });
      state[today] = {
        governanceHash,
        dailyHash,
        combinedHash,
        lastLineCount: lineCount,
        snapshot: orientationSnapshot,
        lastUpdatedIso: new Date().toISOString(),
      };
      writeBootstrapState(state);
    }

    if (orientationSnapshot) {
      context.bootstrapFiles['OBSIDIAN_DAILY.md'] = [
        '# Obsidian Session Orientation',
        '',
        readThrottleWarning(),
        orientationSnapshot,
        '',
        '---',
        '*Injected at session start only. Per-turn vault retrieval now happens in before_prompt_build.*',
      ].join('\n');
      return;
    }

    context.bootstrapFiles['OBSIDIAN_DAILY.md'] = [
      '# Obsidian Session Orientation',
      '',
      'No daily orientation context was available yet.',
      '',
      governanceContext ? `# Behavioral Governance\n${governanceContext}` : '',
      '',
      '---',
      '*Injected at session start only. Per-turn vault retrieval now happens in before_prompt_build.*',
    ].join('\n');
  } catch (error) {
    context.bootstrapFiles['OBSIDIAN_ERROR.md'] = [
      '# Obsidian Memory Error',
      '',
      `The Obsidian bootstrap hook failed: ${error.message}`,
      '',
      'Session-start orientation was unavailable for this run.',
    ].join('\n');

    console.error('Obsidian bootstrap hook failure:', error.message);
  }
}

export {
  buildBeforePromptContext,
  retrieveTargetedVaultContext,
  isLikelyWriteAwarePrompt,
  buildOrientationSnapshot,
  buildTokenAwareDailySnapshot,
  readDailyViaFileFallback,
  readVaultFile,
  resolveVaultRoot,
  getTodayDateString,
};
```

## File: LICENSE
size: 1056
sha: 14fac913ccf80234b1848540089a3bbcb6e5283d
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2026

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: package.json
size: 536
sha: ecabae5b9c70e96bb1ddc8e10442d51f6ac9aa49
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/package.json

```text
{
  "name": "obsidian-life-memory",
  "version": "0.1.0",
  "description": "One-command setup and maintenance CLI for the Obsidian Life Memory OpenClaw skill",
  "type": "module",
  "bin": {
    "obsidian-life-memory": "bin/obsidian-life-memory.js",
    "olm": "bin/obsidian-life-memory.js"
  },
  "scripts": {
    "test": "node --test tests/*.test.js",
    "lint": "node -e \"console.log('no lint configured')\""
  },
  "keywords": [
    "openclaw",
    "obsidian",
    "skill",
    "memory",
    "heartbeat"
  ],
  "license": "MIT"
}
```

## File: plugins/obsidian-cli-tool/index.js
size: 5294
sha: 6d5c3f4042b0d8515e35b2832de810cb884be531
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/plugins/obsidian-cli-tool/index.js

```text
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);

function cfg(api) {
  return api?.config?.plugins?.entries?.['obsidian-cli-tool']?.config ?? {};
}
function trunc(text, maxChars) {
  text = text || '';
  return text.length <= maxChars ? text : text.slice(0, maxChars) + `\n\n[truncated ${text.length - maxChars} chars]`;
}
async function run(api, subcommand, kv = {}, opts = {}) {
  const conf = cfg(api);
  const command = conf.command || 'obsidian-cli';
  const maxOutputChars = Number(conf.maxOutputChars || 20000);
  const args = [subcommand, ...Object.entries(kv).filter(([,v]) => v !== undefined && v !== null).map(([k,v]) => `${k}=${String(v)}`)];
  try {
    const { stdout, stderr } = await execFileAsync(command, args, { maxBuffer: 20 * 1024 * 1024, timeout: opts.timeoutMs || 30000, env: process.env });
    return { ok: true, text: trunc(stdout || stderr || '', maxOutputChars), details: { command, args } };
  } catch (err) {
    const text = [err?.stdout, err?.stderr, err?.message].filter(Boolean).join('\n');
    return { ok: false, text: trunc(text, maxOutputChars), details: { command, args, error: true } };
  }
}
function reg(api, name, description, parameters, handler) {
  api.registerTool({ name, label: name, description, parameters, async execute(_id, params) { return handler(params || {}); } });
}
export default function register(api) {
  reg(api, 'obsidian_read', 'Read a note from the Obsidian vault.', {
    type: 'object', additionalProperties: false, properties: { path: { type: 'string' } }, required: ['path']
  }, async ({ path }) => {
    const r = await run(api, 'read', { path });
    return { content: [{ type: 'text', text: r.text }], details: r.details };
  });

  reg(api, 'obsidian_search', 'Search Obsidian notes by filename.', {
    type: 'object', additionalProperties: false, properties: { query: { type: 'string' } }, required: ['query']
  }, async ({ query }) => {
    const r = await run(api, 'search', { query });
    return { content: [{ type: 'text', text: r.text }], details: r.details };
  });

  reg(api, 'obsidian_search_content', 'Full-text search Obsidian notes with context.', {
    type: 'object', additionalProperties: false, properties: { query: { type: 'string' } }, required: ['query']
  }, async ({ query }) => {
    const r = await run(api, 'search-content', { query });
    return { content: [{ type: 'text', text: r.text }], details: r.details };
  });

  reg(api, 'obsidian_create', 'Create or overwrite a note in the Obsidian vault.', {
    type: 'object', additionalProperties: false, properties: { path: { type: 'string' }, content: { type: 'string' }, force: { type: 'boolean' } }, required: ['path','content']
  }, async ({ path, content, force }) => {
    const r = await run(api, 'create', { path, content, ...(force ? { force: 'true' } : {}) });
    return { content: [{ type: 'text', text: r.text }], details: r.details };
  });

  reg(api, 'obsidian_edit', 'Find and replace text within a vault note.', {
    type: 'object', additionalProperties: false, properties: { path: { type: 'string' }, find: { type: 'string' }, replace: { type: 'string' }, regex: { type: 'boolean' } }, required: ['path','find','replace']
  }, async ({ path, find, replace, regex }) => {
    const r = await run(api, 'edit', { path, find, replace, ...(regex ? { regex: 'true' } : {}) });
    return { content: [{ type: 'text', text: r.text }], details: r.details };
  });

  reg(api, 'obsidian_append', 'Append text to a note in the Obsidian vault.', {
    type: 'object', additionalProperties: false, properties: { path: { type: 'string' }, content: { type: 'string' } }, required: ['path','content']
  }, async ({ path, content }) => {
    const r = await run(api, 'append', { path, content });
    return { content: [{ type: 'text', text: r.text }], details: r.details };
  });

  reg(api, 'obsidian_move', 'Move or rename a note and update wikilinks.', {
    type: 'object', additionalProperties: false, properties: { path: { type: 'string' }, to: { type: 'string' } }, required: ['path','to']
  }, async ({ path, to }) => {
    const r = await run(api, 'move', { path, to });
    return { content: [{ type: 'text', text: r.text }], details: r.details };
  });

  reg(api, 'obsidian_list', 'List notes in an Obsidian folder.', {
    type: 'object', additionalProperties: false, properties: { folder: { type: 'string' } }, required: ['folder']
  }, async ({ folder }) => {
    const r = await run(api, 'list', { folder });
    return { content: [{ type: 'text', text: r.text }], details: r.details };
  });

  reg(api, 'obsidian_daily_read', 'Read today\'s daily note.', {
    type: 'object', additionalProperties: false, properties: {} 
  }, async () => {
    const r = await run(api, 'daily:read', {});
    return { content: [{ type: 'text', text: r.text }], details: r.details };
  });

  reg(api, 'obsidian_daily_append', 'Append to today\'s daily note.', {
    type: 'object', additionalProperties: false, properties: { content: { type: 'string' } }, required: ['content']
  }, async ({ content }) => {
    const r = await run(api, 'daily:append', { content });
    return { content: [{ type: 'text', text: r.text }], details: r.details };
  });
}
```

## File: plugins/obsidian-cli-tool/openclaw.plugin.json
size: 528
sha: 06a98dcb7f01867478fb8f73260037265c3a56b3
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/plugins/obsidian-cli-tool/openclaw.plugin.json

```text
{
  "id": "obsidian-cli-tool",
  "name": "Obsidian CLI Tool",
  "description": "First-class Obsidian vault tools backed by obsidian-cli.",
  "configSchema": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "command": { "type": "string" },
      "maxOutputChars": { "type": "number", "minimum": 1000 }
    }
  },
  "uiHints": {
    "command": { "label": "Obsidian CLI Command", "help": "Path to obsidian-cli wrapper/binary." },
    "maxOutputChars": { "label": "Max Output Characters" }
  }
}
```

## File: templates/Context/now.example.md
size: 301
sha: 27fbc11125946788320ace4ff5b22f2c3767879d
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/templates/Context/now.example.md

```text
# now

Quick index for fast retrieval.

## Active projects
- [[Projects/example-project|Example Project]]

## People
- [[People/example-person|Example Person]]

## Places
- [[Places/example-place|Example Place]]

## Vendors
- [[Vendors/example-vendor|Example Vendor]]

## Today
- [[Daily/YYYY-MM-DD]]
```

## File: templates/Context/retrieval_policy.example.md
size: 430
sha: bb9d6e04aecaeed345b9813429e1d67ac4ca512e
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/templates/Context/retrieval_policy.example.md

```text
# Retrieval Policy (Fast Path)

Default: automatic retrieval with adaptive depth.

## Retrieval ladder
1) Tier 1 (Index): check `Context/now.md` first.
2) Tier 2 (Targeted notes): read 1–2 likely nodes.
3) Tier 3 (Search): semantic + grep only if still missing.

## Output rules
- Answer directly.
- Prefer exact facts over narrative.

## Safety
- Never modify governance/system files.
- Keep filenames slugged and links clean.
```

## File: tests/cli.test.js
size: 943
sha: f1ac9ebcc9ec78a2bd862ab9766910e1aa7d82a8
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/tests/cli.test.js

```text
import test from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(__dirname, '..');
const bin = path.join(root, 'bin', 'obsidian-life-memory.js');

function run(args) {
  return spawnSync('node', [bin, ...args], { encoding: 'utf8' });
}

test('help exits cleanly', () => {
  const r = run(['help']);
  assert.equal(r.status, 0);
  assert.match(r.stdout, /Commands:/);
});

test('init dry-run with heartbeat exits cleanly', () => {
  const r = run(['init', '--yes', '--dry-run', '--enable-heartbeat', '--timezone', 'UTC', '--every', '30m']);
  assert.equal(r.status, 0, r.stderr || r.stdout);
  assert.match(r.stdout, /Planned actions:/);
  assert.match(r.stdout, /Done\. \(dry-run\)|Done\.\(dry-run\)|Done\. \(dry-run\)/);
});
```

## File: tests/obsidian-cli-adapter.test.js
size: 4254
sha: 8433e3b480ff62bedd324a6a5099cc2904711341
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/tests/obsidian-cli-adapter.test.js

```text
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { makeTempVault, makeFakeOfficialCli, run } from './test-helpers.js';

const adapter = path.resolve('bin/obsidian-cli');

function setup() {
  const vault = makeTempVault();
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'olm-cli-'));
  const official = makeFakeOfficialCli(dir);
  const env = {
    ...process.env,
    OBSIDIAN_OFFICIAL_CLI: official,
    OBSIDIAN_VAULT_PATH: vault,
    OBSIDIAN_VAULT_NAME: 'workspace',
    TEST_VAULT_PATH: vault,
  };
  return { vault, env };
}

function cli(args, env) {
  return run(adapter, args, { env });
}

test('read + append + create + delete work', () => {
  const { vault, env } = setup();
  let r = cli(['create', 'path=People/alice.md', 'content=# Alice\n#friend'], env);
  assert.equal(r.status, 0, r.stderr);
  r = cli(['append', 'path=People/alice.md', 'content=\n- note'], env);
  assert.equal(r.status, 0, r.stderr);
  r = cli(['read', 'path=People/alice.md'], env);
  assert.match(r.stdout, /# Alice/);
  assert.match(r.stdout, /- note/);
  r = cli(['delete', 'path=People/alice.md'], env);
  assert.equal(r.status, 0, r.stderr);
  assert.equal(fs.existsSync(path.join(vault, 'People', 'alice.md')), false);
});

test('edit handles pipes and first-match replacement safely', () => {
  const { vault, env } = setup();
  fs.writeFileSync(path.join(vault, 'MEMORY.md'), 'hello | one\nhello | one\n');
  const r = cli(['edit', 'path=MEMORY.md', 'find=hello | one', 'replace=hello | fixed'], env);
  assert.equal(r.status, 0, r.stderr);
  const text = fs.readFileSync(path.join(vault, 'MEMORY.md'), 'utf8');
  assert.equal(text.trimEnd(), 'hello | fixed\nhello | one');
});

test('daily commands use memory folder', () => {
  const { vault, env } = setup();
  let r = cli(['daily:read'], env);
  assert.match(r.stdout, /Carla remortgage/);
  r = cli(['daily:append', 'content=\n- added'], env);
  assert.equal(r.status, 0, r.stderr);
  r = cli(['daily:read'], env);
  assert.match(r.stdout, /- added/);
  r = cli(['daily:create', 'content=# Daily Note — 2026-03-23\n\nreset'], env);
  assert.equal(r.status, 0, r.stderr);
  assert.equal(fs.readFileSync(path.join(vault, 'memory', '2026-03-23.md'), 'utf8'), '# Daily Note — 2026-03-23\n\nreset');
});

test('list + move + backlinks work', () => {
  const { vault, env } = setup();
  fs.writeFileSync(path.join(vault, 'People', 'old-name.md'), '# Old\n');
  fs.writeFileSync(path.join(vault, 'Projects', 'proj.md'), 'Talk to [[old-name]]\n');
  let r = cli(['list', 'folder=People'], env);
  assert.match(r.stdout, /People\/old-name\.md/);
  r = cli(['move', 'path=People/old-name.md', 'to=People/new-name.md'], env);
  assert.equal(r.status, 0, r.stderr);
  assert.equal(fs.existsSync(path.join(vault, 'People', 'new-name.md')), true);
  const proj = fs.readFileSync(path.join(vault, 'Projects', 'proj.md'), 'utf8');
  assert.match(proj, /\[\[new-name\]\]/);
  r = cli(['backlinks', 'path=People/new-name.md'], env);
  assert.match(r.stdout, /Projects\/proj\.md/);
});

test('search + search-content + query + tags work', () => {
  const { vault, env } = setup();
  fs.writeFileSync(path.join(vault, 'People', 'carla.md'), '# Carla\nstatus: open\n#broker\n');
  fs.writeFileSync(path.join(vault, 'Projects', 'mortgage.md'), 'Carla says remortgage\n');
  let r = cli(['search', 'query=carla'], env);
  assert.match(r.stdout, /People\/carla\.md/);
  r = cli(['search-content', 'query=remortgage'], env);
  assert.match(r.stdout, /Projects\/mortgage\.md:/);
  r = cli(['query', 'key=status', 'value=open'], env);
  assert.match(r.stdout, /People\/carla\.md:/);
  r = cli(['tags'], env);
  assert.match(r.stdout, /#broker/);
});

test('print-default and status expose vault info', () => {
  const { vault, env } = setup();
  let r = cli(['print-default'], env);
  assert.equal(r.stdout.trim(), 'workspace');
  r = cli(['print-default', '--path-only'], env);
  assert.equal(r.stdout.trim(), vault);
  r = cli(['status'], env);
  assert.match(r.stdout, new RegExp(vault.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
  assert.match(r.stdout, /Version:/);
  assert.match(r.stdout, /memory\/2026-03-23\.md/);
});
```

## File: tests/obsidian-plugin.test.js
size: 2914
sha: e61bc21316b0c60435dcc9b1fe720cad6323ffea
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/tests/obsidian-plugin.test.js

```text
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { makeTempVault, makeFakeOfficialCli } from './test-helpers.js';

function setup() {
  const vault = makeTempVault();
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'olm-plugin-'));
  const official = makeFakeOfficialCli(dir);
  const adapter = path.resolve('bin/obsidian-cli');
  const api = {
    config: { plugins: { entries: { 'obsidian-cli-tool': { config: { command: adapter, maxOutputChars: 20000 } } } } },
    tools: new Map(),
    registerTool(def) { this.tools.set(def.name, def); },
  };
  const env = {
    ...process.env,
    OBSIDIAN_OFFICIAL_CLI: official,
    OBSIDIAN_VAULT_PATH: vault,
    OBSIDIAN_VAULT_NAME: 'workspace',
    TEST_VAULT_PATH: vault,
  };
  return { api, vault, env };
}

test('plugin registers expected obsidian tools and wrappers work', async () => {
  const { api, vault, env } = setup();
  const oldEnv = process.env;
  Object.assign(process.env, env);
  try {
    const mod = await import(path.resolve('plugins/obsidian-cli-tool/index.js') + `?t=${Date.now()}`);
    mod.default(api);

    const expected = [
      'obsidian_read','obsidian_search','obsidian_search_content','obsidian_create','obsidian_edit',
      'obsidian_append','obsidian_move','obsidian_list','obsidian_daily_read','obsidian_daily_append'
    ];
    for (const name of expected) assert.equal(api.tools.has(name), true, `${name} not registered`);

    await api.tools.get('obsidian_create').execute('1', { path: 'People/carla.md', content: '# Carla' });
    let r = await api.tools.get('obsidian_read').execute('2', { path: 'People/carla.md' });
    assert.match(r.content[0].text, /# Carla/);

    await api.tools.get('obsidian_append').execute('3', { path: 'People/carla.md', content: '\nstatus: open' });
    await api.tools.get('obsidian_edit').execute('4', { path: 'People/carla.md', find: 'open', replace: 'closed' });
    r = await api.tools.get('obsidian_search_content').execute('5', { query: 'closed' });
    assert.match(r.content[0].text, /People\/carla\.md/);

    r = await api.tools.get('obsidian_list').execute('6', { folder: 'People' });
    assert.match(r.content[0].text, /People\/carla\.md/);

    await api.tools.get('obsidian_move').execute('7', { path: 'People/carla.md', to: 'People/carla-corbisiero.md' });
    r = await api.tools.get('obsidian_list').execute('8', { folder: 'People' });
    assert.match(r.content[0].text, /People\/carla-corbisiero\.md/);

    r = await api.tools.get('obsidian_daily_read').execute('9', {});
    assert.match(r.content[0].text, /Daily Note/);
    await api.tools.get('obsidian_daily_append').execute('10', { content: '\n- plugin test' });
    assert.match(fs.readFileSync(path.join(vault, 'memory', '2026-03-23.md'), 'utf8'), /plugin test/);
  } finally {
    process.env = oldEnv;
  }
});
```

## File: tests/obsidian-preprompt.test.js
size: 3376
sha: 4b88879e34a09ee0dd5fca3ed27e9aa9656dda60
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/tests/obsidian-preprompt.test.js

```text
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { makeTempVault, makeFakeOfficialCli } from './test-helpers.js';

function setupEnv() {
  const vault = makeTempVault();
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'olm-hook-'));
  const official = makeFakeOfficialCli(dir);
  process.env.OBSIDIAN_CLI_BIN = path.resolve('bin/obsidian-cli');
  process.env.OBSIDIAN_OFFICIAL_CLI = official;
  process.env.OBSIDIAN_VAULT_PATH = vault;
  process.env.OBSIDIAN_VAULT_NAME = 'workspace';
  process.env.TEST_VAULT_PATH = vault;
  process.env.OBSIDIAN_BOOTSTRAP_STATE_PATH = path.join(vault, '.obsidian-bootstrap-state.test.json');
  return vault;
}

test('before_prompt_build injects relevant retrieval context', async () => {
  const vault = setupEnv();
  fs.writeFileSync(path.join(vault, 'People', 'carla-corbisiero.md'), '# Carla Corbisiero\nMortgage broker\n');
  const mod = await import(path.resolve('hooks/obsidian-preprompt.js') + `?t=${Date.now()}`);
  const res = await mod.default({ type: 'before_prompt_build', prompt: 'What did Carla say about the remortgage?' }, {});
  assert.ok(res?.prependContext);
  assert.match(res.prependContext, /Obsidian Targeted Retrieval/);
  assert.match(res.prependContext, /Carla/);
  assert.match(res.prependContext, /remortgage/i);
});

test('before_prompt_build includes write targets for correction/update prompts', async () => {
  const vault = setupEnv();
  fs.writeFileSync(path.join(vault, 'People', 'carla-corbisiero.md'), '# Carla Corbisiero\nstatus: open\n');
  const mod = await import(path.resolve('hooks/obsidian-preprompt.js') + `?t=${Date.now()}`);
  const res = await mod.default({ type: 'before_prompt_build', prompt: 'Actually update Carla status to closed' }, {});
  assert.ok(res?.prependContext);
  assert.match(res.prependContext, /Possible write targets/);
  assert.match(res.prependContext, /carla-corbisiero\.md/);
});

test('before_prompt_build returns nothing when no vault match is relevant', async () => {
  setupEnv();
  const mod = await import(path.resolve('hooks/obsidian-preprompt.js') + `?t=${Date.now()}`);
  const res = await mod.default({ type: 'before_prompt_build', prompt: 'Completely unrelated banana spaceship question' }, {});
  assert.equal(res, undefined);
});

test('agent bootstrap injects orientation and writes bootstrap state', async () => {
  const vault = setupEnv();
  const mod = await import(path.resolve('hooks/obsidian-preprompt.js') + `?t=${Date.now()}`);
  const context = {};
  await mod.default({ type: 'agent:bootstrap' }, context);
  assert.ok(context.bootstrapFiles?.['OBSIDIAN_DAILY.md']);
  assert.match(context.bootstrapFiles['OBSIDIAN_DAILY.md'], /Obsidian Session Orientation/);
  assert.match(context.bootstrapFiles['OBSIDIAN_DAILY.md'], /Barclays|Carla|Daily/);
  const statePath = process.env.OBSIDIAN_BOOTSTRAP_STATE_PATH;
  assert.equal(fs.existsSync(statePath), true);
  const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
  assert.ok(Object.keys(state).length >= 1);
});

test('non-target hook events are ignored cleanly', async () => {
  setupEnv();
  const mod = await import(path.resolve('hooks/obsidian-preprompt.js') + `?t=${Date.now()}`);
  const res = await mod.default({ type: 'something-else' }, {});
  assert.equal(res, undefined);
});
```

## File: tests/obsidian-prompt-corpus.test.js
size: 2563
sha: 356f1c1d717309fe6164bacbc28ad7031ec7d0b9
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/tests/obsidian-prompt-corpus.test.js

```text
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { makeTempVault, makeFakeOfficialCli } from './test-helpers.js';

function setupEnv() {
  const vault = makeTempVault();
  fs.writeFileSync(path.join(vault, 'People', 'carla-corbisiero.md'), '# Carla Corbisiero\nMortgage broker\nrate 4.68%\n');
  fs.writeFileSync(path.join(vault, 'Projects', 'orsett-terrace.md'), '# Orsett Terrace\nBM Solutions mortgage\n');
  fs.writeFileSync(path.join(vault, 'Places', 'athens.md'), '# Athens\nFlight tomorrow\n', { flag: 'w' });
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'olm-corpus-'));
  const official = makeFakeOfficialCli(dir);
  process.env.OBSIDIAN_CLI_BIN = path.resolve('bin/obsidian-cli');
  process.env.OBSIDIAN_OFFICIAL_CLI = official;
  process.env.OBSIDIAN_VAULT_PATH = vault;
  process.env.OBSIDIAN_VAULT_NAME = 'workspace';
  process.env.TEST_VAULT_PATH = vault;
  process.env.OBSIDIAN_BOOTSTRAP_STATE_PATH = path.join(vault, '.obsidian-bootstrap-state.test.json');
  return vault;
}

const promptCases = [
  'What did Carla say about the remortgage?',
  'Update Barclays to closed',
  'Actually the loan was rejected',
  'Where is the Athens flight note?',
  'show me Orsett Terrace context',
  'Minecraft subscription tomorrow?',
  'Do I have anything about Lexie?',
  'Carla email draft',
  'What changed today?',
  'random banana spaceship nonsense',
  'please update Carla status',
  'Did George mention BM Solutions?',
  'AFM deadline',
  'school records overdue',
  'what do I need to do tomorrow',
  'wrong date for the flight',
  'new note about Athens move',
  'search for mortgage fee',
  'Who is Carla Corbisiero',
  'Minecraft',
  'Barclays',
  'Lexie grooming',
  'Hyperoptic bill',
  'Airport Executive receipt',
  'Can you correct the remortgage amount?',
];

test('before_prompt_build handles a corpus of prompts without throwing and returns only valid shapes', async () => {
  setupEnv();
  const mod = await import(path.resolve('hooks/obsidian-preprompt.js') + `?t=${Date.now()}`);
  for (const prompt of promptCases) {
    const res = await mod.default({ type: 'before_prompt_build', prompt }, {});
    const valid = res === undefined || (res && typeof res.prependContext === 'string');
    assert.equal(valid, true, `invalid response shape for prompt: ${prompt}`);
    if (res?.prependContext) {
      assert.match(res.prependContext, /# Obsidian Targeted Retrieval/);
      assert.ok(res.prependContext.length > 20);
    }
  }
});
```

## File: tests/test-helpers.js
size: 5511
sha: 2566a35012cc351f03bf6e1ac1c279a03038597b
upstream: https://github.com/georgeantonopoulos/obsidian-life-memory-skill/blob/HEAD/tests/test-helpers.js

```text
import fs from 'fs';
import os from 'os';
import path from 'path';
import { spawnSync } from 'child_process';

export function makeTempVault() {
  const root = fs.mkdtempSync(path.join(os.tmpdir(), 'olm-vault-'));
  fs.mkdirSync(path.join(root, 'memory'), { recursive: true });
  fs.mkdirSync(path.join(root, 'People'), { recursive: true });
  fs.mkdirSync(path.join(root, 'Projects'), { recursive: true });
  fs.mkdirSync(path.join(root, 'Places'), { recursive: true });
  fs.writeFileSync(path.join(root, 'SOUL.md'), '# Soul\n\nRules live here.\n');
  fs.writeFileSync(path.join(root, 'USER.md'), '# User\n\nGeorge\n');
  fs.writeFileSync(path.join(root, 'AGENTS.md'), '# Agents\n\nUse obsidian-cli.\n');
  fs.writeFileSync(path.join(root, 'TOOLS.md'), '# Tools\n\nSome tools.\n');
  fs.writeFileSync(path.join(root, 'MEMORY.md'), '# Memory\n\n- Barclays loan status\n');
  fs.writeFileSync(path.join(root, 'memory', '2026-03-23.md'), '# Daily Note — 2026-03-23\n\n- Barclays £40k loan\n- Carla remortgage follow-up\n');
  return root;
}

export function makeFakeOfficialCli(dir) {
  const cliPath = path.join(dir, 'fake-official-cli.js');
  fs.writeFileSync(cliPath, String.raw`#!/usr/bin/env node
const fs = require('fs');
const path = require('path');

const VAULT_PATH = process.env.TEST_VAULT_PATH;
if (!VAULT_PATH) { console.error('TEST_VAULT_PATH required'); process.exit(2); }
const args = process.argv.slice(2);
let idx = 0;
if (args[0] && args[0].startsWith('vault=')) idx = 1;
const cmd = args[idx];
const rest = args.slice(idx + 1);
const kv = {};
for (const arg of rest) {
  if (arg.includes('=')) {
    const i = arg.indexOf('=');
    kv[arg.slice(0, i)] = arg.slice(i + 1);
  }
}
function p(rel='') { return path.join(VAULT_PATH, rel); }
function ensureDir(file) { fs.mkdirSync(path.dirname(file), { recursive: true }); }
function read(rel) {
  const file = p(rel);
  if (!fs.existsSync(file)) { console.error('not found'); process.exit(1); }
  process.stdout.write(fs.readFileSync(file, 'utf8'));
}
function write(rel, content) {
  const file = p(rel); ensureDir(file); fs.writeFileSync(file, content, 'utf8');
}
function append(rel, content) {
  const file = p(rel); ensureDir(file); if (!fs.existsSync(file)) fs.writeFileSync(file, '', 'utf8'); fs.appendFileSync(file, content, 'utf8');
}
function dailyPath() { return 'memory/2026-03-23.md'; }
function filesUnder(folder='') {
  const start = p(folder);
  const out = [];
  function walk(dir) {
    for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
      const full = path.join(dir, ent.name);
      if (ent.isDirectory()) walk(full);
      else if (ent.isFile() && ent.name.endsWith('.md')) out.push(path.relative(VAULT_PATH, full));
    }
  }
  walk(start);
  return out.sort();
}
function grep(query, withContext=false, limit=20) {
  const out = [];
  for (const rel of filesUnder('')) {
    const file = p(rel);
    const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
    lines.forEach((line, i) => {
      if (line.toLowerCase().includes(String(query).toLowerCase())) {
        out.push(withContext ? rel + ':' + (i+1) + ': ' + line : rel);
      }
    });
  }
  const uniq = [...new Set(out)].slice(0, Number(limit));
  process.stdout.write(uniq.join('\n') + (uniq.length ? '\n' : ''));
}
function backlinks(rel) {
  const stem = path.basename(rel, '.md');
  grep('[[' + stem, false, 100);
}
function tags() {
  const found = new Set();
  for (const rel of filesUnder('')) {
    const text = fs.readFileSync(p(rel), 'utf8');
    for (const m of text.matchAll(/(^|\s)(#[A-Za-z0-9_-]+)/g)) found.add(m[2]);
  }
  const arr = [...found].sort();
  process.stdout.write(arr.join('\n') + (arr.length ? '\n' : ''));
}

switch (cmd) {
  case 'version': process.stdout.write('1.12.7 (installer 1.12.7)\n'); break;
  case 'daily:path': process.stdout.write(dailyPath() + '\n'); break;
  case 'daily:read': read(dailyPath()); break;
  case 'daily:append': append(dailyPath(), kv.content || ''); break;
  case 'read': read(kv.path || kv.file); break;
  case 'append': append(kv.path || kv.file, kv.content || ''); break;
  case 'create': write(kv.path || kv.file || kv.name, kv.content || ''); break;
  case 'delete': fs.unlinkSync(p(kv.path || kv.file)); process.stdout.write('Deleted permanently: ' + (kv.path || kv.file) + '\n'); break;
  case 'files': {
    const out = filesUnder(kv.folder || '');
    process.stdout.write(out.join('\n') + (out.length ? '\n' : ''));
    break;
  }
  case 'move': {
    const from = kv.path;
    const to = kv.to;
    ensureDir(p(to));
    fs.renameSync(p(from), p(to));
    const oldStem = path.basename(from, '.md');
    const newStem = path.basename(to, '.md');
    for (const rel of filesUnder('')) {
      const file = p(rel);
      const original = fs.readFileSync(file, 'utf8');
      const updated = original.replaceAll('[[' + oldStem + ']]', '[[' + newStem + ']]');
      if (updated !== original) fs.writeFileSync(file, updated, 'utf8');
    }
    process.stdout.write('Moved\n');
    break;
  }
  case 'search': grep(kv.query, false, kv.limit || 20); break;
  case 'search:context': grep(kv.query, true, kv.limit || 20); break;
  case 'backlinks': backlinks(kv.path || kv.file); break;
  case 'tags': tags(); break;
  default: console.error('unsupported fake command: ' + cmd); process.exit(2);
}
`);
  fs.chmodSync(cliPath, 0o755);
  return cliPath;
}

export function run(command, args, opts = {}) {
  return spawnSync(command, args, { encoding: 'utf8', ...opts });
}
```
