skill-system-memory について
skill-system-memoryは、PostgreSQLを使った永続的な共有メモリをAIエージェントに提供し、プロジェクト単位で分離します。任意のMCPサーバーから、メモリの検索や管理を利用できます。
主な機能
- 01PostgreSQLによる永続メモリ
- 02プロジェクト単位のDB分離
- 03ハイブリッド検索
- 04メモリのコンテキストと状態管理
- 05明示的なDB横断読み取り
活用シーン
- 01セッションをまたいだエージェントの記憶保持
- 02プロジェクトメモリからの情報検索
- 03圧縮やメモリ喪失後のコンテキスト再構築
MCP 対応
付属のMCPサーバーは、メモリの検索、保存、更新、削除に加え、コンテキストや状態を扱うツールを公開します。スキーマと状態のリソースも提供します。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ arthur0824hao/ skills --skill skill-system-memoryインストール後、Claude Code で/skill-system-memoryを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
SKILL.behavior.yamlSKILL.meta.yamlSKILL.spec.yamlans-myelin-bridge-contract.yamlclose-report-ingestion-runbook.mdinit.sqlmcp.jsonmemory-mirror-config.yamlmemory-mirror-contract.mdmigrate-v2-postgres-first.sqlmyelin-registry.schema.yamlmyelin-seeds.yamlschema-diagram.mdartifacts/myelin-registry.jsonhooks/log-compaction.ps1log-compaction.shmemory-rebuild-reminder.shtest_log_compaction.pytest_memory_rebuild_reminder.pymcp/requirements.txtserver.pytest_mcp_server.pyplugins/runtime_sync.jsruntime_sync.test.mjsskill-system-memory.jsscripts/auto-write-template.mdbootstrap.ps1bootstrap.shconsolidate-compactions.ps1consolidate-compactions.sh詳細
スキルシステムメモリ(PostgreSQL)
すべての AI エージェントで共有される永続メモリです。Linux または Windows 上の PostgreSQL 14 以降に対応しています。 メモリの失敗は、知能の失敗に見えることがあります。このスキルにより、適切なタイミングで適切なメモリを取得できます。
契約に関する注意事項:
- モジュール優先:
mem.pyと MCP ツールが主なランタイムインターフェースです。 - プラグインは任意:OpenCode プラグインとの統合はアダプターレイヤーであり、必須の依存関係ではありません。
- プロジェクト単位の DB 命名を推奨します:
<project>-memory(例:skills-memory)。
DB のターゲット設定 — プロジェクトの分離
スキルはグローバルにインストールされますが、メモリはプロジェクト単位です。分離はデータベースレベルで行われ、各プロジェクトには <project>-memory という名前の専用 PostgreSQL データベースが割り当てられます。
複数 DB をまたぐ検索は明示的な読み取り側機能であり、デフォルトの動作ではありません。呼び出し元が scope=all または cross_db=true を指定しない限り、検索とコンテキストの読み取りは現在のメモリ DB 内にとどまります。すべての書き込み処理は、ローカルの SKILL_PGDATABASE ターゲットに固定されます。
Search Path のロールアーキテクチャ(SK-C)
互換性を保った段階的な導入経路は、既存の仕組みに追加する形です。
- 従来のモードは、プロジェクトごとの DB を使用します:
SKILL_PGDATABASE=<project>-memory - 共有 DB モードは、明示的に指定した共有 DB とスキーマ分離を使用します
- ランタイムロールは
admin、connector、visitor_<identity>に分かれます
ロールモデル:
admin:マイグレーションと初期化のみ。スキーマ、権限、ロールを作成しますconnector:CONNECT のみの認証情報。DB 接続を開き、直ちにSET ROLEを実行しますvisitor_<identity>:search_pathが強制される日常的なクエリ用ロールです
Visitor の search_path マトリックス:
visitor_hermes:ep_scope, sk_scope, fd_scope, work_scope, publicvisitor_atlas:ep_scope, publicvisitor_athena:sk_scope, publicvisitor_fd_coder:fd_scope, publicvisitor_ep_coder:ep_scope, publicvisitor_sk_coder:sk_scope, publicvisitor_hephaestion:work_scope, sk_scope, public
共有 DB モードは明示的で、後方互換性があります。
SKILL_PGSHARED_DB=<shared-db-name>で共有 DB を選択しますSKILL_PGSCHEMA=<scope-schema>でローカルの書き込み可能なスキーマを選択します- 従来のプロジェクトごとの DB モードでは、引き続き
SKILL_PGDATABASEを使用できます
共有 DB モードのランタイムフロー:
connectorとして接続しますSET ROLE visitor_<identity>を実行します- スコープ付きクエリには visitor の
search_pathを使用します - 全スコープの監査クエリでは、Hermes のみ明示的なオーバーライドを許可します
共有 DB の例:
# Provision shared DB schemas/roles for SK scope
python3 scripts/mem.py init-project \
--project-id sk \
--db-name shared-memory \
--schema-name sk_scope \
--shared-db-mode
# Run local SK queries through shared DB scope
SKILL_PGSHARED_DB=shared-memory \
SKILL_PGSCHEMA=sk_scope \
SKILL_VISITOR_ROLE=visitor_sk_coder \
python3 scripts/mem.py search "router policy"
# Hermes explicit all-scopes audit across the shared DB
SKILL_PGSHARED_DB=shared-memory \
SKILL_PGSCHEMA=sk_scope \
SKILL_VISITOR_ROLE=visitor_hermes \
python3 scripts/mem.py search "friction skill-system-comms" --all-scopes
複数 DB 間の可視性に関する契約
visibility=private(デフォルト):メモリが保存されている DB 内でのみ検索可能です。可視性のない従来の行はprivateとして読み取られますvisibility=shared:フェデレーションが明示的に有効な場合、設定されたメモリ DB 間で検索可能ですvisibility=global:設定されたメモリ DB 間で検索可能で、複数 DB 間の自動コンテキスト挿入の対象になります- 複数 DB 間の検索結果には
source_dbを含める必要があります - 複数 DB 間のランキングには、DB ごとのスコアをそのまま比較せず、正規化された統合方式(RRF 方式)を使用します
- 既知の DB の検索対象は、
config/insight.yamlのmemory.cross_db_targetsで設定します - 読み取り側の複数 DB 間フェデレーションが有効な場合も、すべての変更処理(
store、update、delete、purge)は、現在のSKILL_PGDATABASEターゲット内にとどまります
自動検出(推奨)
環境変数が設定されていない場合、プロジェクトディレクトリ名から DB 名が自動的に導出されます。
- プラグイン(JS):OpenCode ホストから渡される
directoryを使用 → パスの末尾のセグメント →<dir>-memory - mem.py CLI:スクリプトのルートディレクトリまたは cwd を使用 →
<dir>-memory - MCP サーバー:起動時の
Path.cwd()を使用 →<dir>-memory
**SKILL_PGDATABASE をグローバルに設定しないでください。**すべてのプロジェクトで自動検出が上書きされます。
# WRONG — breaks project isolation
export SKILL_PGDATABASE=skills-memory # every project now hits skills-memory
# RIGHT — let auto-detection work (no env var needed)
cd /path/to/FraudDetect && opencode # → FraudDetect-memory
cd /path/to/skills && opencode # → skills-memory
プロジェクトごとのオーバーライド(必要な場合)
オーバーライドする必要がある場合は、SKILL_PGDATABASE をグローバルではなくプロジェクトレベルで設定してください。
- プロジェクトの
.opencode設定または起動スクリプト内 - プロジェクトの
.envファイル内(ホストが読み込む場合) - コマンドのプレフィックスとして指定:
SKILL_PGDATABASE=FraudDetect-memory opencode
Fail-closed ポリシー
PGDATABASE が設定されていて SKILL_PGDATABASE が設定されていない場合、すべてのエントリーポイントで接続を拒否します。これにより、誤ってプロジェクト間でメモリが混在するのを防ぎます。
複数プロジェクトのセットアップでの MCP サーバーのパス
スキルを ~/.agents/skills/ にグローバルインストールした場合は、グローバルインストール先への絶対パスを MCP に設定してください。
{
"skill-system-memory": {
"command": "python3",
"args": ["~/.agents/skills/skill-system-memory/mcp/server.py"]
}
}
skills/skill-system-memory/mcp/server.py のような相対パスは使用しないでください。ローカルに skills/ ディレクトリがないプロジェクトでは動作しません。
クイックスタート
データベース <project>-memory とすべての関数は、このスキルディレクトリの init.sql によって作成されます。
現在サポートされているランタイムの機能範囲は、コアメモリ、型付きコンテキストの読み取り、型付き進化レジャー、doctor/圧縮のサポートです。
セッション/プロジェクト/コンテキストのプロジェクションテーブルと動作グラフの更新は、任意の機能ゲート付きの機能であり、無条件にランタイムで保証されるものではありません。
# Linux — replace 'postgres' with your PostgreSQL superuser if different (e.g. your system username)
psql -U postgres -c "CREATE DATABASE <project>-memory;"
psql -U postgres -d <project>-memory -f init.sql
# Windows (adjust path to your psql.exe; replace 'postgres' with your PG superuser if needed)
& "C:\Program Files\PostgreSQL\18\bin\psql.exe" -U postgres -c "CREATE DATABASE <project>-memory;"
& "C:\Program Files\PostgreSQL\18\bin\psql.exe" -U postgres -d <project>-memory -f init.sql
注:PostgreSQL のインストールに
postgresロールがない場合は、実際に使用している PostgreSQL のスーパーユーザー名を指定してください。多くの Linux ディストリビューションでは、OS のユーザー名と同じです。 スクリプトの実行前にPGUSERを設定すれば、いつでも上書きできます。export PGUSER=your_pg_username(Linux/macOS)または$env:PGUSER = "your_pg_username"(PowerShell)を実行してください。
確認方法:SELECT * FROM memory_health_check();
MCP サーバー(フェーズ 6.1)
このスキルには、メモリ操作をエージェント用ツールとして公開する MCP(Model Context Protocol)サーバーが含まれています。
MCP サーバーのセットアップ
# Install dependencies
cd skills/skill-system-memory/mcp
pip install -r requirements.txt
# Verify installation
python server.py --help
# Run with stdio transport (default)
python server.py
# Run with SSE transport (for remote access)
MCP_TRANSPORT=sse MCP_PORT=8000 python server.py
# Or via MCP CLI
mcp dev server.py
MCP 環境変数
| 変数 | デフォルト値 | 説明 |
|---|---|---|
SKILL_PGDATABASE | <project>-memory | プロジェクトごとのレガシーな PostgreSQL データベース名 |
SKILL_PGSHARED_DB | (未設定) | search_path モードで使用する共有 PostgreSQL データベース名 |
SKILL_PGSCHEMA | (未設定) | search_path モードで使用するローカル書き込み可能スキーマ |
PGHOST | localhost | PostgreSQL ホスト |
PGPORT | 5432 | PostgreSQL ポート |
PGUSER | (任意) | PostgreSQL ユーザー |
MCP_TRANSPORT | stdio | トランスポートモード(stdio または sse) |
MCP_PORT | 8000 | SSE トランスポート用ポート |
MCP ツール
| ツール | 説明 |
|---|---|
memory_search | 自然言語のクエリでメモリを検索します(ハイブリッド:FTS + trigram + pgvector) |
memory_store | 自動重複排除とローカルのみへの書き込み分離を行い、新しいメモリを保存します |
memory_update | 監査ログを記録しながら、ID で指定したローカルメモリ行の選択したフィールドを更新します |
memory_delete | 監査ログを記録しながら、ID で指定したローカルメモリ行を論理削除します |
memory_purge | 明示的な許可がある場合に限り、ローカルメモリ行を完全に削除します |
memory_auto_match | 入力テキストにメモリを自動照合し、.sisyphus/tmp/mem-{session}.md に書き込みます |
memory_context | ユーザーコンテキスト(状態、設定、最近のファセット)を取得します |
memory_status | メモリシステムの健全性(接続、スキーマ、pgvector)を確認します |
ingest-close-reports | inbox のクローズレポートを解析し、構造化されたエピソード記憶の候補または書き込みに変換します |
backfill-embeddings | pgvector の修復後、既存メモリの不足しているベクトル埋め込みをバックフィルします |
myelin_search | インテント/コンテキストでミエリン・アフォーダンスレジストリを検索し、上位 k 件のラッパー/反射のみを返します |
myelin_get | 1 件のアフォーダンスレコードを完全なメタデータ付きで取得します |
myelin_validate | 引数とガードルールに照らして、1 件のアフォーダンスを検証します |
debug_diagnose | 統合 MCP サーバーを介してデバッグツールによる診断を実行します |
eda_profile | 統合 MCP サーバーを介して EDA データセットのプロファイリングを実行します |
gate_validate | 統合 MCP サーバーを介してゲート検証を実行します |
memory_rebuild | 圧縮またはメモリ喪失後に、エージェントのコンテキスト全体を再構築します |
MCP リソース
| リソース | 説明 |
|---|---|
memory://schema | メモリデータベースのスキーマ情報 |
memory://status | 現在のメモリシステムのステータス |
MCP エージェントとの統合
エージェントで MCP サーバーを使用するには、次の内容を含むようにエージェントの MCP 設定を構成してください。
{
"mcpServers": {
"skill-system": {
"command": "python",
"args": ["skills/skill-system-memory/mcp/server.py"],
"env": {
"SKILL_PGDATABASE": "<project>-memory"
}
}
}
}
共有 DB を使用する MCP の例:
{
"mcpServers": {
"skill-system": {
"command": "python",
"args": ["skills/skill-system-memory/mcp/server.py"],
"env": {
"SKILL_PGSHARED_DB": "shared-memory",
"SKILL_PGSCHEMA": "sk_scope",
"SKILL_VISITOR_ROLE": "visitor_sk_coder"
}
}
}
}
MCP ツールの例
# Search memories
mcp_tool: memory_search
args: { "query": "pgvector installation", "limit": 5 }
# Search memories with full content for the returned top-k rows
mcp_tool: memory_search
args: { "query": "pgvector installation", "limit": 5, "mode": "full" }
# Explicit cross-DB search
mcp_tool: memory_search
args: { "query": "reviewer feedback", "cross_db": true, "limit": 5 }
# Hermes all-scopes override in shared-DB mode
mcp_tool: memory_search
args: { "query": "cross-project audit", "all_scopes": true, "limit": 10 }
# Store a memory
mcp_tool: memory_store
args: { "type": "semantic", "category": "troubleshooting", "title": "Fixed pgvector on Windows", "content": "Build steps...", "importance": 8 }
# Update a memory locally
mcp_tool: memory_update
args: { "id": 42, "fields": { "title": "Updated title", "visibility": "shared" } }
# Soft-delete a memory locally
mcp_tool: memory_delete
args: { "id": 42 }
# Hard-delete a memory locally only with explicit authorization
mcp_tool: memory_purge
args: { "id": 42, "hard": true, "authorized": true }
# Auto-match memories (KEY TOOL for near-automatic surfacing)
mcp_tool: memory_auto_match
args: { "text": "I'm seeing an error with database connections", "threshold": 0.8, "limit": 5 }
# Auto-match without hiding low-score candidates
mcp_tool: memory_auto_match
args: { "text": "I'm seeing an error with database connections", "threshold": 0.8, "include_below_threshold": true, "limit": 5, "mode": "full" }
# Get user context
mcp_tool: memory_context
args: { "user": "default" }
# Check system health
mcp_tool: memory_status
args: {}
既存のインストールでは、次も実行してください。
psql -U postgres -d <project>-memory -v ON_ERROR_STOP=1 -f migrate-v2-postgres-first.sql
純粋なスキルモード(デフォルト)
このスキルは、プラグインをインストールしなくても動作します。純粋なスキルモードでは:
- 必要に応じてスクリプトを手動で実行します(段階的な情報開示)
- OpenCode のグローバル設定は自動的に変更されません
オプションのブートストラップ(選択を確認・記録し、インストールを試行)
注意事項:
- 対話モードでは、負荷の高いオプションコンポーネントはデフォルトでインストールされません。
- すべてをインストールする準備ができた場合にのみ、
-InstallAll/--install-allを使用してください。
ブートストラップスクリプトを実行して、オプションコンポーネント(pgpass、ローカル埋め込み、pgvector)を選択し、その選択内容を記録します。
ブートストラップでは、OpenCode の圧縮ログ記録プラグインもオプションでインストールできます(プラグインを OpenCode のプラグインディレクトリにコピーします)。
Windows:
# run from the skill directory
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "scripts\bootstrap.ps1"
Linux/macOS:
# run from the skill directory
bash "scripts/bootstrap.sh"
選択内容の記録は次の場所に保存されます。
~/.config/opencode/skill-system-memory/setup.json
エージェントルール:
- このファイルが存在しない場合は、オプションコンポーネントを有効にするかユーザーに確認してください。
- 推奨:すべてのオプションを有効にしてブートストラップを実行し、報告された失敗を修正してください。
ランタイム機能モデル
現在のライブ機能分類は、意図的に対象を絞っています。
| 機能 | 現在の状態 | 現在のサポート範囲 |
|---|---|---|
core_memory | SUPPORTED_NOW | agent_memories と store_memory、search_memories、memory_health_check |
evolution_ledger | SUPPORTED_NOW | evolution_snapshots と insert_evolution_snapshot、get_evolution_history |
compaction_logging | リポジトリのプラグインが同期されている場合は SUPPORTED_NOW | ローカルの JSONL 圧縮ログと、ガード付きの store_memory(...) 書き戻し |
typed_context_reads | SUPPORTED_NOW | get_agent_context、get_soul_state、get_recent_facets、get_user_preferences |
runtime_sync_projections | GATED_OPTIONAL | 該当するテーブルが存在する場合に限り、session_summaries、project_summaries、context_rollups |
behavior_refresh_graph | GATED_OPTIONAL | 該当するテーブルが存在する場合に限り、behavior_* の更新 |
control_plane_refresh | DEFERRED_UNSUPPORTED | 現在のユーザー向けメモリランタイムには含まれません |
永続的な進化提案モデルが存在する場合、doctor は次も報告します。
- 正規の承認済みストア:
evolution_nodes - 正規の却下済みストア:
evolution_rejections - 正規のタスク実体化:
evolution_tasks -> agent_tasks agent_memoriesの役割:明示的なレガシー互換行を含む、検索可能な要約およびバックリファレンスの範囲- 承認/却下パスの状態:CLI 境界でトランザクション安全
- マイグレーション/バックフィルの冪等性:再実行しても安全
- 決定のリプレイ状態:
proposal_idによるリプレイ冪等性 - 調整メカニズム:提案単位のアドバイザリロックと、正規の承認済み/却下済み行に対するセマンティックフィンガープリント
- ペイロード不一致ポリシー:変更なしでブロック
- 競合する終端状態のポリシー:変更なしでブロック
- タスク権限モデル:
agent_tasksがライフサイクルの権限を持ち、evolution_tasksはマッピングのみ
この状態では、提案の永続化に関して evolution_snapshots は LEGACY_COMPAT_SURFACE として扱われます。一方、スナップショット/バージョン履歴については引き続き有効です。
Windows では、pgvector のインストールに公式の pgvector 手順(Visual Studio C++ + nmake /F Makefile.win)を使用します。ブートストラップでは、winget を使って前提条件のインストールを試みます。
オプションの自動化:コンパクションのログ記録(OpenCode プラグイン)
コンパクションのログを自動的に記録する場合は、このスキルに同梱されている OpenCode プラグインのテンプレートをインストールします。
オプション A(推奨):bootstrap を実行し、プラグインのオプションを選択します。
plugins/skill-system-memory.jsとplugins/runtime_sync.jsを~/.config/opencode/plugins/にコピーします- OpenCode を再起動します
安全対策/ロールバック(OpenCode の起動時に停止してしまう場合):
~/.config/opencode/plugins/skill-system-memory.jsを削除または名前変更します~/.config/opencode/plugins/runtime_sync.jsを削除または名前変更します- OpenCode を再起動します
- ログを確認します:
- macOS/Linux:
~/.local/share/opencode/log/ - Windows:
%USERPROFILE%\.local\share\opencode\log
- macOS/Linux:
プラグインの動作に関する注意事項:
- このプラグインは、bootstrap で明示的に有効にしない限り何もしないよう設計されています(
setup.jsonでselected.opencode_plugin=trueが設定されます)。 - Postgres への書き込みを試みるのは、
selected.pgpass=trueの場合のみです(認証プロンプトによる停止を回避します)。 - コンパクション時には、ローカルの JSONL ログ記録と、DB の接続先が有効な場合のコア
store_memory(...)パスを常に利用できます。 - ランタイム投影の upsert(
session_summaries、project_summaries、context_rollups)は機能の有無に応じて実行されます。これらのテーブルがない場合、プラグインは書き込みを試みず、その理由を明示してスキップします。 behavior_*テーブルへの行動グラフの更新も機能の有無に応じて実行され、必要なテーブルがない場合は明示的にスキップされます。
アンインストール:
~/.config/opencode/plugins/skill-system-memory.jsを削除します~/.config/opencode/plugins/runtime_sync.jsを削除します- OpenCode を再起動します
認証情報(psql)
スクリプト、スキルのドキュメント、設定ファイルにパスワードをハードコードしないでください。
非対話型の psql には、次のオプションを推奨します。
.pgpass/pgpass.conf(推奨)- Linux/macOS:
~/.pgpass(chmod 0600 ~/.pgpassを実行する必要があります。そうしないと libpq に無視されます) - Windows:
%APPDATA%\postgresql\pgpass.conf(例:C:\Users\<you>\AppData\Roaming\postgresql\pgpass.conf) - 形式:
hostname:port:database:username:password - ドキュメント:https://www.postgresql.org/docs/current/libpq-pgpass.html
- Linux/macOS:
PGPASSFILE(任意の上書き):パスワードファイルのカスタムの場所を指定しますPGPASSWORD(非推奨):ローカルでの簡単なテストにのみ使用します。環境変数が一部のシステムで漏えいする可能性があります
ヒント:接続のデフォルトを(シェルごとに)一度設定すると、コマンドを短縮できます。
export PGHOST=localhost
export PGPORT=5432
export SKILL_PGDATABASE=<project>-memory
export PGUSER=postgres # change to your PG superuser if postgres role does not exist
シェルへのコピー&ペースト時の安全性:
- インラインの Markdown バッククォート(例:
semantic)をシェルにコピーしないでください。zsh ではバッククォートはコマンド置換として扱われます。 - ラッパースクリプト(
scripts/mem.sh、scripts/mem.ps1)を使用するか、フェンス付きコードブロックからコピーしてください。
一度限りのセットアップ用ヘルパースクリプト
このスキルには、次のヘルパースクリプト(相対パス)が同梱されています。
scripts/setup-pgpass.ps1scripts/setup-pgpass.sh
OpenCode での使用方法:スキルのディレクトリから実行します。
Windows での実行:
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "scripts\setup-pgpass.ps1"
Linux/macOS での実行:
bash "scripts/setup-pgpass.sh"
メモリの種類
| 種類 | 有効期間 | 使用する場面 |
|---|---|---|
working | 24時間後に自動期限切れ | 現在の会話のコンテキスト(session_id が必要) |
episodic | 永続+減衰 | 問題解決の経験、デバッグセッション |
semantic | 永続 | 抽出された事実、知識、パターン |
procedural | 永続 | 手順ごとの手順、チェックリスト(重要度 >= 7) |
コア関数
store_memory(type, category, tags[], title, content, metadata, agent_id, session_id, importance)
コンテンツハッシュに基づいて重複を自動排除します。重複する挿入があると、access_count と importance_score が増加します。
SELECT store_memory(
'semantic',
'windows-networking',
ARRAY['ssh', 'tunnel', 'port-conflict'],
'SSH Tunnel Port Conflict Resolution',
'Fix: 1) taskkill /F /IM ssh.exe 2) Use processId not pid 3) Wait 3s',
'{"os": "Windows 11"}',
'sisyphus',
NULL,
9.0
);
ラッパー:scripts/mem.py(推奨 — パラメーター化クエリで、引用符の問題がありません)
要件:
pip install psycopg2-binary
# DB 連線狀態 + 記憶總數
python3 scripts/mem.py status
# 搜尋記憶(含特殊字元也安全)
python3 scripts/mem.py search "pgvector windows install" --limit 5
python3 scripts/mem.py search "pgvector windows install" --limit 5 --mode full
python3 scripts/mem.py search "fraud features" --scope project --limit 10
python3 scripts/mem.py search "reviewer feedback" --cross-db --limit 10
python3 scripts/mem.py search "shared debugging notes" --scope all --limit 10
# 跨 5 維度診斷搜尋 (B-015 TKT-001)
python3 scripts/mem.py search "alert file" --diagnostic --limit 10
# Tag 前綴自動展開 (B-015 TKT-003)
python3 scripts/mem.py search "root-cause" --auto-expand
# 儲存記憶(--content flag)
python3 scripts/mem.py store --type semantic --category project --title "pgvector install" --tags "postgres,pgvector,windows" --importance 8 --scope project --content "Steps: ..."
python3 scripts/mem.py store --type semantic --category feedback --title "Reviewer note" --visibility shared --content "Cross-DB searchable note"
python3 scripts/mem.py update 42 --field title="Updated note" --field visibility=shared
python3 scripts/mem.py delete 42
python3 scripts/mem.py purge 42 --hard --authorized
# 儲存記憶(stdin)
printf '%s' "Steps: ..." | python3 scripts/mem.py store semantic project "pgvector install" "postgres,pgvector,windows" 8 --scope session
# 列出 / 匯出 / 壓縮
python3 scripts/mem.py list --scope project --limit 20
python3 scripts/mem.py export --format json --scope global
python3 scripts/mem.py compact --scope project
# session 開頭自動撈出相關記憶
python3 scripts/mem.py context "pgvector ssh tunnel"
# 列出所有已使用的 tags / categories
python3 scripts/mem.py tags
python3 scripts/mem.py categories
# DB 不可用時,將 pending fallback 寫回 DB
python3 scripts/mem.py flush
# 保守升級 visibility(只影響本地 DB)
python3 scripts/mem.py visibility-upgrade --visibility shared --category feedback --dry-run
python3 scripts/mem.py visibility-upgrade --visibility global --tags reviewer,decision
フォールバックの動作:
- DB への接続に失敗した場合、
storeは.memory/pending/*.jsonへの書き込みに切り替わり、search/contextはローカルの pending ファイルを読み込み、警告を出力します list/exportも pending のフォールバックから読み込みます。DB が利用できない場合、compactは警告を出力するだけで、クラッシュしません- DB に接続できても memory スキーマがない場合、
storeは警告を出して何もせず、search/context/tags/categoriesは警告とともに空の結果を返します - DB が復旧すると、
flushは.memory/pending/の内容を PostgreSQL に書き戻します
スコープモデル:
session(デフォルト):metadata.scope=sessionとして記録し、可能な場合はsession_idも付与しますproject:metadata.scope=project+metadata.project_id=<repo>として記録しますglobal:metadata.scope=globalとして記録します。DB をまたいで検索するには、明示的なフェデレーション読み取りが引き続き必要ですsearch/list/exportに--scopeを指定しない場合、すべてのスコープが返され、結果にソーススコープが示されます
可視性はスコープとは別のものです:
private(デフォルト):ローカル DB のみshared:明示的な DB 横断検索の対象になりますglobal:明示的な DB 横断検索と、自動コンテキスト注入の対象になります
変更監査ルール:
updateは選択されたフィールドの変更のみを、ローカル DB に書き込みますdeleteは論理削除のみを行い(deleted_at)、後方互換性のある読み取りを維持しますpurgeは物理削除であり、明示的な認可が必要です- すべての変更操作で、変更前後の値と実行者のメタデータを含む
memory_audit行が書き込まれます
CLI の変更操作の例:
python3 scripts/mem.py update 42 --field title="Updated note" --field visibility=shared
python3 scripts/mem.py delete 42
python3 scripts/mem.py purge 42 --hard --authorized
memory_audit は、これらの操作における正式な変更履歴です。各行には以下が記録されます:
memory_idaction(update、delete、purge)old_valuenew_valueactor_idsession_idchanged_at
警告:purge は破壊的な操作であり、論理削除からの復旧を迂回します。ローカルのみに適用され、明示的な認可フラグが必要です。定期的なクリーンアップには使用しないでください。
既知のフェデレーション読み取り先は config/insight.yaml で設定します:
memory:
cross_db_targets:
- Work-memory
- skills-memory
- ExperimentPipeline-memory
- FraudDetect-memory
cross_db_context_visibility:
- global
このリストは、明示的な読み取りのファンアウトのみを制御します。呼び出し元が target_db 形式のデータを渡しても、書き込み先は引き続きローカルの SKILL_PGDATABASE データベースです。
ラッパー:scripts/mem.sh / scripts/mem.ps1(シェルのフォールバック)
# 連線狀態
bash "scripts/mem.sh" status
# 搜尋
bash "scripts/mem.sh" search "pgvector windows install" 5
# 儲存 (content via stdin)
printf '%s' "Steps: ..." | bash "scripts/mem.sh" store semantic project "pgvector install" "postgres,pgvector,windows" 8
# 列出 tags / categories
bash "scripts/mem.sh" tags
bash "scripts/mem.sh" categories
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "scripts\mem.ps1" types
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "scripts\mem.ps1" search "pgvector windows install" 5
"Steps: ..." | powershell.exe -NoProfile -ExecutionPolicy Bypass -File "scripts\mem.ps1" store semantic project "pgvector install" "postgres,pgvector,windows" 8
Router との統合(任意)
固定されたパイプラインを実行する Router スキルを使用する場合、SKILL.md に埋め込まれたマニフェストを読み取ることができます。
移植性を確保するため、マニフェストブロックは YAML としてフェンスされていますが、内容は JSON です(有効な YAML です)。Router はこれを解析します。
{
"schema_version": "2.0",
"id": "skill-system-memory",
"version": "1.0.0",
"capabilities": ["memory-search", "memory-search-cross-db", "memory-role-scope", "memory-store", "memory-update", "memory-delete", "memory-purge", "memory-visibility-upgrade", "memory-list", "memory-compact", "memory-export", "memory-export-md", "memory-flush", "memory-mirror-capture", "memory-reconcile-note-live", "memory-ingest-close-reports", "memory-backfill-embeddings", "myelin-search", "myelin-get", "myelin-validate", "memory-health", "memory-types", "memory-auto-write", "memory-doctor", "plugin-debug", "plugin-eda", "plugin-gate", "memory-rebuild"],
"effects": ["proc.exec", "db.read", "db.write"],
"operations": {
"search": {
"description": "Search memories by natural language query. Returns ranked results with relevance scores.",
"input": {
"query": { "type": "string", "required": true, "description": "Natural language search query" },
"limit": { "type": "integer", "required": false, "default": 5, "description": "Max results" },
"scope": { "type": "string", "required": false, "description": "global | project | session filter; all enables explicit cross-DB federation" },
"cross_db": { "type": "boolean", "required": false, "description": "Explicitly fan out reads across configured memory DBs" },
"all_scopes": { "type": "boolean", "required": false, "description": "Hermes/admin override to bypass visitor search_path scoping for cross-project audit" }
},
"output": {
"description": "Array of memory matches with local scope labels and cross-DB source attribution when federation is enabled",
"fields": { "status": "ok | error", "data": "array of {id, title, content, relevance_score, scope, source_db?}" }
},
"entrypoints": {
"unix": ["bash", "scripts/router_mem.sh", "search", "{query}", "{limit}"],
"windows": ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts\\router_mem.ps1", "search", "{query}", "{limit}"]
}
},
"store": {
"description": "Store a new memory. Auto-deduplicates by content hash and always writes to the local memory DB.",
"input": {
"memory_type": { "type": "string", "required": true, "description": "One of: semantic, episodic, procedural, working" },
"category": { "type": "string", "required": true, "description": "Category name" },
"title": { "type": "string", "required": true, "description": "One-line summary" },
"tags_csv": { "type": "string", "required": true, "description": "Comma-separated tags" },
"importance": { "type": "integer", "required": true, "description": "1-10 importance score" },
"scope": { "type": "string", "required": false, "description": "global | project | session" },
"visibility": { "type": "string", "required": false, "description": "private | shared | global" }
},
"output": {
"description": "Confirmation with stored memory id",
"fields": { "status": "ok | error", "id": "integer" }
},
"entrypoints": {
"unix": ["bash", "scripts/router_mem.sh", "store", "{memory_type}", "{category}", "{title}", "{tags_csv}", "{importance}"],
"windows": ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts\\router_mem.ps1", "store", "{memory_type}", "{category}", "{title}", "{tags_csv}", "{importance}"]
}
},
"update": {
"description": "Update selected fields of a local memory row by id with audit logging.",
"input": {
"id": { "type": "integer", "required": true },
"fields": { "type": "object", "required": true }
},
"output": {
"description": "Update summary",
"fields": { "status": "ok | error", "id": "integer", "updated_fields": "array" }
},
"entrypoints": {
"unix": ["python3", "scripts/mem.py", "update"],
"windows": ["python", "scripts/mem.py", "update"]
}
},
"delete": {
"description": "Soft-delete a local memory row by id with audit logging.",
"input": {
"id": { "type": "integer", "required": true }
},
"output": {
"description": "Soft-delete summary",
"fields": { "status": "ok | error", "id": "integer", "deleted_at": "string" }
},
"entrypoints": {
"unix": ["python3", "scripts/mem.py", "delete"],
"windows": ["python", "scripts/mem.py", "delete"]
}
},
"purge": {
"description": "Hard-delete a local memory row only with explicit authorization.",
"input": {
"id": { "type": "integer", "required": true },
"hard": { "type": "boolean", "required": true },
"authorized": { "type": "boolean", "required": true }
},
"output": {
"description": "Hard-delete summary",
"fields": { "status": "ok | error", "id": "integer", "purged": "boolean" }
},
"entrypoints": {
"unix": ["python3", "scripts/mem.py", "purge"],
"windows": ["python", "scripts/mem.py", "purge"]
}
},
"list": {
"description": "List memories with optional scope/category filters.",
"input": {
"scope": { "type": "string", "required": false },
"category": { "type": "string", "required": false },
"limit": { "type": "integer", "required": false, "default": 20 }
},
"output": {
"description": "Memory listing with scope labels",
"fields": { "status": "ok | error", "results": "array" }
},
"entrypoints": {
"unix": ["python3", "scripts/mem.py", "list"],
"windows": ["python", "scripts/mem.py", "list"]
}
},
"compact": {
"description": "Compact duplicate memories within an optional scope.",
"input": {
"scope": { "type": "string", "required": false }
},
"output": {
"description": "Compaction result",
"fields": { "status": "ok | warn | error", "compacted_count": "integer" }
},
"entrypoints": {
"unix": ["python3", "scripts/mem.py", "compact"],
"windows": ["python", "scripts/mem.py", "compact"]
}
},
"export": {
"description": "Export memories in json or csv format.",
"input": {
"format": { "type": "string", "required": false },
"scope": { "type": "string", "required": false },
"limit": { "type": "integer", "required": false, "default": 1000 }
},
"output": {
"description": "Export payload",
"fields": { "status": "ok | error", "results": "array|string" }
},
"entrypoints": {
"unix": ["python3", "scripts/mem.py", "export"],
"windows": ["python", "scripts/mem.py", "export"]
}
},
"export-md": {
"description": "Export DB-only memories to markdown files that memory_sync can re-import.",
"input": {
"folder": { "type": "string", "required": true, "description": "Target folder for markdown exports" }
},
"output": {
"description": "Markdown export result",
"fields": { "status": "ok | error", "created": "integer", "skipped": "integer", "folder": "string" }
},
"entrypoints": {
"agent": "Use the memory_export MCP tool from skills/skill-system-memory/mcp/server.py"
}
},
"visibility-upgrade": {
"description": "Batch-upgrade local memory visibility conservatively by category and/or tag selectors.",
"input": {
"visibility": { "type": "string", "required": true, "description": "shared | global | private" },
"category": { "type": "string", "required": false },
"tags": { "type": "string", "required": false },
"dry_run": { "type": "boolean", "required": false, "default": false }
},
"output": {
"description": "Upgrade summary",
"fields": { "status": "ok | error", "matched": "integer", "updated": "integer" }
},
"entrypoints": {
"unix": ["python3", "scripts/mem.py", "visibility-upgrade"],
"windows": ["python", "scripts/mem.py", "visibility-upgrade"]
}
},
"flush": {
"description": "Flush local pending fallback files into PostgreSQL when the DB is back.",
"input": {},
"output": {
"description": "Confirmation that pending fallback files were replayed",
"fields": { "status": "ok | warn | error", "flushed_count": "integer" }
},
"entrypoints": {
"unix": ["python3", "scripts/mem.py", "flush"],
"windows": ["python", "scripts/mem.py", "flush"]
}
},
"mirror-capture": {
"description": "Mirror changed decision-critical file sections into the selected project memory DB with fail-open behavior.",
"input": {
"file": { "type": "string", "required": true, "description": "Changed file path" },
"content": { "type": "string", "required": false, "description": "New file content" },
"content_file": { "type": "string", "required": false, "description": "Path containing new file content" },
"old_content": { "type": "string", "required": false, "description": "Previous file content" },
"old_content_file": { "type": "string", "required": false, "description": "Path containing previous file content" },
"config": { "type": "string", "required": false, "description": "Whitelist config path" },
"pattern": { "type": "string", "required": false, "description": "Additional whitelist glob pattern" },
"work_root": { "type": "string", "required": false, "description": "Optional root for relative whitelist matching" },
"db_target": { "type": "string", "required": false, "description": "Explicit project memory DB target" },
"log_path": { "type": "string", "required": false, "description": "Caller-configurable JSONL log path" },
"pane": { "type": "string", "required": false, "description": "Origin pane/session metadata" },
"dry_run": { "type": "boolean", "required": false, "default": false }
},
"output": {
"description": "Mirror result with changed sections, store ids, and fail-open warnings",
"fields": { "status": "ok | warn | error", "sections": "array", "store_ids": "array", "errors": "array" }
},
"entrypoints": {
"unix": ["python3", "scripts/memory_mirror.py", "capture"],
"windows": ["python", "scripts/memory_mirror.py", "capture"]
}
},
"reconcile-note-live": {
"description": "Reconcile live note decisions against memory backrefs before compact or close flows.",
"input": {
"note_file": { "type": "string", "required": true, "description": "Path to note_live style markdown" },
"db_target": { "type": "string", "required": false, "description": "Explicit project memory DB target" },
"log_path": { "type": "string", "required": false, "description": "Caller-configurable JSONL log path" },
"pane": { "type": "string", "required": false, "description": "Origin pane/session metadata" },
"dry_run": { "type": "boolean", "required": false, "default": false },
"strict": { "type": "boolean", "required": false, "default": false },
"store_missing": { "type": "boolean", "required": false, "default": true }
},
"output": {
"description": "Reconcile result including checked titles, missing backrefs, and auto-store ids",
"fields": { "status": "ok | warn | error", "checked_titles": "array", "missing_titles": "array", "store_ids": "array" }
},
"entrypoints": {
"unix": ["python3", "scripts/memory_mirror.py", "reconcile"],
"windows": ["python", "scripts/memory_mirror.py", "reconcile"]
}
},
"ingest-close-reports": {
"description": "Parse milestone close reports from inbox markdown and ingest them into episodic memory with dedup.",
"input": {
"inbox": { "type": "string", "required": true, "description": "Path to inbox markdown file" },
"dry_run": { "type": "boolean", "required": false, "default": false },
"limit": { "type": "integer", "required": false }
},
"output": {
"description": "Structured candidates, stored ids, and dedup skips",
"fields": { "status": "ok | error", "candidate_count": "integer", "candidates": "array", "stored_ids": "array", "skipped": "array" }
},
"entrypoints": {
"unix": ["python3", "scripts/mem.py", "ingest-close-reports"],
"windows": ["python", "scripts/mem.py", "ingest-close-reports"]
}
},
"backfill-embeddings": {
"description": "Backfill missing vector embeddings for existing memories after pgvector repair.",
"input": {
"limit": { "type": "integer", "required": false, "default": 50 },
"model": { "type": "string", "required": false }
},
"output": {
"description": "Updated ids, skipped ids, and provider/model summary",
"fields": { "status": "ok | error", "updated_count": "integer", "updated_ids": "array", "skipped": "array" }
},
"entrypoints": {
"unix": ["python3", "scripts/mem.py", "backfill-embeddings"],
"windows": ["python", "scripts/mem.py", "backfill-embeddings"]
}
},
"myelin-search": {
"description": "Search the myelin affordance registry by intent/context and return top-k relevant wrappers/reflexes.",
"input": {
"intent": { "type": "string", "required": true, "description": "Intent label such as dispatch, inbox, or EP-status" },
"context": { "type": "string", "required": false, "description": "Free text or JSON context payload" },
"limit": { "type": "integer", "required": false, "default": 5 }
},
"output": {
"description": "Ranked affordance results with guard warnings and bridge metadata",
"fields": { "status": "ok | error", "results": "array", "warnings": "array", "bridge_contract": "object" }
},
"entrypoints": {
"unix": ["python3", "scripts/myelin_registry.py", "search", "{intent}"],
"windows": ["python", "scripts/myelin_registry.py", "search", "{intent}"]
}
},
"myelin-get": {
"description": "Get one affordance record with full metadata.",
"input": {
"id": { "type": "string", "required": true, "description": "Affordance identifier" }
},
"output": {
"description": "Affordance record",
"fields": { "status": "ok | error", "record": "object" }
},
"entrypoints": {
"unix": ["python3", "scripts/myelin_registry.py", "get", "{id}"],
"windows": ["python", "scripts/myelin_registry.py", "get", "{id}"]
}
},
"myelin-validate": {
"description": "Validate one affordance against args and guard raw-shell fallbacks.",
"input": {
"id": { "type": "string", "required": true },
"args": { "type": "string", "required": false, "description": "JSON args/context payload" }
},
"output": {
"description": "Validation result",
"fields": { "status": "ok | error", "valid": "boolean", "warnings": "array", "missing_required_context": "array" }
},
"entrypoints": {
"unix": ["python3", "scripts/myelin_registry.py", "validate", "{id}"],
"windows": ["python", "scripts/myelin_registry.py", "validate", "{id}"]
}
},
"health": {
"description": "Check memory system health: total count, average importance, stale count.",
"input": {},
"output": {
"description": "Health metrics",
"fields": { "status": "ok | error", "data": "array of {metric, value, status}" }
},
"entrypoints": {
"unix": ["bash", "scripts/router_mem.sh", "health"],
"windows": ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts\\router_mem.ps1", "health"]
}
},
"types": {
"description": "List available memory types and their descriptions.",
"input": {},
"output": {
"description": "Memory type definitions",
"fields": { "status": "ok | error", "data": "array of {type, lifespan, description}" }
},
"entrypoints": {
"unix": ["bash", "scripts/router_mem.sh", "types"],
"windows": ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts\\router_mem.ps1", "types"]
}
},
"auto-write": {
"description": "Procedure template for automatically storing a memory after solving a non-obvious problem.",
"input": {},
"output": {
"description": "Proposed memory fields to store",
"fields": {"memory_type": "string", "category": "string", "title": "string", "tags_csv": "string", "importance": "integer", "content": "string"}
},
"entrypoints": {
"agent": "Follow scripts/auto-write-template.md"
}
},
"doctor": {
"description": "Report the current runtime capability map, memory plugin drift, memory DB target, OMO resolution, canonical evolution stores, table/routine readiness, and evolution ledger status.",
"input": {},
"output": {
"description": "Doctor report for the current runtime state",
"fields": {"status": "ok | warn | error", "doctor_report": "object"}
},
"entrypoints": {
"unix": ["python3", "scripts/runtime_doctor.py", "--format", "json"],
"windows": ["python", "scripts/runtime_doctor.py", "--format", "json"]
}
},
"debug-diagnose": {
"description": "Expose skill-system-debug diagnose through the unified MCP server.",
"input": {
"symptom": { "type": "string", "required": true },
"context": { "type": "string", "required": false }
},
"output": {
"description": "Structured diagnosis payload",
"fields": { "status": "ok | error", "result": "object" }
},
"entrypoints": {
"agent": "Use the debug_diagnose MCP tool from skills/skill-system-memory/mcp/server.py"
}
},
"eda-profile": {
"description": "Expose skill-system-eda dataset profiling through the unified MCP server.",
"input": {
"input_path": { "type": "string", "required": true },
"sample": { "type": "integer", "required": false },
"target": { "type": "string", "required": false }
},
"output": {
"description": "EDA profile output",
"fields": { "status": "ok | error", "profile_path": "string", "report_path": "string" }
},
"entrypoints": {
"agent": "Use the eda_profile MCP tool from skills/skill-system-memory/mcp/server.py"
}
},
"gate-validate": {
"description": "Expose skill-system-gate validation through the unified MCP server.",
"input": {
"rules": { "type": "string", "required": false },
"artifact_root": { "type": "string", "required": false }
},
"output": {
"description": "Gate validation summary",
"fields": { "status": "ok | error", "passed": "boolean", "results": "array" }
},
"entrypoints": {
"agent": "Use the gate_validate MCP tool from skills/skill-system-memory/mcp/server.py"
}
},
"rebuild": {
"description": "Rebuild full agent context after compact or memory loss.",
"input": {
"user": { "type": "string", "required": false },
"recent_limit": { "type": "integer", "required": false }
},
"output": {
"description": "Soul, preferences, recent memories, and pending decisions",
"fields": { "status": "ok | error", "rebuild_context": "object" }
},
"entrypoints": {
"agent": "Use the memory_rebuild MCP tool from skills/skill-system-memory/mcp/server.py"
}
}
},
"stdout_contract": {
"last_line_json": true
},
"mcp": {
"server": {
"name": "skill-system",
"description": "Unified skill-system MCP server exposing memory, myelin, debug, eda, gate, and memory_rebuild tools",
"entrypoint": "python skills/skill-system-memory/mcp/server.py",
"transport": "stdio",
"tools": ["memory_search", "memory_store", "memory_auto_match", "memory_context", "memory_status", "memory_sync", "memory_export", "myelin_search", "myelin_get", "myelin_validate", "debug_diagnose", "eda_profile", "gate_validate", "memory_rebuild"],
"resources": ["memory://schema", "memory://status"]
}
}
}
注:
- Router は各ステップが 最終行に JSON を出力することを想定しています。
- 既存のワークフローを壊さないよう、これらの Router アダプタースクリプトは
mem.sh/mem.ps1とは別になっています。
Memory Mirror Engine(SK-005)
scripts/memory_mirror.py は、メモリの自動ミラーリングとコンパクション前の調整を行う、SK 管理のフェイルオープンエンジンです。
python3 scripts/memory_mirror.py capture --file Work/note/note_live.md --content-file /tmp/new.md --old-content-file /tmp/old.md --db-target Work-memory --log-path Work/.tkt/memory-mirror.log
python3 scripts/memory_mirror.py reconcile --note-file Work/note/note_live.md --db-target Work-memory --log-path Work/.tkt/memory-mirror.log
- デフォルトのホワイトリストは
memory-mirror-config.yamlにあります - Work 管理のラッパーでは、
--db-target Work-memoryを明示的に指定してください - 構造化ログの出力は JSONL で、呼び出し元が設定できます
- 判定ログのトランザクション強化に関する契約は
memory-mirror-contract.mdに記載されています
Close Report の取り込み
./sk mem ingest-close-reports --inbox /share/nas165/arthur0824hao/Work/.tkt/inbox/hermes/inbox.md --dry-run
./sk mem ingest-close-reports --inbox /share/nas165/arthur0824hao/Work/.tkt/inbox/hermes/inbox.md
- 目的:マイルストーンの完了/ブロッカー報告を、検索可能なエピソード記憶に変換します
- 重複排除:バンドル ID + 実行者 + タイムスタンプ + 報告ステータスの取り込みキー
- 運用手順書:
close-report-ingestion-runbook.md
ベクター/エンベディングの健全性
memory_status は、セマンティック/ベクター検索を、機能の有効性に応じて任意の健全性項目として扱うようになりました:
pgvector_enablement_status:enabled | disabled | unavailable-on-hostpgvector_blocker:利用できない場合の、ホスト/インストールに関する具体的なブロッカーembedding_dependency_installed:ローカルのエンベディング実行環境が存在するかどうかsemantic_search_mode:hybrid-ready | hybrid-schema-no-vectors | vector-installable-but-disabled | fts-trgm-only
pgvector または sentence-transformers がない場合、FTS + pg_trgm のフォールバックが、引き続きデフォルトの安全な経路です。
セマンティック検索の修復コマンド
SKILL_PGDATABASE=Work-memory python3 scripts/mem.py backfill-embeddings --limit 100
SKILL_PGDATABASE=Work-memory python3 scripts/semantic_smoke.py --db-target Work-memory
mem.pyは、sentence-transformers モデルの読み込み時に HuggingFace Xet をデフォルトで無効にするようになりました。これにより、現在の MCP 環境でall-MiniLM-L6-v2の初回ダウンロードを妨げていた CAS の再試行エラーを回避します。semantic_smoke.pyは、言い換えたセマンティックメモリを 1 つ保存し、単純ではない表現でクエリを実行して、ハイブリッド検索の経路を検証します。
Codex MCP トランスポートの復旧フォールバック
ネイティブ MCP セッションで Transport closed が報告された場合は、まず MCP の外部で標準 CLI/スクリプトを使用してください。
python3 scripts/mcp_health_probe.py --db-target Work-memory --tool-error "Transport closed"
python3 scripts/mem_work.py status
python3 scripts/mem_work.py search "Hermes inbox triage latest 14:35 Talos Sisyphus Daedalus memory MCP fallback mem.py" --limit 5
python3 scripts/mem_work.py store --type episodic --category scratch --title "transport recovery check" --content "explicit fallback path" --scope project
mem_work.pyは、標準のmem.pyをラップする薄いラッパーです。SKILL_PGDATABASE=Work-memory、PGDATABASE=Work-memory、PGHOST=localhost、PGPORT=5432を設定します。- 毎回手入力で環境変数を指定する代わりに、Finch/Wren のフォールバックで使用してください。
復旧ルール(フェイルクローズ):
mcp_health_probe.pyがdiagnosis=client_transport_staleを返した場合、現在のクライアント/ツールのトランスポートはサーバー側だけでは修復できません。- メモリ MCP プロセスをむやみに強制終了したり、無関係なペインを再起動したりしないでください。
- 影響を受けたクライアントセッション/ツールのトランスポートのみを(オペレーターの承認を得て)再起動し、その後、次の項目を再確認してください。
- MCP の
memory_statusが再び動作する python3 scripts/mem_work.py statusが正常な状態を維持するnvidia-smi --query-compute-appsに、GPU0 上のskill-system-memoryサポートコンテキストが表示されない
- MCP の
Myelin Registry + ANS Bridge
scripts/myelin_registry.py は、SK MCP をミエリンのインデックス/アフォーダンスインターフェースに変換します。
python3 scripts/myelin_registry.py build --output artifacts/myelin-registry.json
python3 scripts/myelin_registry.py search dispatch --context '{"pane":"dev_coder:SK-coder","message_file":"/tmp/spec.txt"}' --limit 3
python3 scripts/myelin_registry.py get dispatch:hermes-dispatch
python3 scripts/myelin_registry.py validate cli:raw-tmux-sendkeys --args '{"pane":"dev_coder:SK-coder","message":"hi","intent":"dispatch","urgent":false}'
- メタデータスキーマ:
myelin-registry.schema.yaml - シード済みの高価値アフォーダンス:
myelin-seeds.yaml - ANS イベント/応答コントラクト:
ans-myelin-bridge-contract.yaml - ポリシー:すべてのアフォーダンスをインデックス化し、意図/コンテキストに関連する上位 k 件のみを挿入します。
メモリの可視化(Markdown エクスポート)
PostgreSQL へのクエリが日常的な使用には不便な場合は、メモリを ./Memory/ 配下の Markdown ファイルにエクスポートできます(デフォルトではカレントディレクトリです)。
bash "<skill-dir>/scripts/sync_memory_to_md.sh" --out-dir "./Memory"
出力:
Memory/Long.md(セマンティック+手続き的)Memory/Procedural.md(手続き的のみ)Memory/Short.md(摩擦+日次圧縮+手続き的な重要事項)Memory/Episodic.md(エピソード記憶)
バックアップ:
git statusに不要な差分が表示されないよう、バックアップはMemory/.backups/配下に保存されます。- 無効にするには
--no-backupを使用してください。
同期スクリプトは、存在しない場合に Memory/.gitignore も作成します(.backups/ と SYNC_STATUS.txt を無視します)。
長期インデックス:
Memory/Long.mdには、エクスポートを閲覧しやすくするためのIndexセクション(主なカテゴリ+タグ)が含まれます。
search_memories(query, types[], categories[], tags[], agent_id, min_importance, limit)
ハイブリッド検索:全文検索(tsvector)+トライグラム類似度(pg_trgm)+タグによるフィルタリング。
平易な英語のクエリを受け付けます。tsquery 構文は不要です。
関連性スコア:text_score * decay * recency * importance。
-- Natural language
SELECT * FROM search_memories('ssh tunnel port conflict', NULL, NULL, NULL, NULL, 7.0, 5);
-- Filter by type + tags
SELECT * FROM search_memories(
'troubleshooting steps',
ARRAY['procedural']::memory_type[],
NULL,
ARRAY['ssh'],
NULL, 0.0, 5
);
戻り値:id, memory_type, category, title, content, importance_score, relevance_score, match_type
match_type は次のいずれかです:fulltext、trigram_title、trigram_content、metadata。
memory_health_check()
total_memories、avg_importance、stale_count の metric | value | status を返します。
apply_memory_decay()
エピソード記憶を 0.9999^days_since_access で減衰させます。毎日実行してください。
prune_stale_memories(age_days, max_importance, max_access_count)
しきい値を下回る古いエピソード記憶を論理削除します。デフォルト:180 日、重要度 <= 3、アクセスなし。
エージェントのワークフロー
自動書き込みテンプレート
バグを修正した後、または自明ではない問題を解決した後は、標準テンプレートを使用してメモリを保存してください。
- 手順:
scripts/auto-write-template.md
ベストプラクティス:シェルのクォートや認証の問題を避けるため、
mem.pyラッパーを優先して使用してください。 Raw SQL の例については、付録:Raw SQL を参照してください。
タスクの前
# 自動撈出相關記憶摘要(推薦)
python3 scripts/mem.py context "keywords from user request"
# 或搜尋並手動閱讀
python3 scripts/mem.py search "keywords from user request" 5
関連するメモリが見つかった場合は、それを参照してください:「過去の経験(メモリ #1)に基づくと……」
問題の解決後
python3 scripts/mem.py store semantic category-name "One-line problem summary" \
"tag1,tag2,tag3" 8 --content "Detailed problem + solution"
サブエージェントに委任する場合
プロンプトに次を含めてください:
MUST DO FIRST:
python3 scripts/mem.py context 'relevant keywords'
MUST DO AFTER:
If you solved something new:
python3 scripts/mem.py store semantic <category> '<title>' '<tags>' <importance> --content '<solution>'
メモリシステムの健全性を確認する
python3 scripts/mem.py status
タスクメモリレイヤー(任意)
このスキルには、Beads に着想を得た最小限のタスク/課題レイヤーも含まれています。グラフセマンティクスと、「着手可能な作業」を決定的に検索するクエリを提供します。
オブジェクト:
agent_tasks:タスク(ステータス、優先度、担当者)task_links:型付きリンク(blocks、parent_child、relatedなど)blocked_tasks_cache:着手可能なタスクのクエリを高速化するためのマテリアライズドキャッシュtask_memory_links:タスクを、成果やメモを記録するメモリ(agent_memories)にリンクします
タスクを作成します:
INSERT INTO agent_tasks(title, description, created_by, priority)
VALUES ('Install pgvector', 'Windows build + enable extension', 'user', 1);
依存関係を追加します:
-- Task 1 blocks task 2
INSERT INTO task_links(from_task_id, to_task_id, link_type)
VALUES (1, 2, 'blocks');
-- Task 2 is parent of task 3 (used for transitive blocking)
INSERT INTO task_links(from_task_id, to_task_id, link_type)
VALUES (2, 3, 'parent_child');
ブロックキャッシュを再構築します(通常はトリガーによって自動的に行われます):
SELECT rebuild_blocked_tasks_cache();
着手可能な作業を検索します:
SELECT id, title, priority
FROM agent_tasks t
WHERE t.deleted_at IS NULL
AND t.status IN ('open','in_progress')
AND NOT EXISTS (SELECT 1 FROM blocked_tasks_cache b WHERE b.task_id = t.id)
ORDER BY priority ASC, updated_at ASC
LIMIT 50;
タスクを取得します(アトミック):
SELECT claim_task(2, 'agent-1');
タスクをメモリにリンクします:
INSERT INTO task_memory_links(task_id, memory_id, link_type)
VALUES (2, 123, 'outcome');
任意の追加機能:conditional_blocks(まだ実装されていません)
- コアワークフローが安定するまでは、意図的に実装を保留しています。
- 今すぐ必要な場合は、
task_links.metadataに条件(例:{ "os": "windows" })を保存し、ドキュメントとして扱ってください。
ラッパースクリプト(推奨)
SQL の再入力を避けるため、このスキルに同梱されているラッパースクリプトを使用してください。
Windows:
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "scripts\tasks.ps1" ready 50
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "scripts\tasks.ps1" create "Install pgvector" 1
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "scripts\tasks.ps1" claim 2 agent-1
Linux/macOS:
bash "scripts/tasks.sh" ready 50
bash "scripts/tasks.sh" create "Install pgvector" 1
bash "scripts/tasks.sh" claim 2 agent-1
圧縮ログ(高価値)
圧縮によってコンテキストが削除されることがあります。圧縮はすべて重要なイベントとして扱い、記録してください。
OpenCode を使用している場合は、自動圧縮ログ記録に OpenCode プラグインの方法をおすすめします。
OpenCode プラグイン(experimental.session.compacting)
plugins/skill-system-memory.jsとplugins/runtime_sync.jsを~/.config/opencode/plugins/にコピーします- OpenCode を再起動します
圧縮イベントを次の場所にローカル保存します:
~/.config/opencode/skill-system-memory/compaction-events.jsonl
また、Postgres への store_memory(...) 書き込みも可能な範囲で試みます(pgpass が必要です)。
確認
SELECT id, title, relevance_score
FROM search_memories('compaction', NULL, NULL, NULL, NULL, 0, 10);
何も挿入されない場合は、psql がプロンプトなしで認証できるように .pgpass/pgpass.conf を設定してください。
日次圧縮の統合
未処理の圧縮イベントはノイズが多いため、複数の圧縮イベントを1件の日次メモリにまとめる日次統合ジョブを実行してください。
統合スクリプトでは、OpenCode プラグインのイベントログパスがデフォルトで使用されます。
- OpenCode イベント:
~/.config/opencode/skill-system-memory/compaction-events.jsonl - 出力ディレクトリ:
~/.config/opencode/skill-system-memory/compaction-daily/
Windows で手動実行:
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "scripts\consolidate-compactions.ps1"
Linux/macOS で手動実行:
bash "scripts/consolidate-compactions.sh"
スケジュール設定:
- Windows タスク スケジューラ:上記の PowerShell コマンドを毎日実行するタスクを作成します
- Linux の cron の例:
# every day at 02:10 UTC
10 2 * * * bash "<skill-dir>/scripts/consolidate-compactions.sh" >/dev/null 2>&1
フリクションログ(不便をツール改善につなげる)
不便なこと、壊れやすいこと、失敗することがあれば、必ず次の対応を行ってください。
- カテゴリを
frictionとし、ツール/OS/エラーのタグを付けたepisodicメモリを保存します。 - 繰り返し発生する場合(2回以上)は、チェックリストを含む
proceduralメモリ(重要度 >= 7)に昇格させます。 - 修正内容が安定したルール/ワークフローになったら、このスキルのドキュメントを更新します(すべてのエージェントが学習できるようにします)。
スキーマの概要
agent_memories — 一般的なイベントログです。全文検索、トライグラムインデックス、JSONB メタデータ、論理削除に対応しています。
soul_states — ユーザーごとに 1 行です。構造化された性格/感情/バッファーの JSONB を保存します。FK → agent_memories。
insight_facets — セッションごとのファセットを構造化フィールドで保存します。FK → agent_memories。
evolution_snapshots — 変更内容を JSONB で保存する、バージョン管理された進化記録です。FK → agent_memories。現在のステータスは、提案の永続化における LEGACY_COMPAT_SURFACE であり、スナップショット/バージョン履歴には引き続き使用されます。
user_preferences — 信頼度スコア付きのキーと値によるユーザー設定です。
memory_links — グラフ上の関係(参照、置き換え、矛盾)です。
working_memory — 自動期限切れに対応した、一時的なセッションコンテキストです。
型付きテーブル関数(型付きテーブルと agent_memories の両方にデュアルライトします):
upsert_soul_state(user, yaml, personality, emotion, ...)→ soul_statesinsert_insight_facet(user, session_id, yaml, ...)→ insight_facetsinsert_evolution_snapshot(user, version_tag, target, ...)→ evolution_snapshotsupsert_user_preference(user, key, value, source, confidence)→ user_preferencesget_soul_state(user)、get_recent_facets(user, limit)、get_evolution_history(user, limit)、get_user_preferences(user)→ 型付き読み取りget_agent_context(user, facet_limit)→ プラグインへの注入用に集約されたコンテキスト
現在、リポジトリに対応する migrate-typed-tables.sql ファイルはありません。レガシー型付きテーブルのバックフィルは延期扱いとし、サポート対象の移行方法として記載しないでください。
Postgres ファーストのランタイムプロジェクションテーブル(session_summaries、project_summaries、context_rollups、behavior_*)は、この機能を明示的に有効にする場合、migrate-v2-postgres-first.sql によって作成されます。
主なカラム:memory_type、category、tags[]、title、content、content_hash(自動設定)、metadata(JSONB)、importance_score、access_count、relevance_decay、search_vector(自動設定)。
アンチパターン
| しないこと | 代わりにすること |
|---|---|
| すべてを保存する | 自明ではない解決策だけを保存する |
| タグを省略する | 技術、エラーコード、プラットフォームなどを網羅的にタグ付けする |
to_tsquery を直接使う | search_memories() は plainto_tsquery を使って処理します |
| すべてのデータに同じ種類を使う | コンテンツに応じた適切な memory_type を使う |
| 重要度の評価を忘れる | 正直に評価する:9~10 は実戦で検証済み、5~6 は部分的 |
注意すべき点
| 問題 | 重大度 | 対策 |
|---|---|---|
| チャンク化でコンテキストが失われる | 重大 | 問題と解決策をひとまとまりとして保存する |
| 古い技術に関するメモリ | 高 | 毎日 apply_memory_decay() を実行し、古くなったものを整理する |
| メモリの重複 | 中 | store_memory() は content_hash に基づいて自動的に重複を排除します |
| ベクトル検索がない | 情報 | pg_trgm があいまい検索を提供します。pgvector は後から追加できます |
クロスプラットフォームに関する注意
- PostgreSQL 14-18 に対応(パーティショニングおよび GENERATED ALWAYS は使用しません)
- pg_trgm のみが必須の拡張機能です(すべての PG ディストリビューションに同梱)
- Linux:
psql -U postgres -d <project>-memory -f init.sql - Windows:psql.exe のフルパスを指定するか、PG の bin を PATH に追加します
- MCP postgres_query:読み取り操作に使用できます。DDL には psql が必要です
メンテナンス
SELECT apply_memory_decay(); -- daily
SELECT prune_stale_memories(180, 3.0, 0); -- monthly
DELETE FROM working_memory WHERE expires_at < NOW(); -- daily
SELECT * FROM memory_health_check(); -- anytime
オプション:pgvector によるセマンティック検索
PostgreSQL サーバーに pgvector がインストールされている場合、init.sql は次の処理を行います。
- 拡張機能
vectorを作成します(存在しない場合もエラーにはなりません) agent_memories.embedding vectorを追加します(次元数は可変)search_memories_vector(p_embedding, p_embedding_dim, ...)を作成します
注意事項:
- これは埋め込みを生成しません。
agent_memories.embeddingは自分で設定する必要があります。 - 埋め込みが存在すれば、最近傍検索を実行できます。
-- p_embedding is a pgvector literal; pass it from your app.
-- Optionally filter by dimension (recommended when using multiple models).
SELECT id, title, similarity
FROM search_memories_vector('[0.01, 0.02, ...]'::vector, 768, NULL, NULL, NULL, NULL, 0.0, 10);
注:次元数が可変のベクトルには、pgvector のインデックスを作成できません。これは、埋め込みサイズの異なるローカルモデルに対応するためのトレードオフです。
pgvector がインストールされていなくても、その他の機能(fts と pg_trgm)はすべて動作します。
埋め込み取り込みパイプライン
pgvector 検索は、agent_memories.embedding にデータを設定した後にのみ機能します。
このスキルには、取り込みスクリプト(相対パス)が含まれています。スキルのディレクトリから実行してください。
scripts/ingest-embeddings.ps1scripts/ingest-embeddings.sh
以下の処理を行います。
embedding IS NULLのメモリを検索します- OpenAI 互換の埋め込みエンドポイント(Ollama を含む)を呼び出します
- ベクトルを
agent_memories.embedding vectorに書き込みます
要件:
- pgvector がインストールされ、
init.sqlが適用されていること(agent_memories.embeddingが存在する必要があります) .pgpass/pgpass.confが設定されていること(psql -wでプロンプトを表示せずに書き込めるようにします)- 埋め込み API 用の環境変数:
EMBEDDING_PROVIDER(ollamaまたはopenai。既定値はopenai)EMBEDDING_API_KEY(openaiでは必須、ollamaでは任意)EMBEDDING_API_URL(既定値はプロバイダーによって異なります)EMBEDDING_MODEL(既定値はプロバイダーによって異なります)EMBEDDING_DIMENSIONS(任意。対応している場合、埋め込みエンドポイントに転送されます)
Windows の例:
$env:EMBEDDING_PROVIDER = "ollama"
$env:EMBEDDING_MODEL = "nomic-embed-text"
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "scripts\ingest-embeddings.ps1" -Limit 25
Linux/macOS の例:
export EMBEDDING_API_KEY=...
export EMBEDDING_MODEL=text-embedding-3-small
bash "scripts/ingest-embeddings.sh"
スケジュール設定:
- 新しいメモリを追加した後、毎日(または毎時間)実行します
- 信頼できると判断するまでは、
Limitを小さく設定してください
堅牢性に関する注意:
- Windows では、非常に長い SQL 文字列を
psql -cに渡すと不安定になることがあります。取り込みスクリプトは行ごとの更新を一時的な.sqlファイルに書き込み、psql -fを実行することで、コマンドラインの長さや引用符に関する問題を回避します。
関連スキル
systematic-debugging、postgres-pro、postgresql-table-design
共有 DB モードでは、実行時のロール切り替えが必要です。
- コネクターの認証情報を使用して接続します
- リクエストごとに
SET ROLE visitor_<identity>を実行します - Hermes/管理者によるプロジェクト横断の監査フローの場合にのみ
--all-scopesを使用します