@yungkei/geoplana 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README-zh.md +253 -0
  2. package/README.md +73 -10
  3. package/dist/adapters/opencode/index.js.map +1 -1
  4. package/dist/{chunk-6BJCPRH7.js → chunk-4JZEJXMA.js} +22 -3
  5. package/dist/chunk-4JZEJXMA.js.map +1 -0
  6. package/dist/chunk-5QLVGPLD.js +56 -0
  7. package/dist/chunk-5QLVGPLD.js.map +1 -0
  8. package/dist/chunk-CUOJUXUT.js +91 -0
  9. package/dist/chunk-CUOJUXUT.js.map +1 -0
  10. package/dist/{chunk-QLNSMEWB.js → chunk-LSGK3SKU.js} +6 -5
  11. package/dist/chunk-LSGK3SKU.js.map +1 -0
  12. package/dist/chunk-TGAZA6IU.js +46 -0
  13. package/dist/chunk-TGAZA6IU.js.map +1 -0
  14. package/dist/chunk-THMXXBZW.js +2593 -0
  15. package/dist/chunk-THMXXBZW.js.map +1 -0
  16. package/dist/chunk-YGHYIQRK.js +46 -0
  17. package/dist/chunk-YGHYIQRK.js.map +1 -0
  18. package/dist/cli/index.js +155 -20
  19. package/dist/cli/index.js.map +1 -1
  20. package/dist/{events-ZYPG3QO3.js → events-QOMOWQVJ.js} +3 -2
  21. package/dist/{handler-XK22NAV5.js → handler-ILMUSX3A.js} +35 -50
  22. package/dist/handler-ILMUSX3A.js.map +1 -0
  23. package/dist/index.d.ts +634 -7
  24. package/dist/index.js +406 -4
  25. package/dist/index.js.map +1 -1
  26. package/dist/{install-GAP3PF2S.js → install-SLFDCAVQ.js} +60 -3
  27. package/dist/install-SLFDCAVQ.js.map +1 -0
  28. package/dist/metrics-CMVYA57T.js +11 -0
  29. package/dist/metrics-CMVYA57T.js.map +1 -0
  30. package/dist/{server-2SYHDJNH.js → server-UK2MWDSH.js} +71 -5
  31. package/dist/server-UK2MWDSH.js.map +1 -0
  32. package/dist/{transfer-HXJSGD4S.js → transfer-S5IMQ5JI.js} +5 -4
  33. package/dist/transfer-S5IMQ5JI.js.map +1 -0
  34. package/package.json +22 -3
  35. package/server.json +22 -0
  36. package/dist/chunk-6BJCPRH7.js.map +0 -1
  37. package/dist/chunk-EHAYHYRK.js +0 -1325
  38. package/dist/chunk-EHAYHYRK.js.map +0 -1
  39. package/dist/chunk-QLNSMEWB.js.map +0 -1
  40. package/dist/handler-XK22NAV5.js.map +0 -1
  41. package/dist/install-GAP3PF2S.js.map +0 -1
  42. package/dist/server-2SYHDJNH.js.map +0 -1
  43. package/dist/transfer-HXJSGD4S.js.map +0 -1
  44. /package/dist/{events-ZYPG3QO3.js.map → events-QOMOWQVJ.js.map} +0 -0
