# anyone-skill

Adopt this skill: https://proskills.md/skills/other/acnlabs-openpersona-skills-anyone-skill

Page: https://proskills.md/skills/other/acnlabs-openpersona-skills-anyone-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: skills/anyone-skill/SKILL.md
size: 20393
sha: 62693912e7f7bee350f894072cba56ccc3ac5c99
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/SKILL.md

````text
---
name: anyone-skill
description: "Distill anyone into a runnable OpenPersona skill pack — real or fictional, personal or public, living or historical. Collects chat logs, documents, and public content, extracts a 4-dimension persona, and generates a portable OpenPersona pack via skills/open-persona. Use when asked to distill, clone, or create a persona for any person or character."
license: MIT
compatibility: "Designed for Claude Code, Cursor, or OpenClaw. Requires Python 3. Uses WebSearch for public figures and fictional characters."
allowed-tools: Read Write Edit Bash WebSearch
metadata:
  version: "1.1.2"
  author: acnlabs
---

# anyone.skill — Distill Anyone

> Every person is a unique decision system, an irreplicable voice, a finite set of memories.  
> **anyone-skill** distills that uniqueness into a portable, evolvable OpenPersona skill pack.

anyone-skill is a **distillation front-end** for OpenPersona. It handles data collection, 4-dimension extraction, and evidence grading. The final output is a full OpenPersona persona pack generated via `skills/open-persona`.

**Dependency chain**: `anyone-skill` → `skills/open-persona` → `openpersona create`  
**Extended chain (local model)**: `anyone-skill` → `persona-knowledge` → `persona-model-trainer` → runnable persona model

**Optional integration**: When `persona-knowledge` is installed (`skills/persona-knowledge/`), anyone-skill uses it for persistent storage, semantic search, and Knowledge Graph instead of writing directly to `training/raw/`. Detection:

```bash
# Check at start of Phase 3 — if this directory exists, use persona-knowledge integration
ls skills/persona-knowledge/SKILL.md 2>/dev/null && echo "persona-knowledge detected"
```

When detected, data flow becomes: `source → persona-knowledge ingest → MemPalace + KG + wiki → persona-knowledge export → training/`

## Trigger phrases

- `/create-anyone`
- "distill X into a skill"
- "create a persona for X"
- "make a skill pack for X"
- "I want to talk to X as an AI"
- "clone X's personality"

To evolve an existing persona:

- "I have more data" / "add this to X"
- "that's not right" / "X wouldn't say that"
- `/update-anyone {slug}`

---

## Tools

| Task                                         | Tool                                                                                   |
| -------------------------------------------- | -------------------------------------------------------------------------------------- |
| Read any text / JSON / CSV / PDF / image     | `Read` (native — use for most chat exports)                                            |
| Search public figures / fictional characters | `WebSearch`                                                                            |
| Extract SQLite databases (iMessage / WeChat) | `Bash` → `python3 ${CLAUDE_SKILL_DIR}/scripts/preprocess.py --input <file.db>`         |
| Sample oversized files (>5000 messages)      | `Bash` → `python3 ${CLAUDE_SKILL_DIR}/scripts/preprocess.py --input <file> --max 3000` |
| Write / update files                         | `Write` / `Edit`                                                                       |
| Version management                           | `Bash` → `python3 ${CLAUDE_SKILL_DIR}/scripts/version_manager.py`                      |
| List existing personas                       | `Bash` → `python3 ${CLAUDE_SKILL_DIR}/scripts/skill_writer.py --action list`           |

> **Reading strategy**: use `Read` directly for all text-based exports — WhatsApp `_chat.txt`, Telegram `result.json`, Slack/Discord JSON, email `.eml`, Twitter/X archive, Feishu/DingTalk export, plain text, CSV. The agent understands any readable format natively; no parser needed.  
> Use `preprocess.py` only for: **(1)** binary SQLite `.db` files, **(2)** files too large to fit in context (auto-samples down to `--max`).

---

## Phase 0: Classify the Subject

Determine which category the subject falls into — different categories use different data strategies and ethical rules:

```
Who do you want to distill?

  [1] Yourself           — full digital self
  [2] Someone you know   — colleague, friend, family, partner, ex
  [3] Public figure      — entrepreneur, artist, athlete, politician
  [4] Fictional character — game, anime, novel, film, series
  [5] Historical figure  — relies on documents, biographies, speeches
  [6] Archetype          — composite persona, no single real subject
```

---

## Phase 1: Ethics & Copyright Check

> Full rules: [references/ethics.md](references/ethics.md). Key points by category:

**Someone you know** — confirm personal use only; no harassment, impersonation, or deception; all data stored locally.

**Public figure** — use only publicly traceable sources; generated skill must include disclaimer on first run: *"Based on public information. Not the real person. For reference only."*

**Fictional character**

