当前位置: 首页 > Skill >

Perstate

Perstate

Perstate

Git 原生、基于知识图谱的持久化状态,用于人格和代理

1.1.0 2026.11.14 866
获取Skill文件查看使用说明
作 者:陆安 许可证: 更新时间:2026.11.14
本文目录展开

Commands

All operations use the /perstate prefix. Scripts are in the skill's scripts/ directory.

Agent receives skill content + args, maps args to the corresponding command below.

Command Purpose Script
/perstate Status check (no side effects, shows config completeness and session binding, guides init) scripts/perstate-info.sh --status --session-id <id>
/perstate init Initialize config (Agent guides user to provide repo URL and branch name) scripts/perstate-init.sh [--repo <url>] [--branch <branch>]
/perstate save [content] Write memory (scan context or write specified content. Create/update/delete determined by Agent from semantics) scripts/perstate-prepare.sh --session-id <id> → knowledge processing → scripts/perstate-commit.sh --session-id <id>
/perstate search <keyword> Recall memory (single-point, multi-hop, subgraph, natural language) scripts/perstate-search.sh --session-id <id> <keyword> (fast path: --read mode skips sync, grep -RErIn batch scan)
/perstate info Memory statistics (entity count, relation count, recent commits) scripts/perstate-info.sh --session-id <id>
/perstate view Render memory graph in browser scripts/perstate-view.sh --session-id <id>
/perstate fork <name> Fork new branch from current and rebind scripts/perstate-fork.sh --name <name> --session-id <id>
/perstate switch <branch> Switch current session's bound branch scripts/perstate-switch.sh --name <branch> --session-id <id>
/perstate prune [Nd] Clean expired session bindings, worktrees, and invalid branches (preview then confirm) scripts/perstate-prune.sh <days>d [--session-id <id>] [--execute]

Agent must always pass --session-id <id> when calling scripts, do not use --worktree to bypass session binding. Unbound sessions must go through the session binding flow first. Session ID source: CC uses session UUID, Kimi Code uses session path ID, other platforms use session identifier or date +%s. Do not use $$ or basename "$PWD".

Initialization (/perstate init)