package/README-zh.md ADDED
@@ -0,0 +1,253 @@
1
+ # Geoplana
2
+
3
+ <p align="center">
4
+ <strong>通用 AI 外置记忆体</strong><br>
5
+ <em>双层存储 · 无损归档 · 压缩抢救 · 跨 agent 持久记忆</em>
6
+ </p>
7
+
8
+ <p align="center">
9
+ <a href="README.md">English</a>
10
+ </p>
11
+
12
+ <p align="center">
13
+ <a href="https://www.npmjs.com/package/@yungkei/geoplana"><img src="https://img.shields.io/npm/v/%40yungkei%2Fgeoplana?style=flat&label=npm" alt="npm version"></a>
14
+ <img src="https://img.shields.io/badge/license-Apache--2.0-blue?style=flat" alt="license">
15
+ <img src="https://img.shields.io/badge/node-%3E%3D20-brightgreen?style=flat&logo=node.js" alt="node version">
16
+ <img src="https://img.shields.io/badge/types-TypeScript-blue?style=flat&logo=typescript" alt="typescript">
17
+ </p>
18
+
19
+ ---
20
+
21
+ 像涡虫(geoplana)一样:即使上下文被"切断"——上下文压缩、会话结束、模型切换——记忆也能完整再生。为 opencode、claude code 等 AI coding agent 提供本地持久记忆。
22
+
23
+ ## 为什么选择 geoplana?
24
+
25
+ **你的 agent 的记忆有两个断点。**
26
+ 一是**会话内**:上下文塞满时,agent 把历史压缩成 LLM 摘要——研究([Compact-Bench](https://arxiv.org/abs/2610.31710))表明,LLM 摘要最多只保留 **~16%** 的结构化细节(后续请求中还会再出现的那些)。二是**会话间**:会话一结束,没写下来的东西全部消失。geoplana 把两个断点都接上:
27
+
28
+ - **压缩前**,完整对话快照无损归档——没有任何内容被"摘要"掉。独立研究中,"纯文本日志 + 检索"方案的召回准确率达 **95–97%**,而有损基线最高只有 **21%**([GrepMem](https://arxiv.org/abs/2611.25123))
29
+ - **结构化提取**(确定性规则,而非 LLM 摘要)额外提炼值得保留的细节:同一基准中,纯机械提取保留了约 **79%** 的此类结构化细节——路径、提交 ID、错误类型、URL、配置项——而 LLM 摘要约 16%(约 **5 倍**)
30
+ - **跨会话、跨 agent**:同一份记忆跟着你从 opencode 到 claude code 到任何 MCP 兼容 agent,切换模型也不丢
31
+
32
+ **为承载多年记忆而建,值得信赖。**
33
+
34
+ - **本地优先、隐私可控**:单个 SQLite 文件,零云端依赖;`<private>` 内容永不落盘
35
+ - **任意语言可检索**:中、日、韩、泰、俄、阿拉伯等语言的全文检索真正可用
36
+ - **存储自管理**:热/温/冷三层(gzip 压缩后体积约为原来的 25%)、容量配额、遗忘曲线淘汰——常用的记忆永不衰减
37
+ - **你拍板,不是 AI 拍板**:冲突记忆只标注提醒,由你裁决(`memory_resolve`),绝不静默合并或删除
38
+ - **规则也留得住**:一项研究发现,第一次压缩摘要就会丢掉约 **1/3** 的任务约束,真实用户会话中"该如何工作、不该做什么"的规则被丢弃的频率约为"要做什么"规格的 **6 倍**([Salle et al., 2026](https://arxiv.org/abs/2610.31778))——geoplana 把这类规则作为 pinned 记忆跨会话保留
39
+ - **升级天然安全**:只增不毁的 schema 迁移、迁移前自动备份、旧版本会拒绝写入更新的数据库,避免损坏数据
40
+
41
+ **几分钟接入。** 一条命令接入 claude code(纯配置)或 opencode(薄 shim),也可以作为带类型的 npm 库嵌入你自己的 agent。
42
+
43
+ ## 功能
44
+
45
+ - **双层存储**:提炼记忆(memories)+ 无损原始归档(episodes),SQLite + FTS5 多语言全文检索(中/日/韩/泰/俄/阿拉伯等),本地零依赖
46
+ - **本地查询扩展**:改写、跨语言、形态变体的查询同样能命中——内置中英概念表 + 意图相关词在匹配前扩展查询(不依赖模型、不联网);中文两字词也能命中,字面命中始终排在仅扩展命中之上
47
+ - **自动捕获**:用户明确表达的决策、偏好与错误按确定性规则结构化提取;工具活动只留在无损原始归档里;`<private>` 内容永不落盘
48
+ - **压缩抢救**:agent 上下文压缩前,完整对话快照自动归档
49
+ - **生命周期管理**:热/温/冷三层留存(gzip 压缩 + 归档导出)、存储配额、遗忘曲线淘汰,以及 GC 清理活动日志记忆
50
+ - **基于证据的召回质量**:每次搜索都会记录查询日志(查询、完整搜索输入、评分参数快照、命中分数、扩展 provenance、带分支与 scope 标签的命中),结局会回写到找出它的那条查询命中上;`memory_stats` 输出零命中率、按查询的使用/无用率与标注覆盖率、LIKE/扩展贡献、scope 命中占比、按类型的价值统计(被读过且评为有用的决策数)、抽取与冲突消解计数、GC 活动与噪音审计(D0-D3)
51
+ - **使用保障**:`geoplana setup` 向 agent 指令文件(AGENTS.md / CLAUDE.md)写入记忆协议,告诉它何时检索、何时保存、冲突如何处理
52
+ - **冲突决策**:`memory_save` 发现相似记忆时返回 `conflicts` 而非静默覆盖;agent 向用户确认后调用 `memory_resolve`(keep-new / keep-old / keep-both)
53
+ - **MCP 工具**:`memory_save` / `memory_search` / `memory_get` / `memory_update` / `memory_delete` / `memory_list` / `memory_capture` / `memory_context` / `memory_resolve` / `memory_feedback` / `memory_stats`
54
+
55
+ ## 安装
56
+
57
+ ```bash
58
+ npm install -g @yungkei/geoplana
59
+ ```
60
+
61
+ 数据存于 `~/.geoplana/geoplana.db`(环境变量 `GEOPLANA_HOME` 可覆盖)。
62
+
63
+ 开发 geoplana 本身:
64
+
65
+ ```bash
66
+ git clone https://github.com/yungkei/geoplana.git
67
+ cd geoplana
68
+ npm install
69
+ npm run build
70
+ npm link # 使 geoplana 命令全局可用
71
+ ```
72
+
73
+ ## 快速开始
74
+
75
+ ### 接入 claude code(纯配置,零代码)
76
+
77
+ ```bash
78
+ geoplana setup claude-code
79
+ ```
80
+
81
+ 自动写入 `~/.claude/settings.json` hooks:会话开始注入记忆 → 每轮捕获 → 压缩前快照抢救。
82
+
83
+ ### 接入 opencode(桥接 shim)
84
+
85
+ ```bash
86
+ geoplana setup opencode
87
+ ```
88
+
89
+ 复制 shim 插件到 `~/.config/opencode/plugins/`,并在 `opencode.json` 中注册 MCP 服务(其余设置保持不变):
90
+
91
+ ```json
92
+ { "mcp": { "geoplana": { "type": "local", "command": ["geoplana", "mcp"] } } }
93
+ ```
94
+
95
+ shim 是双代同体的 —— 同一个文件在加载时自动适配 opencode **V1**(≥1.16.2)与 **V2** 两套插件 API,无需按版本选择产物。`setup` 会检测本机安装的 opencode 世代并报告兼容性。
96
+
97
+ `setup` 还会把当前构建的指纹写入该服务条目。MCP 服务是长驻进程,升级后正在运行的那个仍会继续跑旧代码;指纹让 opencode 重启它、换上新构建。每次升级后重跑一次 `geoplana setup opencode`(在 opencode 里 `/reload` 也可以)。`geoplana doctor` 打印已安装的构建,`memory_stats` 报告运行中服务启动时的构建 —— 两者不一致就说明服务是旧的。
98
+
99
+ ### 接入任意 MCP agent
100
+
101
+ ```json
102
+ {
103
+ "mcpServers": {
104
+ "geoplana": { "command": "geoplana", "args": ["mcp"] }
105
+ }
106
+ }
107
+ ```
108
+
109
+ 不做全局安装的话,直接跑已发布的包:
110
+
111
+ ```json
112
+ {
113
+ "mcpServers": {
114
+ "geoplana": { "command": "npx", "args": ["-y", "@yungkei/geoplana", "mcp"] }
115
+ }
116
+ }
117
+ ```
118
+
119
+ ## CLI
120
+
121
+ ```bash
122
+ geoplana save --namespace global --type decision --content "使用 Valkey 缓存" --importance 0.9
123
+ geoplana search "缓存方案" [--namespace a,b] [--limit 20]
124
+ geoplana list [--namespace a,b] [--type decision] # 别名: ls
125
+ geoplana get <id> / update <id> / delete <id> [--dry-run] # 别名: view / rm
126
+ geoplana resolve --new-id x --old-id y --action keep-new
127
+ geoplana context --namespace global,project:/repo
128
+ geoplana capture --namespace session:abc --kind message --content "..." --session-id abc
129
+
130
+ geoplana episodes list [--session s1] [--kind note] # 浏览无损归档层
131
+ geoplana episodes get <id> # 压缩记录读取时透明解压
132
+ geoplana export --output backup.jsonl.gz [--layer all] # 版本化备份
133
+ geoplana import backup.jsonl.gz [--dry-run] # 已存在的 id 自动跳过
134
+
135
+ geoplana stats # 存储用量、记忆类型分布、namespace 分布
136
+ geoplana stats --perf # 另附各事件的延迟分位数与结果计数器
137
+ geoplana stats --perf --event search,hook:recall:hits # 只看指定指标事件
138
+ geoplana gc [--dry-run] # 留存清理:压缩/导出/淘汰
139
+ geoplana migrate [--dry-run] # 把既有记忆重新归到共享 scope
140
+ geoplana doctor # schema 版本与完整性检查
141
+ geoplana mcp # 以 stdio 启动 MCP server
142
+ geoplana hook <event> # 通用 hook 处理器(agent 钩子调用)
143
+ ```
144
+
145
+ ## 记忆的 scope
146
+
147
+ 每条记忆都归属一个 scope,scope 决定谁读得到它。
148
+
149
+ | scope | namespace | 可见范围 | 内容 |
150
+ |---|---|---|---|
151
+ | global | `global` | 所有项目与会话 | 关于"怎么做"的规定 |
152
+ | project | `project:<path>` | 该仓库的所有会话 | 决策与偏好 |
153
+ | session | `session:<id>` | 仅该会话 | 执行过的命令、改过的文件、快照 |
154
+
155
+ 一个会话读取 global + 自己所在的项目 + 自己。
156
+
157
+ 自动抽取按"是否应当跨会话存活"来路由:
158
+
159
+ - 用户说出的**决策与偏好**进入 project scope
160
+ - **明确规定**(instruction)进入 global scope
161
+ - **事实、错误与上下文**留在 session scope —— 那是活动流水账,不是共享知识
162
+
163
+ 两条规则保证共享 scope 不被污染:
164
+
165
+ - 只有**完整语句**才会被提升。半截话("改为复制 |")留在 session scope,因为共享 scope 会被之后每个会话读取
166
+ - 只有**用户自己的话**才会被提升。agent 复述自己的工作("改为路径无关:...")是在记录任务,不是在做决定
167
+
168
+ 项目路径会做归一化(`D:\repo` 与 `D:/repo` 是同一个 namespace),每次捕获都会把项目目录记录到 episode 上。
169
+
170
+ `geoplana migrate` 把同样的规则应用到规则出现之前捕获的记忆:提升合格的语句、归一化 project namespace,并报告每一条被跳过的记忆及其原因。它不会删除任何东西。
171
+
172
+ ```bash
173
+ geoplana migrate --dry-run # 预览
174
+ geoplana migrate # 执行
175
+ ```
176
+
177
+ `geoplana stats` 会输出 `durableScope`:
178
+
179
+ - `shared` —— 位于 global 或 project scope 的持久记忆,之后每个会话都读得到
180
+ - `locked` —— 符合共享条件却仍留在 session scope 的持久记忆,也就是 `geoplana migrate` 会搬走的那部分积压
181
+ - `sessionOnly` —— 仍留在 session scope 的全部持久记忆,含那些本就不该共享的片段
182
+
183
+ ## 配置
184
+
185
+ `~/.geoplana/config.json`(全部可选,有默认值):
186
+
187
+ ```json
188
+ {
189
+ "dbPath": "~/.geoplana/geoplana.db",
190
+ "embedding": { "provider": "none" },
191
+ "capture": { "maxExtractChars": 20000 },
192
+ "recall": { "intent": true, "expansion": true, "limit": 3 },
193
+ "retention": {
194
+ "hotDays": 30,
195
+ "snapshotHotDays": 90,
196
+ "coldDays": 365,
197
+ "evictThreshold": 0.02,
198
+ "protectRecentDays": 14,
199
+ "maxStorageMb": 500,
200
+ "autoGc": true
201
+ }
202
+ }
203
+ ```
204
+
205
+ | 配置项 | 说明 |
206
+ | ----------------- | ------------------------------------------------------------------------------------- |
207
+ | `recall.intent` | 对召回提示做意图识别(关键词启发式,无 LLM),并对匹配的记忆类型做加权;`false` 关闭加权 |
208
+ | `recall.expansion` | 用概念同义词与意图相关词扩展检索查询(本地,无模型);`false` 关闭扩展 |
209
+ | `recall.limit` | 每次召回注入返回的记忆条数 |
210
+ | `hotDays` | episodes 原文可检索的热窗口天数 |
211
+ | `coldDays` | 压缩层保留天数,`-1` = 永久留存,`0` = 压缩后立即导出 |
212
+ | `maxStorageMb` | DB 体积配额,超限自动升级清理 |
213
+ | `evictThreshold` | 遗忘曲线淘汰阈值(pinned 记忆永不淘汰) |
214
+ | `autoGc` | MCP server 启动时自动执行 GC |
215
+ | `metrics.queryLog` | 把每次搜索记录为证据(查询、namespace、带分支标签的命中),供召回质量报告使用;`false` 关闭 |
216
+
217
+ 环境变量:`GEOPLANA_HOME`(数据目录)、`GEOPLANA_CMD`(agent shim 调用的命令路径)、`GEOPLANA_RECALL=1`(opencode 每轮自动召回)、`GEOPLANA_DEBUG=1`(调试日志)。
218
+
219
+ ## 作为库使用
220
+
221
+ geoplana 也是 npm 包(`@yungkei/geoplana`),第三方程序可直接依赖调用:
222
+
223
+ ```bash
224
+ npm install @yungkei/geoplana
225
+ ```
226
+
227
+ ```ts
228
+ import { Geoplana, createStorage, createMemoryStorage } from "@yungkei/geoplana"
229
+
230
+ const geoplana = new Geoplana(createStorage("/path/to/geoplana.db"))
231
+
232
+ geoplana.memories.save({ namespace: "global", type: "decision", content: "使用 Valkey 缓存" })
233
+ const hits = geoplana.search.search({ query: "缓存", includeEpisodes: false })
234
+ const bundle = geoplana.context.build({ namespaces: ["global"] })
235
+
236
+ geoplana.close()
237
+ ```
238
+
239
+ 全部核心服务均有类型导出:`memories` / `search` / `capture` / `context` / `retention`。如需自定义存储引擎,实现 `Storage` 接口并传入 `Geoplana` 构造函数即可。
240
+
241
+ ## 开发
242
+
243
+ ```bash
244
+ npm test # 单元测试
245
+ npm run typecheck # 类型检查
246
+ npm run lint # biome 规范检查
247
+ npm run check:i18n # 国际化守卫
248
+ npm run build # 构建到 dist/
249
+ ```
250
+
251
+ ## 许可协议
252
+
253
+ [Apache-2.0](LICENSE) © 2026 yungkei
package/README.md CHANGED
@@ -43,15 +43,25 @@ When a long coding session hits the context limit, agents compact history into a
43
43
  ## Features
44
44
 
45
45
  - **Two-layer storage**: curated memories + lossless episode archive. SQLite + FTS5 with multilingual full-text search (CJK/Korean/Thai/Russian/Arabic/...), fully local, zero external dependencies
46
- - **Automatic capture**: decisions, file changes, commands and errors extracted with deterministic rules; `<private>` content never touches disk
46
+ - **Local query expansion**: paraphrased, cross-language and morphological queries still hit — a curated English/Chinese concept table plus intent-scoped terms widen the query before matching (no model, no network). Two-character Chinese words match too, and literal matches always rank above expansion-only ones
47
+ - **Automatic capture**: decisions, preferences and errors the user states are extracted with deterministic rules; tool activity stays in the lossless episode archive; `<private>` content never touches disk
47
48
  - **Compaction rescue**: full conversation snapshot archived before the agent compacts its context
48
- - **Lifecycle management**: hot/warm/cold retention tiers (gzip compression + archive export), storage quota, forgetting-curve eviction
49
+ - **Lifecycle management**: hot/warm/cold retention tiers (gzip compression + archive export), storage quota, forgetting-curve eviction, and GC cleanup of activity-log memories
50
+ - **Evidence-based recall quality**: every search is logged (query, full search input, scoring-parameter snapshot, hit scores, expansion provenance, hits tagged with branch and scope), outcomes are written back onto the query hits that surfaced them, and `memory_stats` reports the zero-hit rate, per-query used/useless rates and label coverage, LIKE/expansion contribution, scope hit-share, per-type value (decisions read and rated useful), extraction and conflict-resolution outcomes, GC activity and a noise audit (D0-D3)
49
51
  - **Usage assurance**: `geoplana setup` writes a memory protocol into the agent's instructions file (AGENTS.md / CLAUDE.md) telling it when to search, when to save, and how to handle conflicts
50
52
  - **Conflict resolution**: `memory_save` returns similar existing memories as `conflicts` instead of silently overwriting; the agent asks the user, then calls `memory_resolve` (keep-new / keep-old / keep-both)
51
- - **MCP tools**: `memory_save` / `memory_search` / `memory_get` / `memory_update` / `memory_delete` / `memory_list` / `memory_capture` / `memory_context` / `memory_resolve`
53
+ - **MCP tools**: `memory_save` / `memory_search` / `memory_get` / `memory_update` / `memory_delete` / `memory_list` / `memory_capture` / `memory_context` / `memory_resolve` / `memory_feedback` / `memory_stats`
52
54
 
53
55
  ## Install
54
56
 
57
+ ```bash
58
+ npm install -g @yungkei/geoplana
59
+ ```
60
+
61
+ Data lives in `~/.geoplana/geoplana.db` (override with the `GEOPLANA_HOME` env var).
62
+
63
+ Working on geoplana itself:
64
+
55
65
  ```bash
56
66
  git clone https://github.com/yungkei/geoplana.git
57
67
  cd geoplana
@@ -60,8 +70,6 @@ npm run build
60
70
  npm link # makes the geoplana command globally available
61
71
  ```
62
72
 
63
- Data lives in `~/.geoplana/geoplana.db` (override with the `GEOPLANA_HOME` env var).
64
-
65
73
  ## Quick start
66
74
 
67
75
  ### claude code (pure config, zero code)
@@ -78,7 +86,7 @@ Writes hooks into `~/.claude/settings.json`: inject memories at session start
78
86
  geoplana setup opencode
79
87
  ```
80
88
 
81
- Copies the shim plugin to `~/.config/opencode/plugins/`, then add to `opencode.json`:
89
+ Copies the shim plugin to `~/.config/opencode/plugins/` and registers the MCP server in `opencode.json` (other settings are preserved):
82
90
 
83
91
  ```json
84
92
  { "mcp": { "geoplana": { "type": "local", "command": ["geoplana", "mcp"] } } }
@@ -86,6 +94,8 @@ Copies the shim plugin to `~/.config/opencode/plugins/`, then add to `opencode.j
86
94
 
87
95
  The shim is dual-generation — one file adapts at load time to both the opencode **V1** (≥1.16.2) and **V2** plugin APIs, so there is no version-specific artifact to choose. `setup` detects the installed opencode generation and reports compatibility.
88
96
 
97
+ `setup` also stamps the server entry with the fingerprint of the installed build. The MCP server is a long-lived process, so after an upgrade the running one would keep serving the old code; the stamp makes opencode restart it onto the new build. Re-run `geoplana setup opencode` after every upgrade (`/reload` in opencode works too). `geoplana doctor` prints the installed build, `memory_stats` reports the build the running server was started with — if the two differ, the server is stale.
98
+
89
99
  ### Any MCP agent
90
100
 
91
101
  ```json
@@ -96,13 +106,23 @@ The shim is dual-generation — one file adapts at load time to both the opencod
96
106
  }
97
107
  ```
98
108
 
109
+ Without a global install, run the published package directly:
110
+
111
+ ```json
112
+ {
113
+ "mcpServers": {
114
+ "geoplana": { "command": "npx", "args": ["-y", "@yungkei/geoplana", "mcp"] }
115
+ }
116
+ }
117
+ ```
118
+
99
119
  ## CLI
100
120
 
101
121
  ```bash
102
122
  geoplana save --namespace global --type decision --content "use Valkey for caching" --importance 0.9
103
123
  geoplana search "caching decision" [--namespace a,b] [--limit 20]
104
124
  geoplana list [--namespace a,b] [--type decision] # alias: ls
105
- geoplana get <id> / update <id> / delete <id> # aliases: view / rm
125
+ geoplana get <id> / update <id> / delete <id> [--dry-run] # aliases: view / rm
106
126
  geoplana resolve --new-id x --old-id y --action keep-new
107
127
  geoplana context --namespace global,project:/repo
108
128
  geoplana capture --namespace session:abc --kind message --content "..." --session-id abc
@@ -110,15 +130,56 @@ geoplana capture --namespace session:abc --kind message --content "..." --sessio
110
130
  geoplana episodes list [--session s1] [--kind note] # browse the archive layer
111
131
  geoplana episodes get <id> # compressed episodes decompress transparently
112
132
  geoplana export --output backup.jsonl.gz [--layer all] # versioned backup
113
- geoplana import backup.jsonl.gz # existing ids are skipped
133
+ geoplana import backup.jsonl.gz [--dry-run] # existing ids are skipped
114
134
 
115
- geoplana stats # storage usage
135
+ geoplana stats # storage usage, memory mix, namespace spread
136
+ geoplana stats --perf # plus per-event latency percentiles and outcome counters
137
+ geoplana stats --perf --event search,hook:recall:hits # only these metric events
116
138
  geoplana gc [--dry-run] # retention GC: compress / export / evict
139
+ geoplana migrate [--dry-run] # re-scope existing memories into the shared scope
117
140
  geoplana doctor # schema version & integrity check
118
141
  geoplana mcp # run the MCP server over stdio
119
142
  geoplana hook <event> # universal hook handler (called by agent hooks)
120
143
  ```
121
144
 
145
+ ## Memory scopes
146
+
147
+ Every memory lives in one of three scopes. The scope decides who can read it.
148
+
149
+ | scope | namespace | visible to | holds |
150
+ |---|---|---|---|
151
+ | global | `global` | every project and session | rules about how to work |
152
+ | project | `project:<path>` | every session of that repository | decisions and preferences |
153
+ | session | `session:<id>` | that one session | commands run, files changed, snapshots |
154
+
155
+ A session reads `global` + its project + itself.
156
+
157
+ Auto-extraction routes by durability, so a decision survives the conversation that produced it:
158
+
159
+ - **decisions and preferences** the user stated go to the project scope
160
+ - **instructions** go to the global scope
161
+ - **facts, errors and context** stay in the session scope - they are the activity log, not shared knowledge
162
+
163
+ Two rules keep the shared scopes clean:
164
+
165
+ - only **complete statements** are promoted. A fragment ("改为复制 |") stays in the session scope, because a shared scope is read by every later session
166
+ - only the **user's own words** are promoted. The agent narrating its work ("改为路径无关:...") documents a task, it does not decide.
167
+
168
+ Project paths are normalized (`D:\repo` and `D:/repo` are one namespace), and the project directory is recorded on every captured episode.
169
+
170
+ `geoplana migrate` applies the same rules to memories captured before the rules existed: it promotes the statements that qualify, normalizes project namespaces, and reports everything it skipped and why. It never deletes.
171
+
172
+ ```bash
173
+ geoplana migrate --dry-run # preview
174
+ geoplana migrate # apply
175
+ ```
176
+
177
+ `geoplana stats` reports `durableScope`:
178
+
179
+ - `shared` - durable memories in a global or project scope, read by every later session
180
+ - `locked` - durable memories that qualify for sharing but still sit in a session scope. This is the backlog `geoplana migrate` would move
181
+ - `sessionOnly` - every durable memory in a session scope, including the ones that do not qualify and are meant to stay there
182
+
122
183
  ## Configuration
123
184
 
124
185
  `~/.geoplana/config.json` (everything optional, sensible defaults):
@@ -128,7 +189,7 @@ geoplana hook <event> # universal hook handler (called by agent hooks)
128
189
  "dbPath": "~/.geoplana/geoplana.db",
129
190
  "embedding": { "provider": "none" },
130
191
  "capture": { "maxExtractChars": 20000 },
131
- "recall": { "intent": true, "limit": 3 },
192
+ "recall": { "intent": true, "expansion": true, "limit": 3 },
132
193
  "retention": {
133
194
  "hotDays": 30,
134
195
  "snapshotHotDays": 90,
@@ -144,12 +205,14 @@ geoplana hook <event> # universal hook handler (called by agent hooks)
144
205
  | Option | Description |
145
206
  | ---------------- | -------------------------------------------------------------------------------- |
146
207
  | `recall.intent` | Classify each recall prompt's intent (keyword heuristics, no LLM) and soft-boost matching memory types; `false` disables the boost |
208
+ | `recall.expansion` | Widen search queries with concept synonyms and intent-scoped terms (local, no model); `false` disables it |
147
209
  | `recall.limit` | Memories returned per recall injection |
148
210
  | `hotDays` | Days episodes stay fully searchable (hot tier) |
149
211
  | `coldDays` | Days compressed episodes are kept; `-1` = keep forever, `0` = export immediately |
150
212
  | `maxStorageMb` | DB size quota; GC escalates when exceeded |
151
213
  | `evictThreshold` | Forgetting-curve eviction threshold (pinned memories are never evicted) |
152
214
  | `autoGc` | Run GC automatically when the MCP server starts |
215
+ | `metrics.queryLog` | Log every search as evidence (query, namespaces, branch-tagged hits) for the recall quality report; `false` disables it |
153
216
 
154
217
  Environment variables: `GEOPLANA_HOME` (data directory), `GEOPLANA_CMD` (command path used by agent shims), `GEOPLANA_RECALL=1` (opencode per-turn recall), `GEOPLANA_DEBUG=1` (debug logs).
155
218
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../adapters/opencode/index.ts"],"sourcesContent":["/**\n * geoplana shim for opencode (design doc §7.2).\n *\n * This file contains NO business logic: it only translates opencode's\n * in-process plugin events into `geoplana hook <event>` external command\n * calls — exactly the same universal hook core that claude code uses via\n * declarative settings.json hooks.\n *\n * Entrypoint shape (one file, both generations):\n * - opencode V1 loads `default` and, when it is an object, calls `server()`\n * (verified in the V1 loader: `readV1Plugin` accepts an object carrying\n * `id` + `server()` from 1.16.2 on, before falling back to legacy calls).\n * - opencode V2 decodes `default` as `{ id, setup }` (its schema rejects\n * function exports outright: \"Expected object\") and calls `setup(ctx)`.\n * Shipping `{ id, setup, server }` therefore satisfies both hosts; the\n * default export is never invoked as a function.\n *\n * The shim never throws: a memory failure must not break a coding session.\n * Set GEOPLANA_DEBUG=1 to log failures to stderr.\n */\nimport { spawn } from \"node:child_process\"\n\n// ---------------------------------------------------------------------------\n// universal hook invocation\n// ---------------------------------------------------------------------------\n\ninterface HookOutput {\n text?: string | null\n [key: string]: unknown\n}\n\nfunction hookCommand(): string[] {\n // PLANARIA_CMD: legacy env name from before the geoplana rename\n const cmd = process.env.GEOPLANA_CMD ?? process.env.PLANARIA_CMD ?? \"geoplana\"\n return cmd.split(\" \")\n}\n\nfunction runHook(event: string, payload: Record<string, unknown>): Promise<HookOutput | null> {\n return new Promise((resolve) => {\n const [bin, ...prefix] = hookCommand()\n const child = spawn(bin!, [...prefix, \"hook\", event], {\n stdio: [\"pipe\", \"pipe\", debugEnabled() ? \"inherit\" : \"ignore\"],\n env: { ...process.env },\n })\n let settled = false\n const done = (out: HookOutput | null) => {\n if (!settled) {\n settled = true\n resolve(out)\n }\n }\n const timer = setTimeout(() => {\n child.kill()\n done(null)\n }, 20000)\n\n const chunks: Buffer[] = []\n child.stdout.on(\"data\", (c) => chunks.push(c as Buffer))\n child.on(\"error\", () => {\n clearTimeout(timer)\n done(null)\n })\n child.on(\"close\", () => {\n clearTimeout(timer)\n const text = Buffer.concat(chunks).toString(\"utf8\").trim()\n if (!text) return done(null)\n try {\n done(JSON.parse(text) as HookOutput)\n } catch {\n done({ text })\n }\n })\n child.stdin.write(JSON.stringify(payload))\n child.stdin.end()\n })\n}\n\n// ---------------------------------------------------------------------------\n// opencode structural types (defensive, minimal)\n// ---------------------------------------------------------------------------\n\ninterface Part {\n type: string\n text?: string\n tool?: string\n state?: { input?: Record<string, unknown> }\n}\n\n/** V1 client / V2 context-hook message: { info, parts }. */\ninterface Message {\n info?: { id?: string; role?: string; sessionID?: string }\n parts?: Part[]\n}\n\n/** V2 `ctx.session.context()` message: flat tagged record. */\ninterface FlatMessage {\n id?: string\n type?: string\n role?: string\n text?: string\n content?: Array<{ type?: string; text?: string; name?: string; state?: { input?: unknown } }>\n}\n\ninterface ToolEvent {\n tool?: string\n files?: string[]\n command?: string\n error?: string\n}\n\ninterface OpencodeClient {\n session: {\n messages(input: { path: { id: string } }): Promise<{ data?: Message[] }>\n }\n}\n\n/** V1 plugin input (also what V1 `server()` receives). */\ninterface PluginContext {\n client: OpencodeClient\n directory?: string\n session?: { hook?: (name: string, fn: (event: unknown) => unknown) => void }\n}\n\n/** V2 hook event bases: `context` / `compaction` share the request shape. */\ninterface V2SessionRequestEvent {\n sessionID?: string\n system?: Array<{ type?: string; text?: string }>\n messages?: Message[]\n}\n\ninterface V2SessionDomain {\n hook(name: string, callback: (input: never) => Promise<void>): Promise<unknown> | undefined\n context(input: { sessionID: string }): Promise<FlatMessage[]>\n}\n\n/** V2 plugin context (promise API) — only what the shim uses. */\ninterface V2PluginContext {\n location?: { directory?: string }\n options?: unknown\n session?: V2SessionDomain\n}\n\n// ---------------------------------------------------------------------------\n\n// PLANARIA_DEBUG / PLANARIA_RECALL: legacy env names from before the rename\nconst debugEnabled = () => Boolean(process.env.GEOPLANA_DEBUG ?? process.env.PLANARIA_DEBUG)\n\nconst debug = (...args: unknown[]) => {\n if (debugEnabled()) console.error(\"[geoplana]\", ...args)\n}\n\nfunction messageText(m: Message): string {\n return (m.parts ?? [])\n .filter((p) => p.type === \"text\" && p.text)\n .map((p) => p.text!)\n .join(\"\\n\")\n}\n\nfunction serializeTranscript(messages: Message[]): string {\n return messages\n .map((m) => {\n const role = m.info?.role ?? \"unknown\"\n const text = messageText(m)\n const tools = (m.parts ?? [])\n .filter((p) => p.type === \"tool\")\n .map((p) => `[tool:${p.tool ?? \"?\"}] ${JSON.stringify(p.state?.input ?? {})}`)\n .join(\"\\n\")\n return [`## ${role}`, text, tools].filter(Boolean).join(\"\\n\")\n })\n .join(\"\\n\\n\")\n}\n\nfunction lastUserMessage(messages: Message[]): Message | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]?.info?.role === \"user\") return messages[i]\n }\n return undefined\n}\n\nfunction inject(output: { messages: Message[] }, text: string): void {\n const target = lastUserMessage(output.messages)\n if (!target) return\n target.parts = target.parts ?? []\n target.parts.unshift({ type: \"text\", text })\n}\n\nfunction extractFiles(input: Record<string, unknown>): string[] | undefined {\n for (const key of [\"filePath\", \"file_path\", \"path\", \"files\"]) {\n const value = input[key]\n if (typeof value === \"string\") return [value]\n if (Array.isArray(value)) return value.filter((v): v is string => typeof v === \"string\")\n }\n return undefined\n}\n\nfunction toolEventFromInput(tool: string | undefined, input: unknown): ToolEvent {\n const rec = (input ?? {}) as Record<string, unknown>\n return {\n tool,\n files: extractFiles(rec),\n command: typeof rec.command === \"string\" ? rec.command : undefined,\n }\n}\n\n/** Map a flat V2 message to capture payload entries (role text + tool events). */\nfunction flatToPayload(m: FlatMessage): { text?: string; role?: string; tools: ToolEvent[] } {\n const role = m.type ?? m.role\n const tools: ToolEvent[] = []\n if (m.type === \"user\" || m.type === \"system\") {\n return { role, text: m.text, tools }\n }\n const content = m.content ?? []\n const texts: string[] = []\n if (m.text) texts.push(m.text)\n for (const item of content) {\n if (item.type === \"text\" && item.text) texts.push(item.text)\n if (item.type === \"tool\") tools.push(toolEventFromInput(item.name, item.state?.input))\n }\n return { role, text: texts.join(\"\\n\"), tools }\n}\n\n/** Shared per-session state for one loaded plugin instance (V1 or V2). */\nfunction createSessionState() {\n const injected = new Set<string>()\n const lastCaptured = new Map<string, string>()\n\n async function sessionStartInject(\n sessionId: string,\n output: { messages: Message[] },\n projectDir?: string,\n ): Promise<void> {\n if (injected.has(sessionId)) return\n injected.add(sessionId)\n const result = await runHook(\"session-start\", { sessionId, projectDir })\n if (result?.text) inject(output, result.text)\n }\n\n async function recallInject(\n sessionId: string,\n output: { messages: Message[] },\n projectDir?: string,\n ): Promise<void> {\n if ((process.env.GEOPLANA_RECALL ?? process.env.PLANARIA_RECALL) !== \"1\") return\n const userText = messageText(lastUserMessage(output.messages) ?? {})\n if (userText.length < 8) return\n const result = await runHook(\"recall\", { sessionId, projectDir, userText })\n if (result?.text) inject(output, result.text)\n }\n\n /** Slice not-yet-seen messages (shared by V1 idle and V2 idle paths). */\n function freshSlice<T>(\n items: T[],\n idOf: (item: T) => string | undefined,\n sessionId: string,\n ): T[] {\n const seen = lastCaptured.get(sessionId)\n const start = seen ? items.findIndex((item) => idOf(item) === seen) + 1 : 0\n const fresh = items.slice(Math.max(start, 0)).slice(-10)\n const last = items.length > 0 ? idOf(items[items.length - 1] as T) : undefined\n if (last) lastCaptured.set(sessionId, last)\n return fresh\n }\n\n return { injected, sessionStartInject, recallInject, freshSlice }\n}\n\n// ---------------------------------------------------------------------------\n// V1: hooks object returned from `server(input, options)`\n// ---------------------------------------------------------------------------\n\nexport async function createGeoplanaPlugin(ctx: PluginContext) {\n const projectDir = ctx.directory\n const state = createSessionState()\n debug(\"v1 server() entry, projectDir:\", projectDir)\n\n async function turnEnd(sessionId: string): Promise<void> {\n const res = await ctx.client.session.messages({ path: { id: sessionId } })\n const messages = res.data ?? []\n const fresh = state.freshSlice(messages, (m) => m.info?.id, sessionId)\n\n const payloadMessages: Array<{ role?: string; text?: string }> = []\n const toolEvents: ToolEvent[] = []\n for (const m of fresh) {\n const text = messageText(m)\n if (text.trim()) payloadMessages.push({ role: m.info?.role, text })\n for (const part of m.parts ?? []) {\n if (part.type !== \"tool\") continue\n toolEvents.push(toolEventFromInput(part.tool, part.state?.input))\n }\n }\n await runHook(\"turn-end\", { sessionId, projectDir, messages: payloadMessages, toolEvents })\n }\n\n const v1Hooks = {\n \"experimental.chat.messages.transform\": async (\n _input: Record<string, never>,\n output: { messages: Message[] },\n ) => {\n try {\n const sid = output.messages.find((m) => m.info?.sessionID)?.info?.sessionID\n if (!sid) return\n await state.sessionStartInject(sid, output, projectDir)\n await state.recallInject(sid, output, projectDir)\n } catch (err) {\n debug(\"messages.transform failed:\", err)\n }\n },\n\n \"experimental.session.compacting\": async (\n input: { sessionID?: string },\n output: { context: string[]; prompt?: string },\n ) => {\n try {\n if (!input.sessionID) return\n const res = await ctx.client.session.messages({ path: { id: input.sessionID } })\n const transcript = serializeTranscript(res.data ?? [])\n const result = await runHook(\"pre-compact\", {\n sessionId: input.sessionID,\n projectDir,\n transcript,\n })\n if (result?.text) output.context.push(result.text)\n } catch (err) {\n debug(\"compacting hook failed:\", err)\n }\n },\n\n event: async ({ event }: { event: { type: string; properties?: Record<string, unknown> } }) => {\n try {\n if (event.type !== \"session.idle\") return\n const sid =\n (event.properties?.sessionID as string | undefined) ??\n (event.properties?.id as string | undefined)\n if (!sid) return\n await turnEnd(sid)\n } catch (err) {\n debug(\"event hook failed:\", err)\n }\n },\n }\n\n return v1Hooks\n}\n\n// ---------------------------------------------------------------------------\n// V2: `setup(ctx)` — ctx.session.hook / ctx.session.context (promise API)\n// ---------------------------------------------------------------------------\n\nasync function setupV2(ctx: V2PluginContext): Promise<void> {\n const projectDir = ctx.location?.directory\n const state = createSessionState()\n\n const session = ctx.session\n if (!session || typeof session.hook !== \"function\") {\n debug(\"v2 setup: session domain unavailable; hooks not registered\")\n return\n }\n\n // context: runs immediately before each model request — inject memories.\n await session.hook(\"context\", async (input: never) => {\n const event = input as unknown as V2SessionRequestEvent\n try {\n const sid = event.sessionID\n if (!sid || !event.messages) return\n const output = { messages: event.messages }\n await state.sessionStartInject(sid, output, projectDir)\n await state.recallInject(sid, output, projectDir)\n } catch (err) {\n debug(\"v2 context hook failed:\", err)\n }\n })\n\n // compaction: archive the transcript and append the structured template.\n await session.hook(\"compaction\", async (input: never) => {\n const event = input as unknown as V2SessionRequestEvent\n try {\n const sid = event.sessionID\n if (!sid) return\n const transcript = serializeTranscript(event.messages ?? [])\n const result = await runHook(\"pre-compact\", { sessionId: sid, projectDir, transcript })\n if (result?.text && event.system) {\n event.system.push({ type: \"text\", text: result.text })\n }\n } catch (err) {\n debug(\"v2 compaction hook failed:\", err)\n }\n })\n\n // experimental.idle: turn finished — capture fresh messages into memory.\n await session.hook(\"experimental.idle\", async (input: never) => {\n const event = input as unknown as { sessionID?: string }\n try {\n const sid = event.sessionID\n if (!sid || typeof session.context !== \"function\") return\n const flat = await session.context({ sessionID: sid })\n const fresh = state.freshSlice(flat, (m) => m.id, sid)\n const payloadMessages: Array<{ role?: string; text?: string }> = []\n const toolEvents: ToolEvent[] = []\n for (const m of fresh) {\n const mapped = flatToPayload(m)\n if (mapped.text?.trim()) payloadMessages.push({ role: mapped.role, text: mapped.text })\n for (const t of mapped.tools) toolEvents.push(t)\n }\n if (payloadMessages.length === 0 && toolEvents.length === 0) return\n await runHook(\"turn-end\", {\n sessionId: sid,\n projectDir,\n messages: payloadMessages,\n toolEvents,\n })\n } catch (err) {\n debug(\"v2 idle hook failed:\", err)\n }\n })\n\n debug(\"v2 setup complete, projectDir:\", projectDir)\n}\n\n// ---------------------------------------------------------------------------\n// dual-generation entrypoint\n// ---------------------------------------------------------------------------\n\nconst geoplana = {\n id: \"geoplana\",\n setup: setupV2,\n server: createGeoplanaPlugin,\n}\n\n// opencode V1 reads `default` (object with server()), V2 validates { id, setup }.\nexport default geoplana\nexport { geoplana as Geoplana }\n"],"mappings":";AAoBA,SAAS,aAAa;AAWtB,SAAS,cAAwB;AAE/B,QAAM,MAAM,QAAQ,IAAI,gBAAgB,QAAQ,IAAI,gBAAgB;AACpE,SAAO,IAAI,MAAM,GAAG;AACtB;AAEA,SAAS,QAAQ,OAAe,SAA8D;AAC5F,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,CAAC,KAAK,GAAG,MAAM,IAAI,YAAY;AACrC,UAAM,QAAQ,MAAM,KAAM,CAAC,GAAG,QAAQ,QAAQ,KAAK,GAAG;AAAA,MACpD,OAAO,CAAC,QAAQ,QAAQ,aAAa,IAAI,YAAY,QAAQ;AAAA,MAC7D,KAAK,EAAE,GAAG,QAAQ,IAAI;AAAA,IACxB,CAAC;AACD,QAAI,UAAU;AACd,UAAM,OAAO,CAAC,QAA2B;AACvC,UAAI,CAAC,SAAS;AACZ,kBAAU;AACV,gBAAQ,GAAG;AAAA,MACb;AAAA,IACF;AACA,UAAM,QAAQ,WAAW,MAAM;AAC7B,YAAM,KAAK;AACX,WAAK,IAAI;AAAA,IACX,GAAG,GAAK;AAER,UAAM,SAAmB,CAAC;AAC1B,UAAM,OAAO,GAAG,QAAQ,CAAC,MAAM,OAAO,KAAK,CAAW,CAAC;AACvD,UAAM,GAAG,SAAS,MAAM;AACtB,mBAAa,KAAK;AAClB,WAAK,IAAI;AAAA,IACX,CAAC;AACD,UAAM,GAAG,SAAS,MAAM;AACtB,mBAAa,KAAK;AAClB,YAAM,OAAO,OAAO,OAAO,MAAM,EAAE,SAAS,MAAM,EAAE,KAAK;AACzD,UAAI,CAAC,KAAM,QAAO,KAAK,IAAI;AAC3B,UAAI;AACF,aAAK,KAAK,MAAM,IAAI,CAAe;AAAA,MACrC,QAAQ;AACN,aAAK,EAA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AAAA,MACvD;AAAA,IACF,SAAS,KAAK;AACZ,YAAM,8BAA8B,GAAG;AAAA,IACzC;AAAA,EACF,CAAC;AAGD,QAAM,QAAQ,KAAK,qBAAqB,OAAO,UAAiB;AAC9D,UAAM,QAAQ;AACd,QAAI;AACF,YAAM,MAAM,MAAM;AAClB,UAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,WAAY;AACnD,YAAM,OAAO,MAAM,QAAQ,QAAQ,EAAE,WAAW,IAAI,CAAC;AACrD,YAAM,QAAQ,MAAM,WAAW,MAAM,CAAC,MAAM,EAAE,IAAI,GAAG;AACrD,YAAM,kBAA2D,CAAC;AAClE,YAAM,aAA0B,CAAC;AACjC,iBAAW,KAAK,OAAO;AACrB,cAAM,SAAS,cAAc,CAAC;AAC9B,YAAI,OAAO,MAAM,KAAK,EAAG,iBAAgB,KAAK,EAAE,MAAM,OAAO,MAAM,MAAM,OAAO,KAAK,CAAC;AACtF,mBAAW,KAAK,OAAO,MAAO,YAAW,KAAK,CAAC;AAAA,MACjD;AACA,UAAI,gBAAgB,WAAW,KAAK,WAAW,WAAW,EAAG;AAC7D,YAAM,QAAQ,YAAY;AAAA,QACxB,WAAW;AAAA,QACX;AAAA,QACA,UAAU;AAAA,QACV;AAAA,MACF,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,YAAM,wBAAwB,GAAG;AAAA,IACnC;AAAA,EACF,CAAC;AAED,QAAM,kCAAkC,UAAU;AACpD;AAMA,IAAM,WAAW;AAAA,EACf,IAAI;AAAA,EACJ,OAAO;AAAA,EACP,QAAQ;AACV;AAGA,IAAO,mBAAQ;","names":[]}
1
+ {"version":3,"sources":["../../../adapters/opencode/index.ts"],"sourcesContent":["/**\n * geoplana shim for opencode.\n *\n * This file contains NO business logic: it only translates opencode's\n * in-process plugin events into `geoplana hook <event>` external command\n * calls — exactly the same universal hook core that claude code uses via\n * declarative settings.json hooks.\n *\n * Entrypoint shape (one file, both generations):\n * - opencode V1 loads `default` and, when it is an object, calls `server()`\n * (verified in the V1 loader: `readV1Plugin` accepts an object carrying\n * `id` + `server()` from 1.16.2 on, before falling back to legacy calls).\n * - opencode V2 decodes `default` as `{ id, setup }` (its schema rejects\n * function exports outright: \"Expected object\") and calls `setup(ctx)`.\n * Shipping `{ id, setup, server }` therefore satisfies both hosts; the\n * default export is never invoked as a function.\n *\n * The shim never throws: a memory failure must not break a coding session.\n * Set GEOPLANA_DEBUG=1 to log failures to stderr.\n */\nimport { spawn } from \"node:child_process\"\n\n// ---------------------------------------------------------------------------\n// universal hook invocation\n// ---------------------------------------------------------------------------\n\ninterface HookOutput {\n text?: string | null\n [key: string]: unknown\n}\n\nfunction hookCommand(): string[] {\n // PLANARIA_CMD: legacy env name from before the geoplana rename\n const cmd = process.env.GEOPLANA_CMD ?? process.env.PLANARIA_CMD ?? \"geoplana\"\n return cmd.split(\" \")\n}\n\nfunction runHook(event: string, payload: Record<string, unknown>): Promise<HookOutput | null> {\n return new Promise((resolve) => {\n const [bin, ...prefix] = hookCommand()\n const child = spawn(bin!, [...prefix, \"hook\", event], {\n stdio: [\"pipe\", \"pipe\", debugEnabled() ? \"inherit\" : \"ignore\"],\n env: { ...process.env },\n })\n let settled = false\n const done = (out: HookOutput | null) => {\n if (!settled) {\n settled = true\n resolve(out)\n }\n }\n const timer = setTimeout(() => {\n child.kill()\n done(null)\n }, 20000)\n\n const chunks: Buffer[] = []\n child.stdout.on(\"data\", (c) => chunks.push(c as Buffer))\n child.on(\"error\", () => {\n clearTimeout(timer)\n done(null)\n })\n child.on(\"close\", () => {\n clearTimeout(timer)\n const text = Buffer.concat(chunks).toString(\"utf8\").trim()\n if (!text) return done(null)\n try {\n done(JSON.parse(text) as HookOutput)\n } catch {\n done({ text })\n }\n })\n child.stdin.write(JSON.stringify(payload))\n child.stdin.end()\n })\n}\n\n// ---------------------------------------------------------------------------\n// opencode structural types (defensive, minimal)\n// ---------------------------------------------------------------------------\n\ninterface Part {\n type: string\n text?: string\n tool?: string\n state?: { input?: Record<string, unknown> }\n}\n\n/** V1 client / V2 context-hook message: { info, parts }. */\ninterface Message {\n info?: { id?: string; role?: string; sessionID?: string }\n parts?: Part[]\n}\n\n/** V2 `ctx.session.context()` message: flat tagged record. */\ninterface FlatMessage {\n id?: string\n type?: string\n role?: string\n text?: string\n content?: Array<{ type?: string; text?: string; name?: string; state?: { input?: unknown } }>\n}\n\ninterface ToolEvent {\n tool?: string\n files?: string[]\n command?: string\n error?: string\n}\n\ninterface OpencodeClient {\n session: {\n messages(input: { path: { id: string } }): Promise<{ data?: Message[] }>\n }\n}\n\n/** V1 plugin input (also what V1 `server()` receives). */\ninterface PluginContext {\n client: OpencodeClient\n directory?: string\n session?: { hook?: (name: string, fn: (event: unknown) => unknown) => void }\n}\n\n/** V2 hook event bases: `context` / `compaction` share the request shape. */\ninterface V2SessionRequestEvent {\n sessionID?: string\n system?: Array<{ type?: string; text?: string }>\n messages?: Message[]\n}\n\ninterface V2SessionDomain {\n hook(name: string, callback: (input: never) => Promise<void>): Promise<unknown> | undefined\n context(input: { sessionID: string }): Promise<FlatMessage[]>\n}\n\n/** V2 plugin context (promise API) — only what the shim uses. */\ninterface V2PluginContext {\n location?: { directory?: string }\n options?: unknown\n session?: V2SessionDomain\n}\n\n// ---------------------------------------------------------------------------\n\n// PLANARIA_DEBUG / PLANARIA_RECALL: legacy env names from before the rename\nconst debugEnabled = () => Boolean(process.env.GEOPLANA_DEBUG ?? process.env.PLANARIA_DEBUG)\n\nconst debug = (...args: unknown[]) => {\n if (debugEnabled()) console.error(\"[geoplana]\", ...args)\n}\n\nfunction messageText(m: Message): string {\n return (m.parts ?? [])\n .filter((p) => p.type === \"text\" && p.text)\n .map((p) => p.text!)\n .join(\"\\n\")\n}\n\nfunction serializeTranscript(messages: Message[]): string {\n return messages\n .map((m) => {\n const role = m.info?.role ?? \"unknown\"\n const text = messageText(m)\n const tools = (m.parts ?? [])\n .filter((p) => p.type === \"tool\")\n .map((p) => `[tool:${p.tool ?? \"?\"}] ${JSON.stringify(p.state?.input ?? {})}`)\n .join(\"\\n\")\n return [`## ${role}`, text, tools].filter(Boolean).join(\"\\n\")\n })\n .join(\"\\n\\n\")\n}\n\nfunction lastUserMessage(messages: Message[]): Message | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]?.info?.role === \"user\") return messages[i]\n }\n return undefined\n}\n\nfunction inject(output: { messages: Message[] }, text: string): void {\n const target = lastUserMessage(output.messages)\n if (!target) return\n target.parts = target.parts ?? []\n target.parts.unshift({ type: \"text\", text })\n}\n\nfunction extractFiles(input: Record<string, unknown>): string[] | undefined {\n for (const key of [\"filePath\", \"file_path\", \"path\", \"files\"]) {\n const value = input[key]\n if (typeof value === \"string\") return [value]\n if (Array.isArray(value)) return value.filter((v): v is string => typeof v === \"string\")\n }\n return undefined\n}\n\nfunction toolEventFromInput(tool: string | undefined, input: unknown): ToolEvent {\n const rec = (input ?? {}) as Record<string, unknown>\n return {\n tool,\n files: extractFiles(rec),\n command: typeof rec.command === \"string\" ? rec.command : undefined,\n }\n}\n\n/** Map a flat V2 message to capture payload entries (role text + tool events). */\nfunction flatToPayload(m: FlatMessage): { text?: string; role?: string; tools: ToolEvent[] } {\n const role = m.type ?? m.role\n const tools: ToolEvent[] = []\n if (m.type === \"user\" || m.type === \"system\") {\n return { role, text: m.text, tools }\n }\n const content = m.content ?? []\n const texts: string[] = []\n if (m.text) texts.push(m.text)\n for (const item of content) {\n if (item.type === \"text\" && item.text) texts.push(item.text)\n if (item.type === \"tool\") tools.push(toolEventFromInput(item.name, item.state?.input))\n }\n return { role, text: texts.join(\"\\n\"), tools }\n}\n\n/** Shared per-session state for one loaded plugin instance (V1 or V2). */\nfunction createSessionState() {\n const injected = new Set<string>()\n const lastCaptured = new Map<string, string>()\n\n async function sessionStartInject(\n sessionId: string,\n output: { messages: Message[] },\n projectDir?: string,\n ): Promise<void> {\n if (injected.has(sessionId)) return\n injected.add(sessionId)\n const result = await runHook(\"session-start\", { sessionId, projectDir })\n if (result?.text) inject(output, result.text)\n }\n\n async function recallInject(\n sessionId: string,\n output: { messages: Message[] },\n projectDir?: string,\n ): Promise<void> {\n if ((process.env.GEOPLANA_RECALL ?? process.env.PLANARIA_RECALL) !== \"1\") return\n const userText = messageText(lastUserMessage(output.messages) ?? {})\n if (userText.length < 8) return\n const result = await runHook(\"recall\", { sessionId, projectDir, userText })\n if (result?.text) inject(output, result.text)\n }\n\n /** Slice not-yet-seen messages (shared by V1 idle and V2 idle paths). */\n function freshSlice<T>(\n items: T[],\n idOf: (item: T) => string | undefined,\n sessionId: string,\n ): T[] {\n const seen = lastCaptured.get(sessionId)\n const start = seen ? items.findIndex((item) => idOf(item) === seen) + 1 : 0\n const fresh = items.slice(Math.max(start, 0)).slice(-10)\n const last = items.length > 0 ? idOf(items[items.length - 1] as T) : undefined\n if (last) lastCaptured.set(sessionId, last)\n return fresh\n }\n\n return { injected, sessionStartInject, recallInject, freshSlice }\n}\n\n// ---------------------------------------------------------------------------\n// V1: hooks object returned from `server(input, options)`\n// ---------------------------------------------------------------------------\n\nexport async function createGeoplanaPlugin(ctx: PluginContext) {\n const projectDir = ctx.directory\n const state = createSessionState()\n debug(\"v1 server() entry, projectDir:\", projectDir)\n\n async function turnEnd(sessionId: string): Promise<void> {\n const res = await ctx.client.session.messages({ path: { id: sessionId } })\n const messages = res.data ?? []\n const fresh = state.freshSlice(messages, (m) => m.info?.id, sessionId)\n\n const payloadMessages: Array<{ role?: string; text?: string }> = []\n const toolEvents: ToolEvent[] = []\n for (const m of fresh) {\n const text = messageText(m)\n if (text.trim()) payloadMessages.push({ role: m.info?.role, text })\n for (const part of m.parts ?? []) {\n if (part.type !== \"tool\") continue\n toolEvents.push(toolEventFromInput(part.tool, part.state?.input))\n }\n }\n await runHook(\"turn-end\", { sessionId, projectDir, messages: payloadMessages, toolEvents })\n }\n\n const v1Hooks = {\n \"experimental.chat.messages.transform\": async (\n _input: Record<string, never>,\n output: { messages: Message[] },\n ) => {\n try {\n const sid = output.messages.find((m) => m.info?.sessionID)?.info?.sessionID\n if (!sid) return\n await state.sessionStartInject(sid, output, projectDir)\n await state.recallInject(sid, output, projectDir)\n } catch (err) {\n debug(\"messages.transform failed:\", err)\n }\n },\n\n \"experimental.session.compacting\": async (\n input: { sessionID?: string },\n output: { context: string[]; prompt?: string },\n ) => {\n try {\n if (!input.sessionID) return\n const res = await ctx.client.session.messages({ path: { id: input.sessionID } })\n const transcript = serializeTranscript(res.data ?? [])\n const result = await runHook(\"pre-compact\", {\n sessionId: input.sessionID,\n projectDir,\n transcript,\n })\n if (result?.text) output.context.push(result.text)\n } catch (err) {\n debug(\"compacting hook failed:\", err)\n }\n },\n\n event: async ({ event }: { event: { type: string; properties?: Record<string, unknown> } }) => {\n try {\n if (event.type !== \"session.idle\") return\n const sid =\n (event.properties?.sessionID as string | undefined) ??\n (event.properties?.id as string | undefined)\n if (!sid) return\n await turnEnd(sid)\n } catch (err) {\n debug(\"event hook failed:\", err)\n }\n },\n }\n\n return v1Hooks\n}\n\n// ---------------------------------------------------------------------------\n// V2: `setup(ctx)` — ctx.session.hook / ctx.session.context (promise API)\n// ---------------------------------------------------------------------------\n\nasync function setupV2(ctx: V2PluginContext): Promise<void> {\n const projectDir = ctx.location?.directory\n const state = createSessionState()\n\n const session = ctx.session\n if (!session || typeof session.hook !== \"function\") {\n debug(\"v2 setup: session domain unavailable; hooks not registered\")\n return\n }\n\n // context: runs immediately before each model request — inject memories.\n await session.hook(\"context\", async (input: never) => {\n const event = input as unknown as V2SessionRequestEvent\n try {\n const sid = event.sessionID\n if (!sid || !event.messages) return\n const output = { messages: event.messages }\n await state.sessionStartInject(sid, output, projectDir)\n await state.recallInject(sid, output, projectDir)\n } catch (err) {\n debug(\"v2 context hook failed:\", err)\n }\n })\n\n // compaction: archive the transcript and append the structured template.\n await session.hook(\"compaction\", async (input: never) => {\n const event = input as unknown as V2SessionRequestEvent\n try {\n const sid = event.sessionID\n if (!sid) return\n const transcript = serializeTranscript(event.messages ?? [])\n const result = await runHook(\"pre-compact\", { sessionId: sid, projectDir, transcript })\n if (result?.text && event.system) {\n event.system.push({ type: \"text\", text: result.text })\n }\n } catch (err) {\n debug(\"v2 compaction hook failed:\", err)\n }\n })\n\n // experimental.idle: turn finished — capture fresh messages into memory.\n await session.hook(\"experimental.idle\", async (input: never) => {\n const event = input as unknown as { sessionID?: string }\n try {\n const sid = event.sessionID\n if (!sid || typeof session.context !== \"function\") return\n const flat = await session.context({ sessionID: sid })\n const fresh = state.freshSlice(flat, (m) => m.id, sid)\n const payloadMessages: Array<{ role?: string; text?: string }> = []\n const toolEvents: ToolEvent[] = []\n for (const m of fresh) {\n const mapped = flatToPayload(m)\n if (mapped.text?.trim()) payloadMessages.push({ role: mapped.role, text: mapped.text })\n for (const t of mapped.tools) toolEvents.push(t)\n }\n if (payloadMessages.length === 0 && toolEvents.length === 0) return\n await runHook(\"turn-end\", {\n sessionId: sid,\n projectDir,\n messages: payloadMessages,\n toolEvents,\n })\n } catch (err) {\n debug(\"v2 idle hook failed:\", err)\n }\n })\n\n debug(\"v2 setup complete, projectDir:\", projectDir)\n}\n\n// ---------------------------------------------------------------------------\n// dual-generation entrypoint\n// ---------------------------------------------------------------------------\n\nconst geoplana = {\n id: \"geoplana\",\n setup: setupV2,\n server: createGeoplanaPlugin,\n}\n\n// opencode V1 reads `default` (object with server()), V2 validates { id, setup }.\nexport default geoplana\nexport { geoplana as Geoplana }\n"],"mappings":";AAoBA,SAAS,aAAa;AAWtB,SAAS,cAAwB;AAE/B,QAAM,MAAM,QAAQ,IAAI,gBAAgB,QAAQ,IAAI,gBAAgB;AACpE,SAAO,IAAI,MAAM,GAAG;AACtB;AAEA,SAAS,QAAQ,OAAe,SAA8D;AAC5F,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,CAAC,KAAK,GAAG,MAAM,IAAI,YAAY;AACrC,UAAM,QAAQ,MAAM,KAAM,CAAC,GAAG,QAAQ,QAAQ,KAAK,GAAG;AAAA,MACpD,OAAO,CA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MAAM,KAAK,EAAG,iBAAgB,KAAK,EAAE,MAAM,OAAO,MAAM,MAAM,OAAO,KAAK,CAAC;AACtF,mBAAW,KAAK,OAAO,MAAO,YAAW,KAAK,CAAC;AAAA,MACjD;AACA,UAAI,gBAAgB,WAAW,KAAK,WAAW,WAAW,EAAG;AAC7D,YAAM,QAAQ,YAAY;AAAA,QACxB,WAAW;AAAA,QACX;AAAA,QACA,UAAU;AAAA,QACV;AAAA,MACF,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,YAAM,wBAAwB,GAAG;AAAA,IACnC;AAAA,EACF,CAAC;AAED,QAAM,kCAAkC,UAAU;AACpD;AAMA,IAAM,WAAW;AAAA,EACf,IAAI;AAAA,EACJ,OAAO;AAAA,EACP,QAAQ;AACV;AAGA,IAAO,mBAAQ;","names":[]}
@@ -9,7 +9,13 @@ var MEMORY_TYPES = [
9
9
  "error"
10
10
  ];
11
11
  var MemoryTypeSchema = z.enum(MEMORY_TYPES);
12
- var EPISODE_KINDS = ["message", "tool_event", "compaction_snapshot", "note"];
12
+ var EPISODE_KINDS = [
13
+ "message",
14
+ "tool_event",
15
+ "compaction_snapshot",
16
+ "note",
17
+ "query"
18
+ ];
13
19
  var EpisodeKindSchema = z.enum(EPISODE_KINDS);
14
20
  var SaveMemoryInputSchema = z.object({
15
21
  namespace: z.string().min(1),
@@ -41,7 +47,19 @@ var SearchInputSchema = z.object({
41
47
  boostTypes: z.array(MemoryTypeSchema).optional(),
42
48
  limit: z.number().int().min(1).max(100).default(10),
43
49
  includeEpisodes: z.boolean().default(true),
44
- includeSuperseded: z.boolean().default(false)
50
+ includeSuperseded: z.boolean().default(false),
51
+ /**
52
+ * session the search runs in; recorded on the query-log episode so the
53
+ * outcome attribution can tell a repeat of the same query apart from a
54
+ * different session asking it
55
+ */
56
+ sessionId: z.string().optional()
57
+ });
58
+ var FeedbackInputSchema = z.object({
59
+ id: z.string().min(1).describe("the memory that was used"),
60
+ useful: z.boolean().describe(
61
+ "true: the memory helped; false: it was noise. Useful feedback also credits the search that surfaced the memory."
62
+ )
45
63
  });
46
64
  var CaptureInputSchema = z.object({
47
65
  namespace: z.string().min(1),
@@ -73,8 +91,9 @@ export {
73
91
  SaveMemoryInputSchema,
74
92
  UpdateMemoryInputSchema,
75
93
  SearchInputSchema,
94
+ FeedbackInputSchema,
76
95
  CaptureInputSchema,
77
96
  ContextInputSchema,
78
97
  ResolveConflictInputSchema
79
98
  };
80
- //# sourceMappingURL=chunk-6BJCPRH7.js.map
99
+ //# sourceMappingURL=chunk-4JZEJXMA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import { z } from \"zod\"\n\n// ---------------------------------------------------------------------------\n// Enums\n// ---------------------------------------------------------------------------\n\nexport const MEMORY_TYPES = [\n \"fact\",\n \"preference\",\n \"decision\",\n \"context\",\n \"instruction\",\n \"error\",\n] as const\nexport const MemoryTypeSchema = z.enum(MEMORY_TYPES)\nexport type MemoryType = z.infer<typeof MemoryTypeSchema>\n\nexport const EPISODE_KINDS = [\n \"message\",\n \"tool_event\",\n \"compaction_snapshot\",\n \"note\",\n \"query\",\n] as const\nexport const EpisodeKindSchema = z.enum(EPISODE_KINDS)\nexport type EpisodeKind = z.infer<typeof EpisodeKindSchema>\n\n// ---------------------------------------------------------------------------\n// Entities\n// ---------------------------------------------------------------------------\n\nexport interface Memory {\n id: string\n namespace: string\n type: MemoryType\n content: string\n summary: string | null\n tags: string[]\n metadata: Record<string, unknown>\n importance: number\n pinned: boolean\n supersededBy: string | null\n sourceEpisodeId: string | null\n contentHash: string\n accessCount: number\n createdAt: number\n updatedAt: number\n lastAccessedAt: number | null\n}\n\nexport interface Episode {\n id: string\n namespace: string\n sessionId: string | null\n kind: EpisodeKind\n content: string\n metadata: Record<string, unknown>\n contentHash: string\n createdAt: number\n /** warm-tier: content stored gzipped, FTS row removed */\n compressed: boolean\n /** short excerpt kept for browsing compressed episodes */\n digest: string | null\n}\n\n// ---------------------------------------------------------------------------\n// Inputs (zod-validated at every interface boundary: MCP / HTTP / CLI)\n// ---------------------------------------------------------------------------\n\nexport const SaveMemoryInputSchema = z.object({\n namespace: z.string().min(1),\n type: MemoryTypeSchema,\n content: z.string().min(1),\n summary: z.string().optional(),\n tags: z.array(z.string()).default([]),\n metadata: z.record(z.unknown()).default({}),\n importance: z.number().min(0).max(1).default(0.5),\n pinned: z.boolean().default(false),\n supersedes: z.string().optional().describe(\"id of an existing memory this one replaces\"),\n sourceEpisodeId: z.string().optional(),\n})\nexport type SaveMemoryInput = z.input<typeof SaveMemoryInputSchema>\n\nexport const UpdateMemoryInputSchema = z.object({\n content: z.string().min(1).optional(),\n summary: z.string().nullable().optional(),\n type: MemoryTypeSchema.optional(),\n tags: z.array(z.string()).optional(),\n metadata: z.record(z.unknown()).optional(),\n importance: z.number().min(0).max(1).optional(),\n pinned: z.boolean().optional(),\n})\nexport type UpdateMemoryInput = z.input<typeof UpdateMemoryInputSchema>\n\nexport const SearchInputSchema = z.object({\n query: z.string().min(1),\n namespaces: z.array(z.string()).optional().describe(\"filter to these namespaces; omitted = all\"),\n types: z.array(MemoryTypeSchema).optional(),\n tags: z.array(z.string()).optional(),\n /** soft-relevant memory types: boosted in ranking, never filtered out */\n boostTypes: z.array(MemoryTypeSchema).optional(),\n limit: z.number().int().min(1).max(100).default(10),\n includeEpisodes: z.boolean().default(true),\n includeSuperseded: z.boolean().default(false),\n /**\n * session the search runs in; recorded on the query-log episode so the\n * outcome attribution can tell a repeat of the same query apart from a\n * different session asking it\n */\n sessionId: z.string().optional(),\n})\nexport type SearchInput = z.input<typeof SearchInputSchema>\n\nexport const FeedbackInputSchema = z.object({\n id: z.string().min(1).describe(\"the memory that was used\"),\n useful: z\n .boolean()\n .describe(\n \"true: the memory helped; false: it was noise. Useful feedback also credits the search that surfaced the memory.\",\n ),\n})\nexport type FeedbackInput = z.input<typeof FeedbackInputSchema>\n\nexport const CaptureInputSchema = z.object({\n namespace: z.string().min(1),\n sessionId: z.string().optional(),\n kind: EpisodeKindSchema,\n content: z.string().min(1),\n metadata: z.record(z.unknown()).default({}),\n extract: z.boolean().default(true).describe(\"run structured extraction into memories\"),\n})\nexport type CaptureInput = z.input<typeof CaptureInputSchema>\n\nexport const ContextInputSchema = z.object({\n namespaces: z.array(z.string()).min(1).describe(\"e.g. ['global', 'project:/repo']\"),\n maxItems: z.number().int().min(1).max(100).default(20),\n includePinned: z.boolean().default(true),\n includeRecent: z.boolean().default(true),\n})\nexport type ContextInput = z.input<typeof ContextInputSchema>\n\n// ---------------------------------------------------------------------------\n// Outputs\n// ---------------------------------------------------------------------------\n\nexport interface SearchHit {\n layer: \"memory\" | \"episode\"\n id: string\n /** higher is better */\n score: number\n snippet: string\n memory?: Memory\n episode?: Episode\n /**\n * which storage branch produced this candidate: \"fts\" = the trigram\n * index, \"like\" = the supplementary LIKE branch (the only branch that\n * can match a two-character word). The share of \"like\" hits tells\n * whether the fallback earns its keep.\n */\n branch?: \"fts\" | \"like\"\n /**\n * the kind of namespace the hit lives in (never the raw path). The\n * share of session-scoped hits at top ranks is the evidence for/against\n * a scope weight in the ranking.\n */\n nsKind?: \"global\" | \"project\" | \"session\" | \"other\"\n /**\n * true when the hit matches only expansion-added terms: without query\n * expansion this query would have found nothing. The share of these\n * hits measures what the concept table rescues.\n */\n expansionOnly?: boolean\n /** ids of co-surfacing memories that look conflicting (read-time annotation) */\n possibleConflictWith?: string[]\n}\n\nexport interface ContextBundle {\n text: string\n items: Array<{\n id: string\n type: MemoryType\n summary: string\n possibleConflictWith?: string[]\n }>\n}\n\nexport interface CaptureResult {\n episode: Episode\n deduplicated: boolean\n extracted: Memory[]\n}\n\n// ---------------------------------------------------------------------------\n// Conflict detection & resolution\n// ---------------------------------------------------------------------------\n\nexport interface ConflictCandidate {\n id: string\n type: MemoryType\n summary: string\n content: string\n importance: number\n createdAt: number\n}\n\nexport const ResolveConflictInputSchema = z.object({\n newId: z.string().describe(\"the newly saved memory\"),\n oldId: z.string().describe(\"the conflicting existing memory\"),\n action: z\n .enum([\"keep-new\", \"keep-old\", \"keep-both\"])\n .describe(\n \"keep-new: supersede the old one; keep-old: delete the new one; keep-both: leave both active\",\n ),\n})\nexport type ResolveConflictInput = z.input<typeof ResolveConflictInputSchema>\n"],"mappings":";AAAA,SAAS,SAAS;AAMX,IAAM,eAAe;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACO,IAAM,mBAAmB,EAAE,KAAK,YAAY;AAG5C,IAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACO,IAAM,oBAAoB,EAAE,KAAK,aAAa;AA6C9C,IAAM,wBAAwB,EAAE,OAAO;AAAA,EAC5C,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC3B,MAAM;AAAA,EACN,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACzB,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EACpC,UAAU,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EAC1C,YAAY,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,EAAE,QAAQ,GAAG;AAAA,EAChD,QAAQ,EAAE,QAAQ,EAAE,QAAQ,KAAK;AAAA,EACjC,YAAY,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,4CAA4C;AAAA,EACvF,iBAAiB,EAAE,OAAO,EAAE,SAAS;AACvC,CAAC;AAGM,IAAM,0BAA0B,EAAE,OAAO;AAAA,EAC9C,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EACpC,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,EACxC,MAAM,iBAAiB,SAAS;AAAA,EAChC,MAAM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