- Personal local use → no restrictions, direct roleplay mode
- Distributing to others → activate **Inspired-by mode** (reinterpret, don't replicate)
- The key criterion is **distribution intent**, not release year

**Historical figure** — publicly published sources only; mark uncertain claims as inferred (L3/L4).

**Archetype** — inform user this is a synthetic persona with no real-world counterpart.

---

## Phase 2: Intake (exactly 3 questions)

Ask only these 3 questions, in order. Summarize answers before proceeding.

**Q1: Codename (required)**

> What should we call them? Doesn't need to be their real name.  
> e.g. `Alex` · `Jobs` · `Geralt` · `Grandma Rose`

**Q2: Basic info (one sentence, skippable)**

> Age / era, role / identity, where they're from — whatever comes to mind.  
> e.g. `28, product designer, Berlin` · `Apple co-founder, 1955–2011, Silicon Valley` · `The Witcher, monster hunter, medieval fantasy world`

**Q3: Personality impression (one sentence, skippable)**

> What's your core impression? MBTI, traits, contradictions, a moment that defined them.  
> e.g. `INTJ, perfectionist, publicly harsh but privately warm` · `quiet until it matters, never explains their moves`

---

## Phase 3: Collect Source Material

Guide the user based on subject type:

### Someone you know / Yourself

```
How would you like to provide source material?
More data = higher fidelity.

  [A] Chat export
      iMessage (macOS) · WhatsApp export · Telegram export
      Signal export · Slack export · Discord export
      WeChat (WeChatMsg / PyWxDump) · Feishu / DingTalk

  [B] Documents / email
      Notes, diaries, letters, essays, .eml / .mbox

  [C] Social media archive
      Twitter/X data export · Instagram archive · LinkedIn export
      Facebook data download

  [D] Paste / describe
      Paste text directly, or describe from memory
```

For each file provided:

- **Text / JSON / CSV exports** → use `Read` directly. The agent reads and understands any format.
- **SQLite `.db` files** (iMessage `chat.db`, WeChat PyWxDump) → run `preprocess.py --input <file.db>`
- **Very large files** (>5 MB or clearly >5000 messages) → run `preprocess.py --input <file> --max 3000`

#### Path A: persona-knowledge detected

If `persona-knowledge` is installed, ingest each source via its pipeline:

```bash
python skills/persona-knowledge/scripts/ingest.py \
  --slug {slug} --source <path> --persona-name "{Name}"
```

This automatically handles PII scanning, deduplication, MemPalace storage, KG extraction, and `sources/` backup. No manual `training/raw/` writing needed.

Report after each source:
`✅ [N] messages from [source] → persona-knowledge/{slug}`

#### Path B: no persona-knowledge (default)

**After processing each source, immediately save a copy to `training/raw/`** (do not wait for Step 6-D):

```
Source type           → save as training/raw/…
─────────────────────────────────────────────────────────────
Chat export (any)     → whatsapp.jsonl / imessage.jsonl / …  [{role, content}, …]
Essay / diary / notes → essays.txt                           plain text paragraphs
Interview / Q&A       → interviews.jsonl                     [{role:"user"|"assistant", content}]
Social posts          → social.jsonl                         [{role:"assistant", content}]
```

- Keep original wording — do NOT paraphrase in raw/
- Redact obvious PII before saving (phone numbers, SSNs, addresses)

Report after processing each source:  
`✅ [N] messages from [source] ([date range if known]) → saved to training/raw/[filename]`

### Public figure / Historical figure

```
Will search the following automatically via WebSearch:

  → Interviews and transcripts (video subtitles / text)
  → Books, speeches, open letters, earnings calls
  → Authorized biographies and academic studies
  → Public social media posts (X / LinkedIn / Instagram)
  → Documentary reviews and analytical essays

Report: [N] sources indexed, ~[M] words of coverage
```

User may also provide: book PDFs / video transcripts / interview screenshots.

Save all collected text to `training/raw/` as plain `.txt` or structured `.jsonl` (interviews as `{role:"user"|"assistant", content}`).

### Fictional character

```
Will collect via:

  [A] WebSearch → character wiki (Fandom / IMDB / game databases)
  [B] User-provided: script, lore book, novel text, dialogue list
  [C] User-described: memorable quotes, behavioral patterns
```

Activate **copyright guard**: ask *"Will this skill be shared with others?"*  

- Yes → Inspired-by mode  
- No → direct roleplay mode

Save all collected text to `training/raw/` (scripts → `script.jsonl`, lore/wiki → `lore.txt`).

### Archetype

Skip data collection. Proceed directly to Phase 4 based on Phase 2 impressions.

---

## Phase 4: 4-Dimension Extraction

After all source material is processed, extract along 4 dimensions.

#### persona-knowledge integration (when detected)

Before extraction, query MemPalace for an overview and use the wiki as a starting point:

```bash
# Get a ~170-token overview of what's been ingested
mempalace wake-up --wing {slug}
```

Then read existing wiki pages for structured knowledge using the `Read` tool:

- `~/.openpersona/knowledge/{slug}/wiki/identity.md`
- `~/.openpersona/knowledge/{slug}/wiki/voice.md`
- `~/.openpersona/knowledge/{slug}/wiki/values.md`
- `~/.openpersona/knowledge/{slug}/wiki/thinking.md`

Use the wiki content as evidence-grounded starting points for each dimension. Fill gaps with semantic search: `mempalace search "decision making style" --wing {slug}`

After extraction, update the wiki pages with new insights (following Phase 3 of persona-knowledge's SKILL.md).

### Dimension 1: Procedure — *How do they think?*

- **Mental models**: 3–6 frameworks they habitually use (e.g. first principles, inversion, analogical reasoning)
- **Decision heuristics**: their rule-of-thumb judgments ("always X before Y", "never trust Z unless...")
- **Information preference**: data-driven or intuitive? big-picture or detail-oriented?
- **Risk posture**: where are they bold, where are they cautious?

### Dimension 2: Interaction — *How do they speak?*

- **Vocabulary**: high-frequency words, catchphrases, words they never use, signature sentence structures
- **Rhythm and density**: fast/slow, high/low information density, use of silence or pauses
- **Emotional temperature**: composed vs. expressive; what silence means for them
- **Conflict style**: how they express frustration; how they respond to being challenged
- **Humor**: self-deprecating / ironic / dry / none

### Dimension 3: Memory — *What shaped them?*

- **Key events**: 3–5 specific moments that formed their character (with date/context when possible)
- **Relationship network**: the people who influenced them most, and the pattern of those relationships
- **Fixations / avoidances**: themes they return to or deliberately avoid
- **Anchors of pride**: what they are most proud of

### Dimension 4: Personality — *What are their hard limits?*

- **Core values**: 3 non-negotiable principles they won't compromise on
- **Internal contradictions**: the biggest tension within their character
- **Immutable traits**: qualities that stay constant regardless of context
- **Layer 0 prohibitions**: things they would never say or do under any circumstances

---

## Phase 5: Evidence Grading

Tag each extracted piece with a confidence level:

| Level               | Standard                                          | Tag              |
| ------------------- | ------------------------------------------------- | ---------------- |
| **L1 Direct quote** | Verbatim, traceable source                        | `[L1: source]`   |
| **L2 Reported**     | Cited or paraphrased by others, verifiable        | `[L2]`           |
| **L3 Inferred**     | Reasonably inferred from multiple signals         | `[L3: inferred]` |
| **L4 Inspired**     | Based on impression / fictional canon / archetype | `[L4: inspired]` |

**Conflict resolution**: higher level wins. Equal-level conflicts are listed side by side with source noted.

---

## Phase 6: Generate OpenPersona Skill Pack

> Field mapping reference: [references/output-format.md](references/output-format.md)

### Step 6-A: Build persona.json

Map extraction results to OpenPersona v0.17+ format:

```json
{
  "soul": {
    "identity": {
      "personaName": "Display name",
      "slug": "lowercase-hyphenated-slug",
      "bio": "2–4 sentence background. Key events. L1/L2 evidence preferred.",
      "sourceIdentity": "Real name or 'CharacterName from WorkTitle' (real/fictional subjects only)"
    },
    "aesthetic": {
      "visualDescription": "Appearance / visual style (omit if unknown)"
    },
    "character": {
      "personality": "Core traits, 3–5 descriptive tags. From Personality dimension.",
      "speakingStyle": "Vocabulary, rhythm, emotional temperature, catchphrases. From Interaction dimension.",
      "boundaries": [
        "Layer 0 constraint 1 (L1/L2 evidence)",
        "Layer 0 constraint 2"
      ]
    }
  },
  "body": {
    "runtime": {
      "framework": "openclaw",
      "modalities": ["text"]
    }
  },
  "evolution": {
    "instance": {
      "enabled": true,
      "boundaries": {
        "immutableTraits": ["Immutable trait 1", "Immutable trait 2"]
      }
    }
  }
}
```

**Filling rules**:

- Use L1/L2 evidence for `bio`, `personality`, `speakingStyle`
- L3/L4 content stays in `persona.md` only — not in `persona.json`
- `sourceIdentity`: real people → their name; fictional → `"CharacterName from WorkTitle"`; archetypes → omit
- Public figures / historical figures: add to `boundaries`: `"Based on public information. Not the real person."`

### Step 6-B: Generate skill pack via skills/open-persona

Load `skills/open-persona/SKILL.md` and run with the `persona.json` from Step 6-A:

```bash
npx openpersona create --config persona.json --output ./{slug}-skill
```

Output is a full OpenPersona persona pack:

```
{slug}-skill/
├── SKILL.md          ← Soul/Body/Faculty/Skill index
├── persona.json      ← Declaration (derived fields stripped)
├── state.json        ← Initial runtime state
├── soul/
│   ├── injection.md  ← Self-awareness injection
│   └── constitution.md
├── agent-card.json
└── scripts/
    └── state-sync.js ← Body nervous system
```

### Step 6-C: Install (optional)

```bash
npx openpersona install ./{slug}-skill
npx openpersona switch {slug}
```

### Step 6-D: Export Training Data (for persona-model-trainer)

> Full procedure and file templates: [references/training-export.md](references/training-export.md)

Export a `training/` directory with raw source files, distilled conversation turns, a character profile, and metadata. If `persona-knowledge` is available, run `export_training.py`; otherwise build files manually from Phase 3–4 outputs.

**With persona-knowledge** (versioned export — preferred):

```bash
python skills/persona-knowledge/scripts/export_training.py \
  --slug {slug} --output training/
# Auto-assigns version (v1, v2, …). Override with --version v2.
# Writes export_version + export_hash to training/metadata.json.
# persona-model-trainer will record these as dataset_version + dataset_export_hash
# in training_summary.json, forming a complete provenance chain.
```

View export history at any time:

```bash
python skills/persona-knowledge/scripts/export_training.py --slug {slug} --list
```

**→ To train a local model**, pass the exported `probes.json` to `persona-model-trainer`:

```bash
bash skills/persona-model-trainer/scripts/pipeline.sh \
  --slug {slug} \
  --model google/gemma-4-E4B-it \
  --source ./training \
  --method mlx \       # or: unsloth (NVIDIA) / colab (no GPU)
  --preset gemma4 \
  --probes ./training/probes.json
```

> Full walkthrough: [`persona-model-trainer/references/pipeline-guide.md`](../persona-model-trainer/references/pipeline-guide.md)

### persona.md (always keep locally)

Alongside `persona.json`, maintain a `persona.md` with the full 4-dimension extraction + all evidence tags. Used for Phase 7 evolution. Not included in the skill pack.

---

## Phase 7: Evolve

Enter evolution mode when the user says — don't restart from scratch:

- **Add material**: "I found more chat logs" / "here's another source"  
→ Preprocess new source → save to `training/raw/` → merge into `persona.md` → conflict check → update `persona.json` → re-run Step 6-D (update `conversations.jsonl` + `metadata.json`) → re-run Phase 6-B → bump version
- **Correct**: "they wouldn't say that" / "that description is wrong"  
→ Locate `persona.md` section → revise → adjust evidence level → sync `persona.json` → update affected turns in `training/conversations.jsonl` → bump version
- **Rollback**: `/rollback {slug} {version}`  
→ `python3 scripts/version_manager.py --action rollback --slug {slug} --version {version}`

Print a diff summary after each update:

```
🔄 v0.1.0 → v0.1.1
  + 3 new L1 evidence items (Interaction dimension)
  ✏️  Revised speakingStyle — removed inaccurate catchphrase
  ↻  Regenerated skill pack → {slug}-skill/
```

---

## Layer 0 Safety (hard rules — always enforced)

1. **Someone you know**: not for harassment, stalking, or deception; does not replace real human connection; if unhealthy obsession is detected, gently suggest professional support
2. **Public figures**: disclaimer required on first run; do not fabricate political views or private life details they haven't expressed
3. **Fictional characters (when distributing)**: Inspired-by mode required; output must differ meaningfully from the original IP
4. **Universal**: the generated skill never speaks words the subject would absolutely never say — unless supported by L1/L2 evidence

---

## Subject Strategy Reference

| Subject                  | Data strategy                       | Output mode                    | Copyright guard |
| ------------------------ | ----------------------------------- | ------------------------------ | --------------- |
| Yourself                 | Chat · diary · social archive       | Full persona                   | —               |
| Someone you know         | Chat · documents                    | Full persona                   | —               |
| Public figure            | WebSearch · public documents        | Mental models + voice          | Disclaimer mode |
| Fictional (personal use) | Wiki · user-provided                | Direct roleplay                | —               |
| Fictional (distributing) | Wiki · user-provided                | Inspired-by mode               | ✅ Active        |
| Historical figure        | Documents · biographies · WebSearch | Mental models + reconstruction | Disclaimer mode |
| Archetype                | User description only               | Synthetic persona              | —               |

---

## List existing personas

When the user says `/list-anyone`:

```bash
python3 ${CLAUDE_SKILL_DIR}/scripts/skill_writer.py --action list --base-dir ./.claude/skills
```

Display: codename · version · last updated · subject type.
````

## File: skills/anyone-skill/README.md
size: 4058
sha: d65c5f50e77234686ff5652520088f0213b182af
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/README.md

````text
# anyone-skill

**Distill anyone into a runnable OpenPersona skill pack** — real or fictional, personal or public, living or historical.

[![Agent Skills](https://img.shields.io/badge/Agent%20Skills-1.0-blue)](https://agentskills.io/specification)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![OpenPersona](https://img.shields.io/badge/OpenPersona-compatible-purple)](https://github.com/acnlabs/openpersona)

## What it does

anyone-skill is a **distillation front-end** for OpenPersona. It guides an AI agent through:

1. Collecting source material (chat logs, documents, public content, creative works)
2. Extracting a 4-dimension persona (Procedure · Interaction · Memory · Personality)
3. Grading evidence (L1 direct quote → L4 inspired)
4. Generating a full OpenPersona persona pack via `skills/open-persona`

The output is a portable, evolvable persona you can install and run with any OpenPersona-compatible agent.

## Subject types

| Type | Examples |
|------|---------|
| Yourself | digital self-archive |
| Someone you know | colleague, friend, family, partner, ex |
| Public figure | entrepreneur, artist, athlete, politician |
| Fictional character | game, anime, novel, film, series |
| Historical figure | relies on documents and biographies |
| Archetype | composite persona, no single real subject |

## Install

```bash
npx skills add acnlabs/anyone-skill
```

Or clone manually:

```bash
git clone https://github.com/acnlabs/anyone-skill .claude/skills/create-anyone
```

## Usage

In Claude Code, type `/create-anyone` or use natural language:

```
distill Elon Musk into a skill
create a persona for Geralt of Rivia
I want to talk to my old colleague Alex as an AI
```

## Distillation pipeline

```
Phase 0  Classify subject (6 types)
Phase 1  Ethics & copyright check         → references/ethics.md
Phase 2  3-question intake
Phase 3  Collect source material
Phase 4  4-dimension extraction
         Procedure · Interaction · Memory · Personality
Phase 5  Evidence grading (L1–L4)
Phase 6  Generate OpenPersona skill pack  → references/output-format.md
         via skills/open-persona + openpersona create
Phase 7  Evolve (add data · correct · rollback)
```

## Supported data sources

| Source | How |
|--------|-----|
| iMessage (.db) / WeChat (.db) | `scripts/preprocess.py` (SQLite extraction) |
| WhatsApp, Telegram, Signal exports | `Read` tool directly (text/JSON) |
| Slack, Discord exports | `Read` tool directly (JSON) |
| Email (.eml / .mbox) | `Read` tool directly |
| Twitter/X, Instagram archives | `Read` tool directly (JSON) |
| Feishu, DingTalk exports | `Read` tool directly |
| Any file > 5000 messages | `scripts/preprocess.py --max 3000` (sampling) |
| Public figures / historical figures | WebSearch (automatic) |
| PDF, images, documents | `Read` tool (native) |

## Output

```
{slug}-skill/                   ← Full OpenPersona pack
├── SKILL.md                    ← Invocable via /{slug}
├── persona.json
├── state.json
├── soul/
│   ├── injection.md
│   └── constitution.md
├── agent-card.json
└── scripts/state-sync.js
```

## Requirements

- Python 3.8+ (for `scripts/preprocess.py`)
- Claude Code or any Agent Skills–compatible agent
- `openpersona` CLI for final pack generation

## How anyone-skill relates to other distillation skills

anyone-skill distills the common methodology behind the distillation skill ecosystem into a universal framework. Specialized skills go deeper in their domain; anyone-skill goes broader.

| Skill | Specialization | Relationship |
|-------|----------------|--------------|
| colleague-skill | Colleague (Feishu/DingTalk) | Specialized version |
| yourself-skill | Self (WeChat/social) | Specialized version |
| ex-skill | Ex-partner | Specialized version |
| boss-skills | Boss + entrepreneur archetypes | Specialized version |
| immortal-skill | 7 real-person types | Complementary — anyone-skill adds fictional/historical/archetype |

## License

MIT
````

## File: skills/anyone-skill/scripts/preprocess.py
size: 11357
sha: 5cb0228a2658afcddf886c925950ea425ec2eab2
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/scripts/preprocess.py

```text
#!/usr/bin/env python3
"""
preprocess.py — Data pre-processor for anyone-skill

Handles two things the agent cannot do natively:

  1. SQLite extraction — reads binary database files (iMessage chat.db,
     WeChat PyWxDump .db) and outputs a readable JSON list.

  2. Large-file sampling — when a file exceeds --max messages, samples
     down to a representative subset before the agent reads it.
     Uses time-distributed sampling weighted by keyword hits.

For all other formats (WhatsApp _chat.txt, Telegram result.json,
Slack/Discord JSON exports, email .eml, Twitter/X archive, plain text,
CSV, etc.) — pass the file directly to the agent via the Read tool.
The agent understands these formats natively.

Usage:
  # Extract SQLite database
  python3 preprocess.py --input ~/Library/Messages/chat.db --output messages.json

  # Sample a large export file
  python3 preprocess.py --input big-export.json --max 3000 --output sampled.json

  # Filter to one person + sample
  python3 preprocess.py --input export.json --target "Alice" --max 2000 --output alice.json
"""

import argparse
import json
import re
import sqlite3
import sys
from pathlib import Path
from typing import Optional

# ── Unified message schema ────────────────────────────────────────────────────

def msg(time: str, sender: str, content: str, platform: str) -> dict:
    return {"time": time, "sender": sender, "content": content, "platform": platform}

# ── SQLite extractors ─────────────────────────────────────────────────────────

def _is_sqlite(path: Path) -> bool:
    try:
        with open(path, "rb") as f:
            return f.read(6) == b"SQLite"
    except Exception:
        return False

def _sqlite_tables(path: Path) -> set:
    try:
        con = sqlite3.connect(str(path))
        tables = {r[0] for r in con.execute(
            "SELECT name FROM sqlite_master WHERE type='table'"
        ).fetchall()}
        con.close()
        return tables
    except Exception:
        return set()

def extract_imessage(path: Path, target: Optional[str]) -> list:
    """Extract from macOS iMessage chat.db (~Library/Messages/chat.db)."""
    results = []
    try:
        con = sqlite3.connect(str(path))
        rows = con.execute("""
            SELECT
                datetime(message.date/1000000000 + 978307200, 'unixepoch') AS dt,
                COALESCE(handle.id, 'me') AS sender,
                message.text
            FROM message
            LEFT JOIN handle ON message.handle_id = handle.ROWID
            WHERE message.text IS NOT NULL AND message.text != ''
            ORDER BY message.date
        """).fetchall()
        con.close()
        for t, sender, content in rows:
            if target and target.lower() not in sender.lower():
                continue
            results.append(msg(str(t), sender, content, "imessage"))
    except Exception as e:
        print(f"❌ iMessage extraction failed: {e}", file=sys.stderr)
    return results

def extract_wechat(path: Path, target: Optional[str]) -> list:
    """Extract from WeChat PyWxDump / WeChatMsg SQLite database."""
    results = []
    try:
        con = sqlite3.connect(str(path))
        tables = _sqlite_tables(path)

        # Try known schemas in order of preference
        queries = []
        if "MSG" in tables:
            queries.append("SELECT CreateTime, NickName, Content FROM MSG")
        if "ChatInfo" in tables:
            queries.append("SELECT CreateTime, Sender, Content FROM ChatInfo")
        if not queries:
            # Generic fallback: look for time/sender/content columns
            for tbl in tables:
                try:
                    cols = {r[1].lower() for r in con.execute(f"PRAGMA table_info({tbl})").fetchall()}
                    if {"content"} & cols and len(cols & {"sender", "nickname", "from", "user"}) > 0:
                        queries.append(f"SELECT * FROM {tbl}")
                except Exception:
                    pass

        for sql in queries:
            try:
                for row in con.execute(sql).fetchall():
                    # Heuristic: first col = time, second = sender, third = content
                    t, sender, content = str(row[0]), str(row[1] or ""), str(row[2] or "")
                    if not content.strip():
                        continue
                    if target and target not in sender:
                        continue
                    results.append(msg(t, sender, content, "wechat"))
                break
            except sqlite3.OperationalError:
                continue
        con.close()
    except Exception as e:
        print(f"❌ WeChat extraction failed: {e}", file=sys.stderr)
    return results

def extract_sqlite(path: Path, target: Optional[str]) -> list:
    """Auto-detect SQLite type and dispatch to the right extractor."""
    tables = _sqlite_tables(path)
    if "message" in tables and "handle" in tables:
        print(f"  → Detected: iMessage database", file=sys.stderr)
        return extract_imessage(path, target)
    if "MSG" in tables or "ChatInfo" in tables:
        print(f"  → Detected: WeChat database", file=sys.stderr)
        return extract_wechat(path, target)
    print(f"  ⚠️  Unknown SQLite schema (tables: {tables}). Trying generic extraction.", file=sys.stderr)
    return extract_wechat(path, target)  # best-effort fallback

# ── Sampler ───────────────────────────────────────────────────────────────────

def load_any(path: Path) -> list:
    """
    Best-effort loader for any readable file.
    Returns a list of message dicts (may be partial for non-standard formats).
    For standard formats the agent should read directly — this is only used
    to count and sample when the file is too large.
    """
    text = path.read_text(encoding="utf-8", errors="ignore")

    # Try JSON first
    try:
        cleaned = re.sub(r"^window\.\w+\s*=\s*", "", text.strip()).rstrip(";")
        data = json.loads(cleaned)
        items = data if isinstance(data, list) else \
                data.get("messages", data.get("statuses", data.get("items", [])))
        if isinstance(items, list) and items:
            results = []
            for item in items:
                if not isinstance(item, dict):
                    continue
                content = str(
                    item.get("content") or item.get("text") or
                    item.get("full_text") or item.get("body") or ""
                )
                content = re.sub(r"<[^>]+>", "", content).strip()
                if not content:
                    continue
                sender = str(
                    item.get("sender") or item.get("from") or
                    item.get("user") or item.get("NickName") or
                    (item.get("author", {}).get("name") if isinstance(item.get("author"), dict) else "") or ""
                )
                t = str(
                    item.get("time") or item.get("date") or
                    item.get("created_at") or item.get("ts") or
                    item.get("create_time") or item.get("timestamp") or ""
                )
                results.append(msg(t, sender, content, "generic"))
            return results
    except Exception:
        pass

    # Plain text: one entry per non-empty line
    lines = [l.strip() for l in text.splitlines() if l.strip()]
    return [msg("", "", line, "plain") for line in lines]

def sample(messages: list, max_count: int, keywords: list = None) -> list:
    """
    Reduce to max_count messages.
    Strategy: keyword-matching messages get priority slots (up to 30%),
    remaining slots filled by time-distributed uniform sampling.
    """
    if len(messages) <= max_count:
        return messages

    kw = [k.lower() for k in (keywords or [])]
    if kw:
        important = [m for m in messages if any(k in m.get("content", "").lower() for k in kw)]
        important_ids = {id(m) for m in important}
        rest = [m for m in messages if id(m) not in important_ids]
        priority_quota = min(len(important), max_count * 3 // 10)
        fill_quota = max_count - priority_quota
    else:
        important, rest = [], messages
        priority_quota, fill_quota = 0, max_count

    # Uniform time-distributed sample from rest
    step = max(1, len(rest) // fill_quota) if fill_quota > 0 else len(rest)
    sampled_rest = rest[::step][:fill_quota]

    result = important[:priority_quota] + sampled_rest
    result.sort(key=lambda x: x.get("time", ""))
    return result[:max_count]

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

def main():
    parser = argparse.ArgumentParser(
        description="anyone-skill pre-processor: SQLite extraction + large-file sampling"
    )
    parser.add_argument("--input", required=True,
                        help="SQLite .db file, or any large export file to sample")
    parser.add_argument("--target", help="Filter to this sender name/ID only")
    parser.add_argument("--output", help="Output JSON file (default: stdout)")
    parser.add_argument("--max", type=int, default=5000,
                        help="Max messages to keep (default: 5000). Only applies to sampling mode.")
    parser.add_argument("--keywords", help="Comma-separated keywords to prioritize during sampling")
    args = parser.parse_args()

    path = Path(args.input)
    if not path.exists():
        print(f"❌ File not found: {path}", file=sys.stderr)
        sys.exit(1)

    keywords = [k.strip() for k in args.keywords.split(",")] if args.keywords else []

    # SQLite: always extract (binary, agent cannot Read)
    if path.suffix == ".db" or _is_sqlite(path):
        print(f"  Mode: SQLite extraction", file=sys.stderr)
        messages = extract_sqlite(path, args.target)

    # Large file: sample down before agent reads
    else:
        messages = load_any(path)
        if args.target:
            messages = [m for m in messages if args.target in m.get("sender", "")]
        if len(messages) > args.max:
            print(f"  Mode: sampling {len(messages)} → {args.max} messages", file=sys.stderr)
            messages = sample(messages, args.max, keywords)
        else:
            print(f"  Mode: pass-through ({len(messages)} messages, under --max threshold)", file=sys.stderr)
            print(f"  ℹ️  Consider reading this file directly with the Read tool instead.", file=sys.stderr)

    messages.sort(key=lambda x: x.get("time", ""))

    output = json.dumps(messages, ensure_ascii=False, indent=2)
    if args.output:
        Path(args.output).write_text(output, encoding="utf-8")
        print(f"\n✅ {len(messages)} messages → {args.output}", file=sys.stderr)
    else:
        print(output)
        print(f"\n✅ Total: {len(messages)} messages", file=sys.stderr)

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

## File: skills/anyone-skill/scripts/skill_writer.py
size: 3356
sha: 047ef24aa36eae24d0eb5de95187469b989a0adc
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/scripts/skill_writer.py

```text
#!/usr/bin/env python3
"""
skill_writer.py — anyone-skill output manager
Actions: list, init, combine
"""

import argparse
import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path

DEFAULT_BASE = Path(".claude/skills")

def list_skills(base_dir: Path):
    skills = []
    if not base_dir.exists():
        print("No skills found.")
        return
    for meta_path in sorted(base_dir.glob("*/meta.json")):
        try:
            meta = json.loads(meta_path.read_text(encoding="utf-8"))
            skills.append(meta)
        except Exception:
            pass
    if not skills:
        print("No skills found in", base_dir)
        return
    print(f"{'Slug':<24} {'Type':<16} {'Version':<10} {'Updated'}")
    print("-" * 70)
    for m in skills:
        print(
            f"{m.get('slug','?'):<24} "
            f"{m.get('subject-type','?'):<16} "
            f"{m.get('version','?'):<10} "
            f"{m.get('updated-at','?')[:10]}"
        )

def init_skill(slug: str, base_dir: Path, subject_type: str = "personal"):
    skill_dir = base_dir / slug
    skill_dir.mkdir(parents=True, exist_ok=True)
    now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    meta = {
        "slug": slug,
        "version": "0.1.0",
        "subject-type": subject_type,
        "display-name": slug,
        "created-at": now,
        "updated-at": now,
        "sources": [],
        "evidence-summary": {"L1": 0, "L2": 0, "L3": 0, "L4": 0},
        "created-by": "create-anyone@1.0.0",
    }
    meta_path = skill_dir / "meta.json"
    meta_path.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"✅ Initialized {skill_dir}/meta.json")
    return skill_dir

def update_meta(slug: str, base_dir: Path, patch: dict):
    meta_path = base_dir / slug / "meta.json"
    if not meta_path.exists():
        print(f"❌ meta.json not found for {slug}", file=sys.stderr)
        sys.exit(1)
    meta = json.loads(meta_path.read_text(encoding="utf-8"))
    meta.update(patch)
    meta["updated-at"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    meta_path.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"✅ Updated meta.json for {slug}")

def main():
    parser = argparse.ArgumentParser(description="anyone-skill writer")
    parser.add_argument("--action", choices=["list", "init", "update-meta"], required=True)
    parser.add_argument("--slug", help="Persona slug")
    parser.add_argument("--base-dir", default=str(DEFAULT_BASE))
    parser.add_argument("--subject-type", default="personal")
    parser.add_argument("--patch", help="JSON patch string for update-meta")
    args = parser.parse_args()

    base_dir = Path(args.base_dir)

    if args.action == "list":
        list_skills(base_dir)
    elif args.action == "init":
        if not args.slug:
            print("❌ --slug required for init", file=sys.stderr)
            sys.exit(1)
        init_skill(args.slug, base_dir, args.subject_type)
    elif args.action == "update-meta":
        if not args.slug or not args.patch:
            print("❌ --slug and --patch required for update-meta", file=sys.stderr)
            sys.exit(1)
        update_meta(args.slug, base_dir, json.loads(args.patch))

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

## File: skills/anyone-skill/scripts/version_manager.py
size: 3896
sha: b6fd461bc94167a9f970d6d9945f4b1975144291
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/scripts/version_manager.py

```text
#!/usr/bin/env python3
"""
version_manager.py — anyone-skill version control
Actions: bump, rollback, history
"""

import argparse
import json
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path

DEFAULT_BASE = Path(".claude/skills")

def _meta_path(slug: str, base_dir: Path) -> Path:
    p = base_dir / slug / "meta.json"
    if not p.exists():
        print(f"❌ meta.json not found for '{slug}'", file=sys.stderr)
        sys.exit(1)
    return p

def _versions_dir(slug: str, base_dir: Path) -> Path:
    d = base_dir / slug / ".versions"
    d.mkdir(parents=True, exist_ok=True)
    return d

def bump(slug: str, base_dir: Path):
    """Snapshot current state and increment patch version."""
    skill_dir = base_dir / slug
    meta_path = _meta_path(slug, base_dir)
    meta = json.loads(meta_path.read_text(encoding="utf-8"))
    current = meta.get("version", "0.1.0")

    # Snapshot
    versions_dir = _versions_dir(slug, base_dir)
    snap_dir = versions_dir / current
    if not snap_dir.exists():
        shutil.copytree(skill_dir, snap_dir, ignore=shutil.ignore_patterns(".versions"))
    print(f"📸 Snapshotted v{current}")

    # Bump patch
    parts = current.split(".")
    parts[-1] = str(int(parts[-1]) + 1)
    new_version = ".".join(parts)
    meta["version"] = new_version
    meta["updated-at"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    meta_path.write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"🔄 Version bumped: {current} → {new_version}")

def rollback(slug: str, version: str, base_dir: Path):
    """Restore a previously snapshotted version."""
    skill_dir = base_dir / slug
    snap_dir = _versions_dir(slug, base_dir) / version
    if not snap_dir.exists():
        print(f"❌ Snapshot for v{version} not found", file=sys.stderr)
        sys.exit(1)
    # Backup current before rollback
    bump(slug, base_dir)
    # Restore snapshot files (excluding .versions/)
    for src in snap_dir.iterdir():
        if src.name == ".versions":
            continue
        dst = skill_dir / src.name
        if src.is_dir():
            if dst.exists():
                shutil.rmtree(dst)
            shutil.copytree(src, dst)
        else:
            shutil.copy2(src, dst)
    print(f"✅ Rolled back to v{version}")

def history(slug: str, base_dir: Path):
    versions_dir = _versions_dir(slug, base_dir)
    def _ver_key(p):
        try:
            return tuple(int(x) for x in p.name.split("."))
        except ValueError:
            return (0,)
    snapshots = sorted(versions_dir.iterdir(), key=_ver_key) if versions_dir.exists() else []
    if not snapshots:
        print("No version history found.")
        return
    print(f"Version history for '{slug}':")
    for s in snapshots:
        meta_f = s / "meta.json"
        ts = "?"
        if meta_f.exists():
            m = json.loads(meta_f.read_text(encoding="utf-8"))
            ts = m.get("updated-at", "?")[:10]
        print(f"  v{s.name}  ({ts})")

def main():
    parser = argparse.ArgumentParser(description="anyone-skill version manager")
    parser.add_argument("--action", choices=["bump", "rollback", "history"], required=True)
    parser.add_argument("--slug", required=True)
    parser.add_argument("--version", help="Target version for rollback")
    parser.add_argument("--base-dir", default=str(DEFAULT_BASE))
    args = parser.parse_args()

    base_dir = Path(args.base_dir)

    if args.action == "bump":
        bump(args.slug, base_dir)
    elif args.action == "rollback":
        if not args.version:
            print("❌ --version required for rollback", file=sys.stderr)
            sys.exit(1)
        rollback(args.slug, args.version, base_dir)
    elif args.action == "history":
        history(args.slug, base_dir)

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

## File: skills/anyone-skill/references/ethics.md
size: 2686
sha: d0555b8bfed4c674c0eb24c86584898505a5534b
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/references/ethics.md

```text
# Ethics & Copyright Reference

Ethics rules enforced by anyone-skill, layered by subject type.

## Someone you know (colleague, friend, family, partner, ex)

- Chat logs and photos are private data. Confirm **personal use only** before proceeding.
- Not for harassment, stalking, deception, or impersonating the real person to others.
- All data stored locally — nothing is uploaded to any server.
- If the user shows signs of unhealthy fixation (unable to let go, obsessive re-engagement), gently acknowledge it and suggest professional support.

## Yourself

- When chat logs include messages from others, treat those as supporting context only — the distillation focuses on *you*, not them.
- Check that exported data does not include sensitive credentials or private third-party information.

## Public figure (entrepreneur, artist, politician, athlete, etc.)

- Use only **publicly traceable sources**: interviews, published books, speeches, public social media.
- Do not use leaked or private materials.
- Generated skill must include this disclaimer on first activation (say it once, not on every message):  
  *"This persona is based on public information about [name]. It is not the real person and should not be treated as their actual views."*
- Do not fabricate political positions, health information, or private relationships they have not publicly disclosed.

## Historical figure

- Sources must be published: books, documented speeches, academic research, verified letters.
- Claims inferred from incomplete evidence must be tagged L3/L4, not stated as facts.
- Note primary references in the generated skill's `soul/injection.md`.

## Fictional character

### Personal local use (not distributing)
No restrictions. Direct roleplay mode.

### Distributing to others
- Commercial IP: activate **Inspired-by mode**
  - Output must differ meaningfully from the original (reinterpretation, not reproduction)
  - Do not copy verbatim dialogue or lore as the skill's own content
  - Note in `description` frontmatter: `Inspired by [IP name]`
- Open-licensed / public domain: direct roleplay mode, credit the source

### The copyright standard is distribution intent, not publication date
- Keeping it for yourself → no restrictions
- Sharing with others → commercial IP requires Inspired-by mode

## Archetype

- Clearly inform the user: this is a synthetic persona and does not correspond to any real individual.
- Do not take a real person as the primary template with only surface-level changes.

## Universal Layer 0 rule

The generated skill will never speak words the subject would absolutely never say —  
**unless L1 or L2 evidence directly supports it.**
```

## File: skills/anyone-skill/references/output-format.md
size: 6805
sha: 908739c4a050058dbb74446b4c862f568570f79d
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/references/output-format.md

````text
# Output Format Reference

## persona.md — Distillation Working File

`persona.md` is the agent's working document. Stores the full extraction with evidence tags. Never included in the final skill pack — keep it in the working directory alongside `persona.json`.

```markdown
# {Display Name} — persona.md

**Subject type**: self | personal | public | fictional | historical | archetype
**Temporal anchor**: {era or period}
**Version**: 0.1.0 | **Updated**: {date}

---

## Dimension 1: Procedure

### {Model Name}
- **One-liner**: {core pattern}
- **Evidence**: {example} `[L?: source]`
- **When it activates**: {trigger}
- **Breaks down when**: {exception}

(3–6 models total)

**Decision heuristics**: {list with [L?]}
**Information preference**: {data/intuition/mixed + evidence}
**Risk posture**: {bold in X, cautious in Y + evidence}

---

## Dimension 2: Interaction

**Signature voice** (2–3 unmistakable patterns): {with [L?] examples}
**High-frequency vocabulary**: {list}
**Words they never use**: {list}
**Rhythm**: {fast/slow, dense/sparse}
**Emotional temperature**: {description}
**Conflict style**: {description} `[L?]`
**Humor**: {type or absent}

---

## Dimension 3: Memory

| Event | Date/Era | [L?] | Why it matters |
|-------|----------|------|----------------|
| {event} | {date} | L? | {significance} |

**Formative relationships**: {names + pattern}
**Fixations / avoidances**: {themes}
**Defining wound or triumph**: {description} `[L?]`

---

## Dimension 4: Personality

**Core values** (each with one time they held the line):
1. {value} — {example} `[L?]`
2. {value} — {example} `[L?]`
3. {value} — {example} `[L?]`

**Central contradiction**: {description}
**Immutable traits**: {list}
**Layer 0 prohibitions**: {list with [L?]}

---

## Coherence Notes (Phase 4.5)

{Cross-dimension conflicts and resolutions. Unresolved tensions noted explicitly.}

---

## Evidence Summary

| L1 | L2 | L3 | L4 |
|----|----|----|-----|
| {n} | {n} | {n} | {n} |

---

## Voice Test (Phase 5.5)

**Q1 (domain)**: {question} → {response} → Authentic: {yes/no + reason}
**Q2 (values challenge)**: {question} → {response} → Authentic: {yes/no + reason}
**Q3 (off-topic)**: {question} → {response} → Authentic: {yes/no + reason}

---

## Source Index

| Source | Type | L-level | Key extractions |
|--------|------|---------|-----------------|
| {title/url} | interview/book/wiki/chat/export | L? | {what was extracted} |
```

---

## persona.json — Distillation → OpenPersona Field Mapping

anyone-skill's final output is a full OpenPersona skill pack generated via `skills/open-persona`.  
This document defines how the 4-dimension extraction maps to OpenPersona v0.17+ `persona.json` fields.

## Field Mapping

| Extraction dimension | Content | → persona.json field | Notes |
|---|---|---|---|
| **Memory** | Background + key event summary | `soul.identity.bio` | 2–4 sentences, L1/L2 preferred |
| **Memory** | Real name or fictional source | `soul.identity.sourceIdentity` | Required for real/fictional subjects |
| **Interaction** | Speaking style + catchphrases + rhythm | `soul.character.speakingStyle` | 1–3 concrete sentences |
| **Personality** | Core character traits | `soul.character.personality` | Tag-style, 3–5 descriptors |
| **Personality** | Layer 0 prohibitions | `soul.character.boundaries` | String array |
| **Personality** | Immutable traits | `evolution.instance.boundaries.immutableTraits` | String array, max 100 chars each |
| **Procedure** | Mental models (summary) | Folded into `soul.identity.bio` | Full models stay in `persona.md` |

## Full persona.json Template

```json
{
  "soul": {
    "identity": {
      "personaName": "Display name",
      "slug": "lowercase-hyphenated-slug",
      "bio": "2–4 sentence background. Shaped by [key events]. Known for [defining qualities]. From Memory dimension, L1/L2 evidence.",
      "sourceIdentity": "Real name — OR — 'CharacterName from WorkTitle' for fictional subjects"
    },
    "aesthetic": {
      "visualDescription": "Appearance / visual style. Omit this field if unknown."
    },
    "character": {
      "personality": "Core traits in tag form. e.g. 'relentlessly direct, pattern-seeking, allergic to vagueness'. From Personality dimension.",
      "speakingStyle": "Concrete description: sentence length, vocabulary level, catchphrases, emotional temperature. From Interaction dimension.",
      "boundaries": [
        "Layer 0 constraint 1 — backed by L1/L2 evidence",
        "Layer 0 constraint 2"
      ]
    }
  },
  "body": {
    "runtime": {
      "framework": "openclaw",
      "modalities": ["text"]
    }
  },
  "evolution": {
    "instance": {
      "enabled": true,
      "boundaries": {
        "immutableTraits": [
          "Immutable trait 1 — from Personality dimension, L1/L2 evidence",
          "Immutable trait 2"
        ]
      }
    }
  },
  "social": {
    "acn": {
      "enabled": false
    }
  }
}
```

## Differences by Subject Type

### Yourself / Someone you know
- `sourceIdentity`: real name or chosen codename
- `bio`: high L1/L2 ratio from private chat logs, diaries
- `evolution.instance.enabled`: `true` — supports relationship/trait evolution over time

### Public figure / Historical figure
- `sourceIdentity`: their real name
- `bio`: from WebSearch-indexed public sources, mostly L2/L3
- Add to `boundaries`: `"Based on public information. Not the real person. For reference only."`

### Fictional character
- `sourceIdentity`: `"CharacterName from WorkTitle"` (e.g. `"Geralt of Rivia from The Witcher"`)
- When distributing: add to `boundaries`: `"Inspired by [IP name]. Not affiliated with or endorsed by the IP owner."`
- Personal use: no additional constraint needed

### Archetype
- Omit `sourceIdentity`
- Add to `bio`: `"Synthetic persona. Does not correspond to any real individual."`

## Handling the Procedure Dimension

Mental models contain too much detail to compress into `persona.json` fields. Handle as follows:

1. The 1–2 most representative models → distill into `soul.character.personality`
2. Full mental model details → keep in `persona.md` only
3. After `openpersona create` runs, manually append detailed models to `soul/injection.md` if desired

## Generation Commands

```bash
# 1. Generate skill pack
npx openpersona create --config persona.json --output ./{slug}-skill

# 2. Install locally
npx openpersona install ./{slug}-skill

# 3. Activate
npx openpersona switch {slug}
```

## Evolution Update Path

Each Phase 7 evolution cycle:

```
Update persona.md
    ↓
Sync changes to persona.json
    ↓
Re-run: npx openpersona create (overwrites skill pack; state.json is preserved)
    ↓
Bump version: python3 scripts/version_manager.py --action bump --slug {slug}
```
````

## File: skills/anyone-skill/references/training-export.md
size: 3001
sha: f292279272923a5de136d6640f0cf3c1ed769853
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/references/training-export.md

````text
# Training Data Export (Step 6-D)

Export a `training/` directory alongside the skill pack. This feeds `persona-model-trainer` with **both layers** of data.

## Path A: persona-knowledge detected

Run the export script — it generates the entire `training/` directory from the dataset:

```bash
python skills/persona-knowledge/scripts/export_training.py --slug {slug} --output training/
```

This copies `sources/` → `training/raw/`, generates `conversations.jsonl` from wiki, and creates `profile.md`, `metadata.json`, and `probes.json`. Skip to the "After export" report below.

## Path B: no persona-knowledge (default)

```
training/
  raw/                      ← original source files (authentic voice, unmodified)
    chat_logs.jsonl         ← chat exports: {role, content} turns
    books.txt               ← long-form text: treated as persona's monologue
    interviews.jsonl        ← Q&A format: {role:"user"|"assistant", content}
    social_posts.jsonl      ← short posts: {role:"assistant", content}
    [... one file per source]
  conversations.jsonl       ← distilled & structured turns (from Phase 4 extraction)
  profile.md                ← concise character profile (system prompt seed)
  metadata.json             ← slug, name, source count, word count, timestamp
```

**How to build each file:**

> `training/raw/` is already populated progressively during Phase 3 as each source is processed. Do not re-write it here.

`**training/conversations.jsonl`** — write distilled turns from Phase 4 extraction:

Each line is one turn: `{"role": "user"|"assistant", "content": "..."}`.  
Represent the persona's voice as `assistant` turns. Synthesize realistic user prompts for `user` turns.

Minimum 50 turns; aim for 200–500 if source material allows.

`**training/profile.md`** — write a concise 300–500 word character sheet:

```markdown
# {Name} — Character Profile

## Identity
[1–2 sentences: who they are, era, role]

## Voice
[Key vocabulary, catchphrases, sentence rhythm, emotional temperature]

## Core Values
[3 non-negotiable principles]

## Immutable Traits
[3–5 qualities that never change regardless of context]

## Do Not Cross
[Layer 0 prohibitions: what they would never say or do]
```

`**training/metadata.json**`:

```json
{
  "slug": "{slug}",
  "name": "{display name}",
  "subject_type": "personal|public|fictional|historical|archetype",
  "source_count": N,
  "total_words": N,
  "distilled_turns": N,
  "raw_files": ["chat_logs.jsonl", "essays.txt"],
  "created_at": "ISO-8601 timestamp"
}
```

**After export, print:**

```
📦 Training data ready → training/
   raw/                {N} source files  (~{M} words authentic voice)
   conversations.jsonl {N} distilled turns
   profile.md          {N} words
   metadata.json       export version, hash, source snapshot
   probes.json         {N} role consistency probes (auto-generated from wiki)
   → Ready for: persona-model-trainer (pass --probes training/probes.json)
```
````

## File: skills/anyone-skill/.gitignore
size: 173
sha: 6fe9862407bcbec41274907fa48dc54c45375928
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/.gitignore

```text
# Generated persona packs (local only)
.claude/skills/*/materials/
.claude/skills/*/.versions/

# Python
__pycache__/
*.py[cod]
*.egg-info/
.venv/

# OS
.DS_Store
Thumbs.db
```

## File: skills/anyone-skill/CHANGELOG.md
size: 1280
sha: 2a0d861214ce905ac6ab8f825119a6dc5b6a723c
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/CHANGELOG.md

```text
# Changelog — anyone-skill

## [1.1.0] — 2026-04-11

### Added

- **Extended dependency chain** — documented the full local-model path: `anyone-skill → persona-knowledge → persona-model-trainer → runnable persona model`
- **Step 6-D: `--probes` guidance** — after `export_training.py` runs, the step now shows a ready-to-copy `pipeline.sh` command including `--probes ./training/probes.json` and links to `persona-model-trainer/references/pipeline-guide.md`
- **`training-export.md` updated** — "After export" output listing now includes `probes.json` with description; `--probes` usage hint added to the "Ready for" line

### Changed

- Step 6-D description clarified: `export_training.py` also generates `probes.json` (in addition to `conversations.jsonl`, `profile.md`, `metadata.json`)

---

## [1.0.0] — initial release

- Phase 0–7 distillation workflow: classify, ethics check, intake, collect sources, 4-dimension extraction, evidence grading, OpenPersona pack generation, evolution
- `persona-knowledge` integration (Phase 3 Path A): ingest → MemPalace + KG + wiki → export
- Step 6-D: training data export for `persona-model-trainer`
- Subject strategy reference (yourself / someone you know / public figure / fictional / historical / archetype)
```

## File: skills/anyone-skill/publish.sh
size: 1836
sha: 0b758de5e76916db2d2e62f74d9379d60fc76776
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/publish.sh

```text
#!/usr/bin/env bash
# Publish anyone-skill to ClawHub.
# Usage: ./publish.sh --changelog "..." [--version 1.2.0] [--dry-run]
set -euo pipefail

SLUG="anyone-skill"
SKILL_DIR="$(cd "$(dirname "$0")" && pwd)"

# Read version from SKILL.md (metadata.version field) as default
_skill_version() {
  awk -F'"' '/version:/{print $2; exit}' "${SKILL_DIR}/SKILL.md"
}

VERSION="$(_skill_version)"
CHANGELOG=""
DRY_RUN=false

while [[ $# -gt 0 ]]; do
  case $1 in
    --version)   VERSION="$2";    shift 2 ;;
    --changelog) CHANGELOG="$2";  shift 2 ;;
    --dry-run)   DRY_RUN=true;    shift   ;;
    *) echo "Unknown option: $1"; exit 1  ;;
  esac
done

if [[ -z "${CHANGELOG}" ]]; then
  echo "Error: --changelog is required" >&2
  echo "Usage: ./publish.sh --changelog \"What changed in this release\"" >&2
  exit 1
fi

DIST_DIR="$(mktemp -d)/${SLUG}"

echo "→ Packaging ${SLUG} v${VERSION} …"
rsync -a \
  --exclude='tests/' \
  --exclude='models/' \
  --exclude='CHANGELOG.md' \
  --exclude='README.md' \
  --exclude='publish.sh' \
  --exclude='.git' \
  --exclude='.gitignore' \
  --exclude='.pytest_cache/' \
  --exclude='__pycache__/' \
  --exclude='*.pyc' \
  --exclude='.agents/' \
  --exclude='.claude/' \
  --exclude='.continue/' \
  --exclude='.kiro/' \
  --exclude='.trae/' \
  --exclude='.windsurf/' \
  --exclude='skills-lock.json' \
  "${SKILL_DIR}/" "${DIST_DIR}/"

echo "→ Package contents:"
find "${DIST_DIR}" -type f | sed "s|${DIST_DIR}/||" | sort

if [[ "${DRY_RUN}" == true ]]; then
  echo "→ Dry run — skipping publish. Package at: ${DIST_DIR}"
  exit 0
fi

echo "→ Publishing to ClawHub …"
clawdhub publish "${DIST_DIR}" \
  --slug  "${SLUG}" \
  --name  "anyone-skill" \
  --version "${VERSION}" \
  --changelog "${CHANGELOG}"

rm -rf "$(dirname "${DIST_DIR}")"
echo "✓ Published ${SLUG} v${VERSION}"
```

## File: skills/anyone-skill/tests/test_scripts.py
size: 15168
sha: e293aa893b35fb206239b3462936efd735e9dddc
upstream: https://github.com/acnlabs/openpersona/blob/main/skills/anyone-skill/tests/test_scripts.py

```text
"""
Unit tests for anyone-skill utility scripts:
  - preprocess.py  — SQLite extraction + large-file sampling
  - skill_writer.py — persona skill directory initialisation + meta management
  - version_manager.py — bump / rollback / history
"""

import json
import shutil
import sqlite3
import sys
import tempfile
import unittest
from pathlib import Path

SCRIPTS_DIR = Path(__file__).resolve().parent.parent / "scripts"
sys.path.insert(0, str(SCRIPTS_DIR))

import preprocess
import skill_writer
import version_manager

# ── helpers ───────────────────────────────────────────────────────────────────

def _make_imessage_db(path: Path) -> None:
    """Create a minimal iMessage-schema SQLite database for testing."""
    con = sqlite3.connect(str(path))
    con.execute("CREATE TABLE handle (ROWID INTEGER PRIMARY KEY, id TEXT)")
    con.execute("CREATE TABLE message (date INTEGER, handle_id INTEGER, text TEXT)")
    con.execute("INSERT INTO handle VALUES (1, 'alice@example.com')")
    # date: Apple epoch (seconds since 2001-01-01); store in nanoseconds
    con.execute("INSERT INTO message VALUES (0, 1, 'Hello from Alice')")
    con.execute("INSERT INTO message VALUES (1000000000, 0, 'Reply from me')")
    con.commit()
    con.close()

def _make_wechat_db(path: Path) -> None:
    """Create a minimal WeChat MSG-schema SQLite database for testing."""
    con = sqlite3.connect(str(path))
    con.execute("CREATE TABLE MSG (CreateTime TEXT, NickName TEXT, Content TEXT)")
    con.execute("INSERT INTO MSG VALUES ('2026-01-01', 'Bob', 'Hi there')")
    con.execute("INSERT INTO MSG VALUES ('2026-01-02', 'Me', 'Hey Bob')")
    con.commit()
    con.close()

# ── preprocess.py ─────────────────────────────────────────────────────────────

class TestMsgConstructor(unittest.TestCase):
    def test_fields(self):
        m = preprocess.msg("2026-01-01", "Alice", "Hello", "imessage")
        self.assertEqual(m["time"],     "2026-01-01")
        self.assertEqual(m["sender"],   "Alice")
        self.assertEqual(m["content"],  "Hello")
        self.assertEqual(m["platform"], "imessage")

    def test_returns_dict(self):
        m = preprocess.msg("t", "s", "c", "p")
        self.assertIsInstance(m, dict)

class TestIsSqlite(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def test_true_for_sqlite_file(self):
        p = Path(self.tmp) / "db.db"
        con = sqlite3.connect(str(p))
        con.execute("CREATE TABLE t (x TEXT)")
        con.close()
        self.assertTrue(preprocess._is_sqlite(p))

    def test_false_for_text_file(self):
        p = Path(self.tmp) / "plain.txt"
        p.write_text("hello world")
        self.assertFalse(preprocess._is_sqlite(p))

    def test_false_for_missing_file(self):
        self.assertFalse(preprocess._is_sqlite(Path(self.tmp) / "nonexistent.db"))

class TestLoadAny(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def test_loads_json_list(self):
        p = Path(self.tmp) / "msgs.json"
        data = [{"content": "hi", "sender": "Alice", "time": "2026-01-01"}]
        p.write_text(json.dumps(data))
        result = preprocess.load_any(p)
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0]["content"], "hi")

    def test_loads_json_with_messages_key(self):
        p = Path(self.tmp) / "export.json"
        data = {"messages": [{"content": "hello", "sender": "Bob"}]}
        p.write_text(json.dumps(data))
        result = preprocess.load_any(p)
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0]["content"], "hello")

    def test_loads_plain_text(self):
        p = Path(self.tmp) / "notes.txt"
        p.write_text("Line one\nLine two\n\nLine three\n")
        result = preprocess.load_any(p)
        self.assertEqual(len(result), 3)
        self.assertEqual(result[0]["content"], "Line one")

    def test_skips_empty_lines_in_plain_text(self):
        p = Path(self.tmp) / "sparse.txt"
        p.write_text("\n\nOnly line\n\n")
        result = preprocess.load_any(p)
        self.assertEqual(len(result), 1)

    def test_strips_js_wrapper(self):
        """X/Twitter archive files start with 'window.YTD.tweets.part0 = [...]'"""
        p = Path(self.tmp) / "tweets.js"
        data = [{"full_text": "A tweet", "created_at": "Mon Jan 01 2026"}]
        p.write_text(f"window.YTD_tweets = {json.dumps(data)};")
        result = preprocess.load_any(p)
        self.assertGreater(len(result), 0)