Flow when user runs /perstate init:

  1. Agent collects repo + branch (cannot skip):
    • If config exists → read default_repo and default_branch, use structured interaction to confirm or modify
    • If config doesn't exist → use AskUserQuestion (one call, two questions):
      • Repo address: options SSH remote (recommended) / local path / HTTPS remote (not recommended) + Other for custom input
      • Branch name: options main (default) / custom + Other for custom input
  2. Agent executes script (pass --yes to skip script's interactive confirmation, since Agent already confirmed in step 1):
    scripts/perstate-init.sh --repo <url> --branch <branch> --yes
    
  3. Script auto-completes: check git → check repo protocol (non-SSH gives security warning) → write config → clone repo → create worktree → create initial structure → commit & push

Remote vs Local (unified architecture):

  • bare clone to ~/.perstate/<repo-name>.git/, worktree at ~/.perstate/worktrees/<repo-name>/<branch>/
  • Remote git URL (git@... recommended / https://...): push/pull over network
  • Local path: push/pull over filesystem (instant). Auto git init if not a git repo
  • Multi-repo coexist, switching doesn't clean old repos (local cache)

Session Binding (entry point for save/search/info/view/fork/switch)

Before executing /perstate save, /perstate search, /perstate info, /perstate view, /perstate fork, /perstate switch, go through the session binding flow to determine branch.

/perstate (no args, status check) and /perstate prune don't need session binding.

Scenario 1: First install (config doesn't exist)

Check if system prompt specifies perstate repo: <url>:

  • Specified → run scripts/perstate-init.sh --repo <url> --branch <perstate branch or main> --yes, continue with original command after init
  • Not specified → collect repo+branch in current interaction (same as "Initialization" step 1), run init, continue with original command

Scenario 2: First binding (config exists, session unbound)

Check if system prompt specifies branch (see scenario 3). If not → use structured interaction to confirm: "Default is personal memory (<default_branch> branch). Confirm? Or enter a new branch name:"

  • Confirm → bind default_branch; enter new name → bind that branch (auto-create if doesn't exist)

Write to config:

grep -q "^sessions:" ~/.perstate/config.yml || echo "sessions:" >> ~/.perstate/config.yml
cat >> ~/.perstate/config.yml << EOF
  <session-id>:
    branch: <branch>
EOF

Scenario 3: System prompt specified (no confirmation needed)

System prompt can contain:

perstate repo: <repo-url>       # Only when config doesn't exist, skip init confirmation
perstate branch: <branch-name>  # Only when session unbound, skip binding confirmation

Local config takes priority: if config exists, perstate repo: is ignored. If session bound, perstate branch: is ignored. System prompt only applies on first-time setup, never overrides existing config.

Scenario 4: Already bound

Session has binding → use directly, no prompt:

grep -q "^  <session-id>:" ~/.perstate/config.yml && echo "bound" || echo "unbound"
SESSION_BRANCH=$(grep -A1 "^  <session-id>:" ~/.perstate/config.yml | grep "branch:" | sed 's/^[^:]*: *//')

After all scenarios: prepare worktree + sync

Once branch is determined:

  • save/search: Agent manually runs prepare → cd "$(scripts/perstate-prepare.sh --session-id <id>)"
  • info/view/fork/switch: scripts internally call prepare.sh, just call the script directly
  • search (fast path): scripts/perstate-search.sh --session-id <id> <keyword> — internally calls prepare with --read mode, uses grep batch scan + reverse/multi-hop traversal

perstate-prepare.sh auto-completes: worktree create/reuse + git fetch origin + git pull --ff-only, ensuring local branch is in sync with remote.

Sync cache (performance): prepare.sh caches the last sync timestamp per <repo>__<branch> in ~/.perstate/.sync/. Within the cache window (60s for writes, 300s for reads), git fetch + git pull are skipped entirely — a single save followed by search makes zero network round trips. Flags: --read (read mode, longer window), --no-sync (skip network entirely), --force-sync (ignore cache), --sync-window <sec> (custom window).

Content index (large-scale search): perstate-index.sh builds a transient content index at ~/.perstate/.index/<repo>__<branch>.content — all entity/relation file contents concatenated into a single stream. search and info use this index when fresh (auto-detected via git HEAD) instead of scanning 400k+ files with grep -r. At 100k entities / 300k relations: search drops from ~120s (grep -r) to ~5s (index awk scan), a 24x improvement. The index is a transient cache, not the knowledge graph data source — falls back to grep -r only if rebuild fails. Auto-refresh: search/info rebuild the index automatically when absent or stale (HEAD mismatch) — users never need to maintain it manually. Rebuild explicitly with scripts/perstate-index.sh --worktree <path> --rebuild.

Repository Structure

entities/
  <entity-id>/
    entity.md                   # Entity metadata + free-form knowledge
    <relation-type>/            # Out-relation directory (e.g. depends-on/, enables/)
      <target-id>.md            # One relation: this entity --type--> target
schema/
  ontology.md                   # Entity types, relation types definition

File system IS the index: ls entities/ lists all entities, ls entities/<id>/ lists out-relation types.

entity-id naming convention

kebab-case, English preferred (e.g. llm-evaluation), must be valid as directory/file name.

File Formats

entity.md

---
id: llm-evaluation
label: LLM Evaluation
type: domain
aliases: [LLM evaluation, model benchmarking]
created_at: 2026-07-14
updated_at: 2026-07-15
sources: ["arxiv:2505.20416", "github:user/repo"]
---

## Overview

LLM evaluation is the systematic measurement of LLM capabilities...

## Key Insights

(Knowledge about this entity itself, not about specific relations)

## Sources

- arxiv:2505.20416 — paper PDF (§4 Method, §5.3 Scaling)
- github:user/repo — README + source code (background_review.py#L1-L25)

relation file (entities/<from>/<type>/<to>.md)

---
from: llm-evaluation
to: harness
type: depends-on
created_at: 2026-07-14
updated_at: 2026-07-15
valid_until: null
sources: ["arxiv:2505.20416 §4", "chat:2026-07-14"]
---

## Insight

LLM evaluation fundamentally depends on harness's engineering capabilities...

Temporal fields

Field Meaning
created_at First recorded date
updated_at Last modified date
valid_until null = still valid; a date = superseded (soft delete)
git history Full provenance (git log --follow <file>)

Write Flow (/perstate save)

1. Extract entities and relations

From conversation insights (or user-specified info), identify:

  • Entities (concepts, domains, technologies)
  • Relations (depends-on, enables, contradicts, etc.)
  • Relation content (the crystallized insight on each relation)

2. Dedup, disambiguate, merge

For each entity:

ls entities/ | grep -i "<entity-id>"           # by id
grep -rl "label:.*<label>" entities/            # by label
grep -rl "<alias>" entities/*/entity.md          # by alias
  • No match → create new; one match → merge (update frontmatter, append body); multiple matches → disambiguate using context

For each relation:

ls entities/<from>/<type>/ | grep "<target>"
  • No match → create new; match → merge (append insight)

3. Write files

Follow templates in "File Formats" section, replacing <placeholders> with actual values.

Create entity: mkdir -p entities/<id> → write entity.md from template

Merge entity: read existing → update frontmatter updated_at + aliases union + sources append → append ### subsection (with date) → use Edit tool

Create relation: mkdir -p entities/<from>/<type> → write <to>.md from template

Merge relation: read existing → update frontmatter updated_at + sources append → append ### subsection → use Edit tool

Delete: locate target → soft delete (set valid_until) or hard delete (rm + clean empty dirs)

4. Commit

scripts/perstate-commit.sh --message "perstate: <summary>" --session-id <session-id>

All steps must complete synchronously within one turn. Never split prepare and commit across turns.

Query Patterns (/perstate search)

Prefer the dedicated scripts/perstate-search.sh for fast keyword/reverse/multi-hop queries. It uses --read mode (skips network sync) and batch grep -RErIn scan. For ad-hoc shell queries, prepare the worktree first then use the commands below.

Basic queries:

cat entities/<id>/entity.md                    # single entity
ls entities/                                     # full overview
ls entities/<id>/                                # list out-relation types
ls entities/<id>/depends-on/                    # specific relation type
cat entities/<id>/depends-on/<target>.md         # read one relation
grep -rl "keyword" entities/ | head -5             # keyword search

Advanced queries:

# Multi-hop traversal
FIRST_HOP=$(ls entities/X/depends-on/ | sed 's/.md$//')
for target in $FIRST_HOP; do echo "=== $target ==="; ls entities/$target/depends-on/ 2>/dev/null; done

# Reverse lookup (who points to X?)
find entities/ -name "X.md" -type f
grep -rl "to: X" entities/

# Temporal query
ls -lt entities/X/depends-on/
git log --oneline -10

# Subgraph extraction (2-hop)
find entities/X/ -name "*.md" -not -name "entity.md"
find entities/ -path "*/X.md"

# Valid relations only
grep -rl "valid_until: null" entities/X/depends-on/

Natural language query: extract keywords → grep -rl to locate → read matching files → synthesize summary Result aggregation: after multi-hop/multi-file queries → merge → dedup → sort by relevance or time → summarize

Additional Commands

info: outputs repo, branch, path, size, entity count, relation count (valid/superseded/undeclared), recent commits. Script internally calls prepare.sh.

view: generates interactive HTML graph (vis-network), auto-opens browser. Nodes colored by entity type, edges labeled with relation type. Script internally calls prepare.sh.

fork <name>: forks new branch from current and rebinds. Script auto-completes: read current binding → create new branch → create worktree → update session binding → push to remote. After fork, subsequent writes go to the new branch; original branch memory is fully preserved.

switch <branch>: switches to an existing branch (vs fork: fork copies into a new branch, switch changes to an existing one). Script auto-completes: validate branch exists → in-place rewrite config binding → call prepare to create worktree and pull. Common usage: after fork experiment, /perstate switch main to go back.

prune [Nd]: two-step flow (preview → confirm → execute, see command table). Cleans: expired session bindings (worktree mtime > N days), expired worktrees (first git worktree prune, then remove), invalid branches (local exists but remote deleted, git branch -d safe delete), orphan content index (index files whose branch no longer exists in the bare repo).

Trigger Timing

When to search (recall)

  • Before answering a question that might relate to accumulated knowledge
  • At conversation start if the topic is within the agent's expertise domains
  • When user says "recall" / "remember" / "memory" / "before" / "you mentioned earlier"

When to save (persist)

  • After producing high-dimensional insights (high-dimensional = non-trivial analysis, pattern recognition, causal reasoning, experience synthesis; NOT data statistics or fact listing)
  • When user says "persist" / "remember" / "save" / "save insight"
  • Do NOT trigger: on every message, on conversations without substantive insight, on pure execution tasks

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,035
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,019
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,014
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,014
Skill 文件
  • SKILL.md
    • Commands
    • Initialization (/perstate init)
    • Session Binding (entry point for save/search/info/view/fork/switch)
      • Scenario 1: First install (config doesn't exist)
      • Scenario 2: First binding (config exists, session unbound)
      • Scenario 3: System prompt specified (no confirmation needed)
      • Scenario 4: Already bound
      • After all scenarios: prepare worktree + sync
    • Repository Structure
      • entity-id naming convention
    • File Formats
      • entity.md
      • relation file (entities/<from>/<type>/<to>.md)
      • Temporal fields
    • Write Flow (/perstate save)
      • 1. Extract entities and relations
      • 2. Dedup, disambiguate, merge
      • 3. Write files
      • 4. Commit
    • Query Patterns (/perstate search)
    • Additional Commands
    • Trigger Timing
      • When to search (recall)
      • When to save (persist)
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期