class TestSample(unittest.TestCase):
    def _msgs(self, n: int) -> list:
        return [preprocess.msg(str(i), "u", f"msg {i}", "test") for i in range(n)]

    def test_under_limit_returns_all(self):
        msgs = self._msgs(10)
        result = preprocess.sample(msgs, 20)
        self.assertEqual(len(result), 10)

    def test_over_limit_reduces_to_max(self):
        msgs = self._msgs(1000)
        result = preprocess.sample(msgs, 100)
        self.assertEqual(len(result), 100)

    def test_keyword_messages_prioritised(self):
        msgs = [preprocess.msg(str(i), "u", "ordinary message", "t") for i in range(200)]
        # Inject 10 important messages
        for i in range(10):
            msgs[i * 20]["content"] = "IMPORTANT keyword"
        result = preprocess.sample(msgs, 50, keywords=["important"])
        texts = [m["content"] for m in result]
        kw_hits = sum(1 for t in texts if "important" in t.lower())
        self.assertGreater(kw_hits, 0)

    def test_empty_input_returns_empty(self):
        self.assertEqual(preprocess.sample([], 10), [])

    def test_result_sorted_by_time(self):
        msgs = self._msgs(100)
        result = preprocess.sample(msgs, 20)
        times = [m["time"] for m in result]
        self.assertEqual(times, sorted(times))

class TestExtractSqlite(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def test_imessage_extraction(self):
        p = Path(self.tmp) / "chat.db"
        _make_imessage_db(p)
        results = preprocess.extract_imessage(p, target=None)
        self.assertGreater(len(results), 0)
        self.assertEqual(results[0]["platform"], "imessage")

    def test_imessage_target_filter(self):
        p = Path(self.tmp) / "chat.db"
        _make_imessage_db(p)
        results = preprocess.extract_imessage(p, target="alice")
        # Only alice@example.com messages (not "me") should remain
        for r in results:
            self.assertIn("alice", r["sender"].lower())

    def test_wechat_extraction(self):
        p = Path(self.tmp) / "wechat.db"
        _make_wechat_db(p)
        results = preprocess.extract_wechat(p, target=None)
        self.assertGreater(len(results), 0)
        self.assertEqual(results[0]["platform"], "wechat")

    def test_dispatch_detects_imessage(self):
        p = Path(self.tmp) / "imsg.db"
        _make_imessage_db(p)
        results = preprocess.extract_sqlite(p, target=None)
        self.assertTrue(all(r["platform"] == "imessage" for r in results))

    def test_dispatch_detects_wechat(self):
        p = Path(self.tmp) / "wx.db"
        _make_wechat_db(p)
        results = preprocess.extract_sqlite(p, target=None)
        self.assertTrue(all(r["platform"] == "wechat" for r in results))

# ── skill_writer.py ───────────────────────────────────────────────────────────

class TestInitSkill(unittest.TestCase):
    def setUp(self):
        self.tmp = Path(tempfile.mkdtemp())

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def test_creates_meta_json(self):
        skill_writer.init_skill("alice", self.tmp)
        self.assertTrue((self.tmp / "alice" / "meta.json").exists())

    def test_meta_fields(self):
        skill_writer.init_skill("bob", self.tmp, subject_type="public")
        meta = json.loads((self.tmp / "bob" / "meta.json").read_text())
        self.assertEqual(meta["slug"], "bob")
        self.assertEqual(meta["subject-type"], "public")
        self.assertEqual(meta["version"], "0.1.0")
        self.assertIn("created-at", meta)
        self.assertIn("evidence-summary", meta)

    def test_default_subject_type_personal(self):
        skill_writer.init_skill("carol", self.tmp)
        meta = json.loads((self.tmp / "carol" / "meta.json").read_text())
        self.assertEqual(meta["subject-type"], "personal")

    def test_idempotent_does_not_crash(self):
        skill_writer.init_skill("dave", self.tmp)
        # Second call should not crash (dir already exists)
        skill_writer.init_skill("dave", self.tmp)
        self.assertTrue((self.tmp / "dave" / "meta.json").exists())

class TestListSkills(unittest.TestCase):
    def setUp(self):
        self.tmp = Path(tempfile.mkdtemp())

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def test_empty_dir_prints_no_skills(self, *_):
        import io
        from unittest.mock import patch
        with patch("sys.stdout", new_callable=io.StringIO) as mock_out:
            skill_writer.list_skills(self.tmp)
        self.assertIn("No skills", mock_out.getvalue())

    def test_lists_initialized_skills(self):
        skill_writer.init_skill("eve", self.tmp)
        skill_writer.init_skill("frank", self.tmp)
        import io
        from unittest.mock import patch
        with patch("sys.stdout", new_callable=io.StringIO) as mock_out:
            skill_writer.list_skills(self.tmp)
        output = mock_out.getvalue()
        self.assertIn("eve", output)
        self.assertIn("frank", output)

    def test_missing_dir_prints_no_skills(self):
        import io
        from unittest.mock import patch
        with patch("sys.stdout", new_callable=io.StringIO) as mock_out:
            skill_writer.list_skills(self.tmp / "nonexistent")
        self.assertIn("No skills", mock_out.getvalue())

class TestUpdateMeta(unittest.TestCase):
    def setUp(self):
        self.tmp = Path(tempfile.mkdtemp())
        skill_writer.init_skill("grace", self.tmp)

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def test_patch_applied(self):
        skill_writer.update_meta("grace", self.tmp, {"display-name": "Grace Hopper"})
        meta = json.loads((self.tmp / "grace" / "meta.json").read_text())
        self.assertEqual(meta["display-name"], "Grace Hopper")

    def test_updated_at_refreshed(self):
        before = json.loads((self.tmp / "grace" / "meta.json").read_text())["updated-at"]
        import time; time.sleep(0.01)
        skill_writer.update_meta("grace", self.tmp, {"display-name": "G"})
        after = json.loads((self.tmp / "grace" / "meta.json").read_text())["updated-at"]
        # updated-at should be refreshed (may be same second but field must exist)
        self.assertIsNotNone(after)

    def test_existing_fields_preserved(self):
        skill_writer.update_meta("grace", self.tmp, {"extra": "value"})
        meta = json.loads((self.tmp / "grace" / "meta.json").read_text())
        self.assertEqual(meta["slug"], "grace")
        self.assertIn("evidence-summary", meta)

# ── version_manager.py ────────────────────────────────────────────────────────

class TestBump(unittest.TestCase):
    def setUp(self):
        self.tmp = Path(tempfile.mkdtemp())
        skill_writer.init_skill("henry", self.tmp)

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def test_bumps_patch_version(self):
        version_manager.bump("henry", self.tmp)
        meta = json.loads((self.tmp / "henry" / "meta.json").read_text())
        self.assertEqual(meta["version"], "0.1.1")

    def test_creates_snapshot(self):
        version_manager.bump("henry", self.tmp)
        snap_dir = self.tmp / "henry" / ".versions" / "0.1.0"
        self.assertTrue(snap_dir.exists())

    def test_snapshot_contains_meta(self):
        version_manager.bump("henry", self.tmp)
        snap_meta = self.tmp / "henry" / ".versions" / "0.1.0" / "meta.json"
        self.assertTrue(snap_meta.exists())

    def test_double_bump(self):
        version_manager.bump("henry", self.tmp)
        version_manager.bump("henry", self.tmp)
        meta = json.loads((self.tmp / "henry" / "meta.json").read_text())
        self.assertEqual(meta["version"], "0.1.2")

class TestHistory(unittest.TestCase):
    def setUp(self):
        self.tmp = Path(tempfile.mkdtemp())
        skill_writer.init_skill("iris", self.tmp)

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def test_empty_history(self):
        import io
        from unittest.mock import patch
        with patch("sys.stdout", new_callable=io.StringIO) as mock_out:
            version_manager.history("iris", self.tmp)
        self.assertIn("No version history", mock_out.getvalue())

    def test_history_shows_snapshot(self):
        version_manager.bump("iris", self.tmp)
        import io
        from unittest.mock import patch
        with patch("sys.stdout", new_callable=io.StringIO) as mock_out:
            version_manager.history("iris", self.tmp)
        self.assertIn("0.1.0", mock_out.getvalue())

class TestRollback(unittest.TestCase):
    def setUp(self):
        self.tmp = Path(tempfile.mkdtemp())
        skill_writer.init_skill("jack", self.tmp)
        # Write a sentinel file to v0.1.0 state
        (self.tmp / "jack" / "sentinel.txt").write_text("original")
        version_manager.bump("jack", self.tmp)  # snapshots 0.1.0, bumps to 0.1.1
        # Overwrite sentinel in v0.1.1
        (self.tmp / "jack" / "sentinel.txt").write_text("modified")

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def test_rollback_restores_file(self):
        version_manager.rollback("jack", "0.1.0", self.tmp)
        content = (self.tmp / "jack" / "sentinel.txt").read_text()
        self.assertEqual(content, "original")

    def test_rollback_bumps_current_first(self):
        """rollback() calls bump() first, so version advances before restoring."""
        version_manager.rollback("jack", "0.1.0", self.tmp)
        meta = json.loads((self.tmp / "jack" / "meta.json").read_text())
        # After rollback, meta.json is from the restored snapshot (0.1.0)
        self.assertEqual(meta["version"], "0.1.0")

    def test_rollback_missing_version_exits(self):
        with self.assertRaises(SystemExit):
            version_manager.rollback("jack", "9.9.9", self.tmp)

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