open-memex 0.9.0-alpha.1 → 0.9.0-alpha.2
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.
- package/AGENTS.md +4 -1
- package/CHANGELOG.md +4 -0
- package/README.md +17 -3
- package/README.zh-CN.md +5 -2
- package/dist/.build-stamp +1 -1
- package/dist/cli.js +52 -3
- package/dist/doctor.js +2 -1
- package/dist/init.js +8 -3
- package/dist/mcp.js +15 -4
- package/dist/opencode-v2.js +1 -1
- package/dist/retrieve/inject.js +6 -0
- package/dist/retrieve/search.js +13 -2
- package/dist/review.js +7 -0
- package/dist/store/db.js +19 -0
- package/dist/store/lifecycle.js +8 -0
- package/dist/store/usage.js +151 -0
- package/dist/tools/memory.js +12 -2
- package/dist/tools/ops.js +55 -1
- package/docs/V2-DESIGN.md +1 -1
- package/docs/design/decisions.md +1 -1
- package/package.json +66 -66
- package/scripts/smoke-mcp.ts +40 -4
- package/scripts/test-full.ts +83 -0
- package/skills/open-memex/SKILL.md +9 -0
- package/src/cli.ts +54 -3
- package/src/doctor.ts +2 -1
- package/src/init.ts +8 -3
- package/src/mcp.ts +21 -3
- package/src/opencode-v2.ts +2 -2
- package/src/retrieve/inject.ts +7 -0
- package/src/retrieve/search.ts +19 -3
- package/src/review.ts +6 -0
- package/src/store/db.ts +20 -0
- package/src/store/lifecycle.ts +9 -0
- package/src/store/usage.ts +178 -0
- package/src/tools/memory.ts +14 -1
- package/src/tools/ops.ts +71 -1
package/AGENTS.md
CHANGED
|
@@ -12,7 +12,7 @@ via `prepublishOnly` — Node refuses `--experimental-strip-types` for files und
|
|
|
12
12
|
|
|
13
13
|
- **opencode host** loads `src/index.ts` under embedded **Bun**. SQLite here is `bun:sqlite` (built-in).
|
|
14
14
|
- **CLI** (`src/cli.ts`) and smoke tests run under **Node 22+** with `--experimental-strip-types`. SQLite here is `better-sqlite3` (native module).
|
|
15
|
-
- **MCP server** (`src/mcp.ts`, stdio) runs under **Node 22+** with `--experimental-strip-types`. It exposes the same
|
|
15
|
+
- **MCP server** (`src/mcp.ts`, stdio) runs under **Node 22+** with `--experimental-strip-types`. It exposes the same thirteen memory tools to any MCP client (VS Code Copilot, Cursor, Claude Code). **stdout is the protocol channel — never log to stdout in `mcp.ts`; diagnostics go to stderr.**
|
|
16
16
|
|
|
17
17
|
`src/store/db.ts` picks the backend at runtime by sniffing `globalThis.Bun`. Both backends share the same surface (`new Database(path)`, `.exec`, `.prepare().run/all/get`, `.close`). Any DB code you write must stay on that common subset — do not import `better-sqlite3` or `bun:sqlite` directly outside `db.ts`. The Node driver is pinned to the `better-sqlite3` 13 N-API line (D72): the pre-13 `node::ObjectWrap` build aborts intermittently on Node 24.19+ when a prepared statement is finalized by GC.
|
|
18
18
|
|
|
@@ -33,6 +33,7 @@ Consequences:
|
|
|
33
33
|
npm install # once
|
|
34
34
|
npm run typecheck # tsc --noEmit — the only lint/type gate
|
|
35
35
|
npm run cli -- where | list | search "q" | add ... | forget <id> | reindex
|
|
36
|
+
npm run cli -- useful <id...> # D77-L2: explicit useful signal + cumulative counters
|
|
36
37
|
npm run cli -- <command> --help # per-command help (AI assistants discover flags this way)
|
|
37
38
|
npm run cli -- sync-status # last sync time/kind + outbox drafts + repo review states + uncommitted files
|
|
38
39
|
npm run cli -- inventory [--format text|json|html] [--scope both] # what is remembered, in the open (D68); personal-bearing output refused inside a git worktree without --allow-personal
|
|
@@ -125,6 +126,8 @@ Layout: `memories/<scope_key>/<id>.md` (YAML frontmatter + body) + `index.db` (S
|
|
|
125
126
|
|
|
126
127
|
**Markdown files are the source of truth; `index.db` is rebuildable.** `syncScope()` (in `src/store/sync.ts`) reconciles the two by mtime on plugin load and before every CLI read. When adding new frontmatter fields, update `Frontmatter` in `src/store/markdown.ts`, the `memories` table in `src/store/db.ts`, and `upsertFromFile` in `src/store/sync.ts` together, and bump the reindex path.
|
|
127
128
|
|
|
129
|
+
D77-L2 counters are the one deliberate exception: `memory_usage` (in `index.db`, owned by `src/store/usage.ts`) holds `retrieved_count` / `useful_self` / `useful_team` keyed by memory id, is created with `CREATE TABLE IF NOT EXISTS` outside the versioned schema, and is NOT dropped by `rebuildIndexSchema` — accumulated telemetry has no Markdown source to rebuild from. They never go into frontmatter and never leave the machine. Only `memory_useful` (explicit), a human approve at review, and a supersede raise the useful side; passive retrieval (search/list/injection, opt-in via `record: true`) raises only `retrieved_count` — never "fix" this by counting exposure as useful.
|
|
130
|
+
|
|
128
131
|
## Scope keys
|
|
129
132
|
|
|
130
133
|
- `personal` scope key is literal `"personal"` (v1 called this `user`; renamed in v2, design §19).
|
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,10 @@ the `@alpha` tag are development snapshots and are not listed individually.
|
|
|
9
9
|
|
|
10
10
|
## [Unreleased]
|
|
11
11
|
|
|
12
|
+
## [0.9.0-alpha.2] - 2026-11-03
|
|
13
|
+
|
|
14
|
+
- D77-L2: measure usefulness by reuse (the D77 counters, layer 2). Each memory now carries local counters in a `memory_usage` table beside the rebuildable index (D77: counters live in SQLite, never in frontmatter, never off the machine): `retrieved_count` — incremented when a memory is actually returned by `memory_search`, `memory_list`, the CLI `search`/`list`, or the session-start injection — and the useful split, `useful_self` (personal memories and unpublished project drafts) vs `useful_team` (approved/published project memories). Only explicit signals raise the useful side: the new **`memory_useful`** tool (thirteenth MCP tool, seventh on the opencode plugin; also `open-memex useful <id...>`), a human approve at review (`promote` to approved), and a supersede. Passive exposure never counts as useful — the tool description, MCP handshake, READMEs, skill, and AGENTS.md all state the restraint so an agent that reads only one still behaves. `memory_usage` is created with `CREATE TABLE IF NOT EXISTS` outside the versioned schema and survives `rebuildIndexSchema` (ids come from the files); hard forget prunes the row, branch-switch removals do not. `memory_useful` returns counts plus `reuse_rate` (useful / retrieved, `n/a` when never retrieved). The D77-L3 reuse report (top reused, zero-reuse zombies, per-scope rates) remains open.
|
|
15
|
+
|
|
12
16
|
## [0.9.0-alpha.1] - 2026-11-03
|
|
13
17
|
|
|
14
18
|
- Session working-state note (D89 → D90, new minor line): one ephemeral per-project Markdown note for resuming an interrupted task — task summary, open files, last commands, where the work stands, next step. The agent writes it at wrap-up via the new **`memory_workingstate`** tool (now the **twelve** tools on both the opencode plugin and the MCP server), it surfaces once at session start next to the first-turn injection (framed as scratch, never knowledge), it never enters `memories/` or the retrieval index or the review ladder, and anything in it worth keeping goes through the normal propose-first flow. TTL defaults to 7 days (`workingStateTtlDays`; `workingStateEnabled` gates the whole feature — both flat keys, settable via `config set`). Expired notes stay silent at session start and are reported by `open-memex audit`; `open-memex wstate` (`--clear`) is the human surface. The write passes through `redact()` and `atomicWriteTextSync` like every path. One correction to D89's wording, recorded as D90: the opencode plugin API has no Stop hook, so the opencode write path is the instruction + tool branch (the agent refreshes the note when the user signals wrap-up); Claude Code's Stop hook waits for the Phase 2C native plugin.
|
package/README.md
CHANGED
|
@@ -444,8 +444,8 @@ If a secret slips through anyway, `open-memex forget <id>` deletes the memory.
|
|
|
444
444
|
|
|
445
445
|
## Tools the agent gets
|
|
446
446
|
|
|
447
|
-
The MCP server exposes
|
|
448
|
-
|
|
447
|
+
The MCP server exposes thirteen tools; the opencode native plugin exposes the
|
|
448
|
+
seven core ones (marked ●). The other six are the team-review workflow tools —
|
|
449
449
|
they only matter once you share memories through Git.
|
|
450
450
|
|
|
451
451
|
| Tool | What it does |
|
|
@@ -456,6 +456,7 @@ they only matter once you share memories through Git.
|
|
|
456
456
|
| ● `memory_supersede` | Replace a memory with a newer version (keeps a supersede chain) |
|
|
457
457
|
| ● `memory_forget` | Delete a memory by id (`soft=true` hides it instead — retracted, one-way) |
|
|
458
458
|
| ● `memory_workingstate` | Read/write/clear the per-project working-state note (§3.6, D89) — resumes an interrupted task; scratch state, never a memory |
|
|
459
|
+
| ● `memory_useful` | Mark a memory as useful (D77) — explicit confirmation only; exposure is counted separately as `retrieved_count` |
|
|
459
460
|
| `memory_status` | Show the sync queue: outbox drafts, repo review states, uncommitted files |
|
|
460
461
|
| `memory_submit` | Move named drafts into the repo memory dir (local branch + commit) |
|
|
461
462
|
| `memory_propose` | Copy personal memories into the project scope as review candidates |
|
|
@@ -467,6 +468,19 @@ So an MCP-connected editor always has the full set; opencode's plugin covers
|
|
|
467
468
|
capture and recall, and anything workflow-shaped goes through the CLI or an
|
|
468
469
|
MCP-connected editor.
|
|
469
470
|
|
|
471
|
+
**Usefulness is measured by reuse, not storage (D77).** Every memory carries
|
|
472
|
+
local counters: `retrieved_count` — how often it was actually handed to the
|
|
473
|
+
agent (search results, lists, the session-start injection) — and useful
|
|
474
|
+
counts, split into `useful_self` (personal memories, unpublished project
|
|
475
|
+
drafts) and `useful_team` (approved/published project memories). Only
|
|
476
|
+
explicit signals raise the useful side: `memory_useful` when a person
|
|
477
|
+
confirms it paid off, a human approval at review, or a supersede. Passive
|
|
478
|
+
exposure never counts as useful — a memory that merely showed up in results
|
|
479
|
+
has shown nothing yet. Same-side CLI surface: `open-memex useful <id...>`.
|
|
480
|
+
Counters live in the local SQLite index only (never in the Markdown files,
|
|
481
|
+
never off this machine); the reuse report (top reused, zero-reuse zombies,
|
|
482
|
+
per-scope rates) rides the D77-L3 follow-up.
|
|
483
|
+
|
|
470
484
|
## Memory types
|
|
471
485
|
|
|
472
486
|
Every memory has a `type` (what it is) and `tags` (what it's about). Eleven
|
|
@@ -950,7 +964,7 @@ config: if it has comments, add the `"plugin"` line manually.
|
|
|
950
964
|
Checks the Node version, config source, scope resolution for the current
|
|
951
965
|
directory, and storage writability; verifies VS Code hasn't disabled MCP;
|
|
952
966
|
then boots a real MCP server and runs `initialize` + `tools/list` against
|
|
953
|
-
it — all
|
|
967
|
+
it — all thirteen tools must show up. It also reports pre-rename `my-o-memory`
|
|
954
968
|
leftovers if any editor config still references the old package name.
|
|
955
969
|
|
|
956
970
|
## FAQ
|
package/README.zh-CN.md
CHANGED
|
@@ -286,7 +286,7 @@ open-memex capture --dry-run "…"
|
|
|
286
286
|
|
|
287
287
|
## 助手拿到的工具
|
|
288
288
|
|
|
289
|
-
MCP
|
|
289
|
+
MCP 服务器暴露十三个工具;opencode 原生插件暴露其中七个核心的(标 ●)。另外六个是团队评审工作流工具——只有当你通过 Git 共享记忆时才用得上。
|
|
290
290
|
|
|
291
291
|
| 工具 | 做什么 |
|
|
292
292
|
|---|---|
|
|
@@ -296,6 +296,7 @@ MCP 服务器暴露十二个工具;opencode 原生插件暴露其中六个核
|
|
|
296
296
|
| ● `memory_supersede` | 用新版本替换一条记忆(保留 supersede 链) |
|
|
297
297
|
| ● `memory_forget` | 按 id 删除一条记忆(`soft=true` 改为隐藏——retracted,单向) |
|
|
298
298
|
| ● `memory_workingstate` | 读/写/清除每项目的工作状态笔记(§3.6,D89)——让被中断的任务得以续接;只是草稿状态,永远不会成为记忆 |
|
|
299
|
+
| ● `memory_useful` | 确认一条记忆有用(D77)——只认显式确认;被动的搜索/列表出现只计入 `retrieved_count`,绝不算有用 |
|
|
299
300
|
| `memory_status` | 显示同步队列:outbox 草稿、仓库评审状态、未提交文件 |
|
|
300
301
|
| `memory_submit` | 把指定的草稿移进仓库记忆目录(本地分支 + 提交) |
|
|
301
302
|
| `memory_propose` | 把个人记忆复制到项目作用域,作为评审候选 |
|
|
@@ -305,6 +306,8 @@ MCP 服务器暴露十二个工具;opencode 原生插件暴露其中六个核
|
|
|
305
306
|
|
|
306
307
|
所以 MCP 接入的编辑器永远是全套;opencode 插件主攻捕获与回想,工作流类的事走 CLI 或 MCP 接入的编辑器。
|
|
307
308
|
|
|
309
|
+
**有用性靠复用来衡量,不靠存储量(D77)。** 每条记忆带本地计数器:`retrieved_count`——它真正被递交给助手的次数(搜索结果、清单、会话开始注入);有用计数则拆成 `useful_self`(个人记忆、未评审的项目草稿)和 `useful_team`(approved/published 的项目记忆)。只有显式信号会抬升有用侧:`memory_useful`(人确认它帮上忙时)、评审中的人为 approve、或一次 supersede。被动曝光永远不算有用——记忆只是出现在结果里,还不能说明任何事。同侧的人用入口:`open-memex useful <id...>`。计数器只存在本地 SQLite 索引里(不进 Markdown 文件、不出这台机器);复用报告(复用最多、零复用的"僵尸"、各作用域复用率)由 D77-L3 后续跟进。
|
|
310
|
+
|
|
308
311
|
## 记忆类型
|
|
309
312
|
|
|
310
313
|
每条记忆有一个 `type`(它是什么)和 `tags`(它关于什么)。内置十一种类型:
|
|
@@ -618,7 +621,7 @@ Windows 上已加载的 DLL 是锁定的:如果 open-memex 的 MCP 服务器
|
|
|
618
621
|
你的编辑器配置里有注释(JSONC)或 JSON 不合法,open-memex 永不重写它无法安全解析的文件。`init` 已经把要加的确切片段打印出来了——手动粘贴进去就好。opencode 配置同理:有注释时,手动把 `"plugin"` 那一行加上。
|
|
619
622
|
|
|
620
623
|
**感觉有问题——跑 `open-memex doctor`。**
|
|
621
|
-
它检查 Node 版本、配置来源、当前目录的作用域解析、存储可写性,并确认 VS Code 没有把 MCP 禁用;然后启动一个真实 MCP 服务器,对它跑 `initialize` + `tools/list
|
|
624
|
+
它检查 Node 版本、配置来源、当前目录的作用域解析、存储可写性,并确认 VS Code 没有把 MCP 禁用;然后启动一个真实 MCP 服务器,对它跑 `initialize` + `tools/list`——十三个工具必须全部出现。它还会报告改名之前遗留的 `my-o-memory` 引用(如果某编辑器配置里还留着旧包名的话)。
|
|
622
625
|
|
|
623
626
|
## 常见问题
|
|
624
627
|
|
package/dist/.build-stamp
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
a8f61bc31b972df3523d0cebe5e6664a9adc28108162385725a004ee6b116656
|
package/dist/cli.js
CHANGED
|
@@ -10,6 +10,7 @@ import { proposeMemories, promoteMemory, listConflicts, resolveConflict, formatR
|
|
|
10
10
|
import { getSyncStatus, formatSyncStatus, submitMemories } from "./submit.js";
|
|
11
11
|
import { getPrStatus, formatPrStatus, applyPrStatus } from "./github.js";
|
|
12
12
|
import { search, list, countList, hitStateLabel } from "./retrieve/search.js";
|
|
13
|
+
import { recordUseful, getUsage, reuseRate, usefulCount, usefulKindFor, deleteUsage } from "./store/usage.js";
|
|
13
14
|
import { DEFAULT_EXPANSIONS_WEIGHT } from "./retrieve/weights.js";
|
|
14
15
|
import { formatInventoryLine, truncationNote } from "./retrieve/display.js";
|
|
15
16
|
import { writeMemoryFile, readMemoryFile, ulid, msToRfc3339, normalizeAliases, } from "./store/markdown.js";
|
|
@@ -144,6 +145,17 @@ Retraction is one-way: a retracted memory cannot be set back to active
|
|
|
144
145
|
|
|
145
146
|
Example:
|
|
146
147
|
open-memex status 01ABC deprecated`,
|
|
148
|
+
useful: `Mark a memory as useful (D77): record that it demonstrably paid
|
|
149
|
+
off. Useful is split automatically — useful_self for personal memories and
|
|
150
|
+
unpublished project drafts, useful_team for approved/published project
|
|
151
|
+
memories. Only explicit confirmation counts; passive retrieval (search/
|
|
152
|
+
list/injection) is counted separately as retrieved_count, never as useful.
|
|
153
|
+
A supersede or a human approval also records a useful signal on its own.
|
|
154
|
+
|
|
155
|
+
Usage: open-memex useful <id...>
|
|
156
|
+
|
|
157
|
+
Example:
|
|
158
|
+
open-memex useful 01ABC`,
|
|
147
159
|
forget: `Delete a memory by id. With --soft, hide it instead: the memory
|
|
148
160
|
is retracted (out of lists and search, file kept). Retraction is one-way —
|
|
149
161
|
save the content as a new memory to bring it back. If the memory lives in
|
|
@@ -388,7 +400,7 @@ Example:
|
|
|
388
400
|
doctor: `Environment health check: Node version, config source, scope resolution,
|
|
389
401
|
storage writability, VS Code MCP enablement (settings.json + system policy),
|
|
390
402
|
then boots a real MCP server and runs initialize + tools/list against it —
|
|
391
|
-
all
|
|
403
|
+
all thirteen tools must show up.
|
|
392
404
|
|
|
393
405
|
Usage: open-memex doctor
|
|
394
406
|
|
|
@@ -429,6 +441,7 @@ Usage:
|
|
|
429
441
|
open-memex add "content" [--scope project|personal] [--type T] [--tag t1,t2]
|
|
430
442
|
open-memex supersede <id> "new content" [--type T] [--tag t1,t2]
|
|
431
443
|
open-memex status <id> active|deprecated|retracted|archived
|
|
444
|
+
open-memex useful <id...>
|
|
432
445
|
open-memex forget <id> [--soft]
|
|
433
446
|
open-memex propose <id...> --to project [--local-approve]
|
|
434
447
|
open-memex promote <id> [--reject] [--resubmit] [--note "..."] [--by NAME]
|
|
@@ -477,8 +490,8 @@ first-turn injection); \`--yes\` accepts all defaults, and non-terminal runs nev
|
|
|
477
490
|
\`open-memex config set <key> <value>\` changes those settings after install.
|
|
478
491
|
|
|
479
492
|
Once installed globally (\`npm i -g open-memex\`) the \`open-memex\` command is
|
|
480
|
-
available directly: \`open-memex mcp\` starts the stdio MCP server (
|
|
481
|
-
the opencode plugin's
|
|
493
|
+
available directly: \`open-memex mcp\` starts the stdio MCP server (13 tools, a superset of
|
|
494
|
+
the opencode plugin's seven memory_* tools); \`open-memex mcp --print-config <client>\`
|
|
482
495
|
prints a copy-paste MCP client config snippet.
|
|
483
496
|
|
|
484
497
|
Scope defaults to \`project\` (derived from cwd's git remote or path).
|
|
@@ -917,6 +930,7 @@ async function main() {
|
|
|
917
930
|
type: flags.type,
|
|
918
931
|
limit: flags.limit ? Number(flags.limit) : undefined,
|
|
919
932
|
include,
|
|
933
|
+
record: true,
|
|
920
934
|
});
|
|
921
935
|
const total = countList(s.key, { type: flags.type, include });
|
|
922
936
|
if (scopes.length > 1) {
|
|
@@ -960,6 +974,7 @@ async function main() {
|
|
|
960
974
|
limit: flags.limit ? Number(flags.limit) : undefined,
|
|
961
975
|
type: flags.type,
|
|
962
976
|
stats,
|
|
977
|
+
record: true,
|
|
963
978
|
});
|
|
964
979
|
if (explain && stats) {
|
|
965
980
|
console.log(`fts: ${stats.ftsQuery || "(empty query)"}`);
|
|
@@ -1168,9 +1183,43 @@ async function main() {
|
|
|
1168
1183
|
}
|
|
1169
1184
|
}
|
|
1170
1185
|
deleteFromIndex(id);
|
|
1186
|
+
// D77-L2: hard forget prunes the usage row with the memory (the tool
|
|
1187
|
+
// path does the same); branch-switch removals go through syncScope and
|
|
1188
|
+
// keep counters for that reason.
|
|
1189
|
+
deleteUsage(id);
|
|
1171
1190
|
console.log(`deleted ${id}`);
|
|
1172
1191
|
return;
|
|
1173
1192
|
}
|
|
1193
|
+
if (cmd === "useful") {
|
|
1194
|
+
// D77-L2: the explicit confirmation route for humans. Auto-split like
|
|
1195
|
+
// the memory_useful tool; unknown ids fail that id without touching
|
|
1196
|
+
// the rest of the batch.
|
|
1197
|
+
const ids = rest;
|
|
1198
|
+
if (ids.length === 0)
|
|
1199
|
+
usage();
|
|
1200
|
+
syncScope(project.key, "cli");
|
|
1201
|
+
syncScope(PERSONAL_SCOPE.key, "cli");
|
|
1202
|
+
let notFound = 0;
|
|
1203
|
+
for (const id of ids) {
|
|
1204
|
+
const row = db()
|
|
1205
|
+
.prepare(`SELECT scope, review_state FROM memories WHERE id = ?`)
|
|
1206
|
+
.get(id);
|
|
1207
|
+
if (!row) {
|
|
1208
|
+
console.error(`not found: ${id}`);
|
|
1209
|
+
notFound++;
|
|
1210
|
+
continue;
|
|
1211
|
+
}
|
|
1212
|
+
const kind = usefulKindFor(row.scope, row.review_state);
|
|
1213
|
+
recordUseful(id, kind, "tool");
|
|
1214
|
+
const u = getUsage(id);
|
|
1215
|
+
const rate = reuseRate(u);
|
|
1216
|
+
const useful = usefulCount(u);
|
|
1217
|
+
console.log(`useful (${kind}) ${id} — retrieved: ${u.retrieved_count}, useful_self: ${u.useful_self}, useful_team: ${u.useful_team}, reuse_rate: ${rate === null ? "n/a" : rate.toFixed(2)} (useful ${useful}/${u.retrieved_count})`);
|
|
1218
|
+
}
|
|
1219
|
+
if (notFound > 0)
|
|
1220
|
+
process.exit(1);
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1174
1223
|
/** Positional args with flags (and their values) skipped. */
|
|
1175
1224
|
function positionalArgs(argv) {
|
|
1176
1225
|
const out = [];
|
package/dist/doctor.js
CHANGED
|
@@ -13,7 +13,7 @@ import { resolveCwdScope } from "./scope.js";
|
|
|
13
13
|
import { MIN_NODE_VERSION, nativeDriverFloorMessage, nodeSupportsNativeDriver, } from "./runtime-floor.js";
|
|
14
14
|
import { db, backendName } from "./store/db.js";
|
|
15
15
|
import { LEGACY_PACKAGE_NAME, opencodeGlobalConfigPath, userMcpConfigPath } from "./init.js";
|
|
16
|
-
// D64: the MCP server exposes
|
|
16
|
+
// D64: the MCP server exposes thirteen tools; checking only the seven the
|
|
17
17
|
// opencode plugin carries let a half-registered server pass as healthy.
|
|
18
18
|
const EXPECTED_TOOLS = [
|
|
19
19
|
"memory_add",
|
|
@@ -21,6 +21,7 @@ const EXPECTED_TOOLS = [
|
|
|
21
21
|
"memory_list",
|
|
22
22
|
"memory_supersede",
|
|
23
23
|
"memory_forget",
|
|
24
|
+
"memory_useful",
|
|
24
25
|
"memory_workingstate",
|
|
25
26
|
"memory_status",
|
|
26
27
|
"memory_submit",
|
package/dist/init.js
CHANGED
|
@@ -51,9 +51,9 @@ const INSTRUCTIONS = `${MARKER}
|
|
|
51
51
|
|
|
52
52
|
You have a local memory MCP server (\`open-memex\`). Its tools are
|
|
53
53
|
\`memory_add\`, \`memory_search\`, \`memory_list\`, \`memory_supersede\`,
|
|
54
|
-
\`memory_forget\`, \`
|
|
55
|
-
\`memory_propose\`, \`memory_promote\`, \`memory_resolve\`,
|
|
56
|
-
always call them by these full names.
|
|
54
|
+
\`memory_forget\`, \`memory_useful\`, \`memory_workingstate\`, \`memory_status\`,
|
|
55
|
+
\`memory_submit\`, \`memory_propose\`, \`memory_promote\`, \`memory_resolve\`,
|
|
56
|
+
\`memory_pr_status\` — always call them by these full names.
|
|
57
57
|
|
|
58
58
|
- The server tells you when project outbox drafts are waiting for review — in
|
|
59
59
|
tool results. When it does (or when the user asks), call \`memory_status\`
|
|
@@ -90,6 +90,11 @@ always call them by these full names.
|
|
|
90
90
|
note — task summary, open files, last commands, where the work stands, next
|
|
91
91
|
step — so an interrupted task can resume in a fresh session. It is scratch
|
|
92
92
|
state, not durable knowledge: never save it as a memory.
|
|
93
|
+
- When a person confirms a memory was useful, or accepts work that clearly
|
|
94
|
+
relied on one, call \`memory_useful\` on it. NEVER call it just because a
|
|
95
|
+
memory appeared in search results or the session-start block: passive
|
|
96
|
+
exposure is counted separately and never counts as useful. Superseding a
|
|
97
|
+
memory or approving it at review already records its useful signal.
|
|
93
98
|
|
|
94
99
|
## Syncing project memories for review (D26)
|
|
95
100
|
|
package/dist/mcp.js
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Exposes the memory tools as the opencode plugin
|
|
5
5
|
* (memory_add / memory_search / memory_list / memory_supersede /
|
|
6
|
-
* memory_forget, plus memory_workingstate + memory_status /
|
|
7
|
-
* memory_propose / memory_promote / memory_resolve /
|
|
6
|
+
* memory_forget, plus memory_useful + memory_workingstate + memory_status /
|
|
7
|
+
* memory_submit / memory_propose / memory_promote / memory_resolve /
|
|
8
|
+
* memory_pr_status)
|
|
8
9
|
* over the Model Context Protocol, so any MCP client —
|
|
9
10
|
* VS Code Copilot Chat, Cursor, Claude Code, etc. — can use open-memex
|
|
10
11
|
* without a host-specific plugin.
|
|
@@ -29,7 +30,7 @@ import { loadConfig } from "./config.js";
|
|
|
29
30
|
import { resolveProjectScope, PERSONAL_SCOPE } from "./scope.js";
|
|
30
31
|
import { db } from "./store/db.js";
|
|
31
32
|
import { syncScope } from "./store/sync.js";
|
|
32
|
-
import { addMemory, searchMemories, listMemories, supersedeMemory, forgetMemory, statusMemories, submitMemoriesOp, proposeMemoriesOp, promoteMemoryOp, resolveMemoryOp, prStatusOp, workingStateMemory, memoryAddArgs, memorySearchArgs, memoryListArgs, memorySupersedeArgs, memoryForgetArgs, memoryStatusArgs, memorySubmitArgs, memoryProposeArgs, memoryPromoteArgs, memoryResolveArgs, memoryPrStatusArgs, memoryWorkingStateArgs, TOOL_DESCRIPTIONS, withOutboxNote, } from "./tools/ops.js";
|
|
33
|
+
import { addMemory, searchMemories, listMemories, supersedeMemory, forgetMemory, markMemoryUseful, statusMemories, submitMemoriesOp, proposeMemoriesOp, promoteMemoryOp, resolveMemoryOp, prStatusOp, workingStateMemory, memoryAddArgs, memorySearchArgs, memoryListArgs, memorySupersedeArgs, memoryForgetArgs, memoryStatusArgs, memorySubmitArgs, memoryProposeArgs, memoryPromoteArgs, memoryResolveArgs, memoryPrStatusArgs, memoryWorkingStateArgs, memoryUsefulArgs, TOOL_DESCRIPTIONS, withOutboxNote, } from "./tools/ops.js";
|
|
33
34
|
import { outboxDraftCount } from "./submit.js";
|
|
34
35
|
// Server version tracks package.json — never hardcode it here again.
|
|
35
36
|
// package.json sits two levels above this file in both layouts
|
|
@@ -53,7 +54,7 @@ const SERVER_VERSION = (() => {
|
|
|
53
54
|
*/
|
|
54
55
|
const SERVER_INSTRUCTIONS = `You are connected to an open-memex local memory MCP server.
|
|
55
56
|
Its tools are memory_add, memory_search, memory_list, memory_supersede,
|
|
56
|
-
memory_forget, memory_workingstate, memory_status, memory_submit,
|
|
57
|
+
memory_forget, memory_useful, memory_workingstate, memory_status, memory_submit,
|
|
57
58
|
memory_propose, memory_promote, memory_resolve, memory_pr_status — always call
|
|
58
59
|
them by these full names.
|
|
59
60
|
|
|
@@ -109,6 +110,11 @@ them by these full names.
|
|
|
109
110
|
files, last commands, where the work stands, next step — so an interrupted
|
|
110
111
|
task can resume. It is scratch state, not knowledge: do not save it as a
|
|
111
112
|
memory; durable conclusions still follow the propose-first flow above.
|
|
113
|
+
- When a person confirms a memory was useful, or accepted work that clearly
|
|
114
|
+
relied on one, call memory_useful on it. NEVER call memory_useful just
|
|
115
|
+
because a memory appeared in results or the session-start block — passive
|
|
116
|
+
exposure never counts as useful. (Superseding or approving a memory also
|
|
117
|
+
auto-records its useful signal; no need to duplicate those.)
|
|
112
118
|
`;
|
|
113
119
|
/** Adapt a framework-agnostic op result to an MCP tool response. */
|
|
114
120
|
function toMcp(p) {
|
|
@@ -193,6 +199,11 @@ export async function runMcpServer() {
|
|
|
193
199
|
inputSchema: z.object(memoryForgetArgs),
|
|
194
200
|
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },
|
|
195
201
|
}, withSync((args) => toMcp(withOutboxNote(getScope().key, forgetMemory(args), "call memory_status to review"))));
|
|
202
|
+
server.registerTool("memory_useful", {
|
|
203
|
+
description: TOOL_DESCRIPTIONS.memory_useful,
|
|
204
|
+
inputSchema: z.object(memoryUsefulArgs),
|
|
205
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
|
|
206
|
+
}, withSync((args) => toMcp(markMemoryUseful(args))));
|
|
196
207
|
server.registerTool("memory_status", {
|
|
197
208
|
description: TOOL_DESCRIPTIONS.memory_status,
|
|
198
209
|
inputSchema: z.object(memoryStatusArgs),
|
package/dist/opencode-v2.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { PLUGIN_ID, bootstrapPlugin, captureFromText, captureHandoff, injectOnce, surfaceWorkingStateOnce, } from "./plugin-core.js";
|
|
3
3
|
import { makeTools } from "./tools/memory.js";
|
|
4
|
-
/** Register the
|
|
4
|
+
/** Register the seven memory tools on a v2 host. */
|
|
5
5
|
async function registerTools(ctx, state) {
|
|
6
6
|
const tools = makeTools(() => state.scope, state.cfg);
|
|
7
7
|
await ctx.tool.transform((editor) => {
|
package/dist/retrieve/inject.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { list, hitStateLabel } from "./search.js";
|
|
2
|
+
import { recordRetrieved } from "../store/usage.js";
|
|
2
3
|
import { PERSONAL_SCOPE } from "../scope.js";
|
|
3
4
|
function oneLine(s, max = 240) {
|
|
4
5
|
const trimmed = s.replace(/\s+/g, " ").trim();
|
|
@@ -9,6 +10,11 @@ export function buildContextBlock(scope, cfg) {
|
|
|
9
10
|
const user = list(PERSONAL_SCOPE.key, { limit: cfg.maxProfileItems });
|
|
10
11
|
if (project.length === 0 && user.length === 0)
|
|
11
12
|
return null;
|
|
13
|
+
// D77-L2: the injection is a retrieval surface — the memories it puts in
|
|
14
|
+
// front of the agent were "returned", so they count as exposure. It must
|
|
15
|
+
// NOT touch the useful counters: passive surfacing never refreshes
|
|
16
|
+
// usefulness (D77).
|
|
17
|
+
recordRetrieved([...project.map((m) => m.id), ...user.map((m) => m.id)]);
|
|
12
18
|
const lines = ["[OPEN-MEMEX]"];
|
|
13
19
|
if (user.length > 0) {
|
|
14
20
|
lines.push("", "User profile / preferences:");
|
package/dist/retrieve/search.js
CHANGED
|
@@ -2,6 +2,7 @@ import { db } from "../store/db.js";
|
|
|
2
2
|
import { toFtsQuery } from "./query.js";
|
|
3
3
|
import { BM25_WEIGHTS } from "./weights.js";
|
|
4
4
|
import { loadAliasEntries, planAliasExpansions, mergeRounds, } from "./alias-memory.js";
|
|
5
|
+
import { recordRetrieved } from "../store/usage.js";
|
|
5
6
|
function toHit(r) {
|
|
6
7
|
const aliases = r.aliases ? r.aliases.split(",").map((a) => a.trim()).filter(Boolean) : [];
|
|
7
8
|
let snippet = r.snippet ?? "";
|
|
@@ -232,7 +233,12 @@ export function search(query, opts = {}) {
|
|
|
232
233
|
// without a user alias the query side stays a single FTS round.
|
|
233
234
|
if (opts.stats)
|
|
234
235
|
opts.stats.candidates = merged.length;
|
|
235
|
-
|
|
236
|
+
const hits = resolveVisible(merged, limit, opts.stats);
|
|
237
|
+
// D77-L2: record only the ids actually returned — the candidate pool is
|
|
238
|
+
// not an exposure, and #53 guarantees the cut below is the final result.
|
|
239
|
+
if (opts.record && hits.length > 0)
|
|
240
|
+
recordRetrieved(hits.map((h) => h.id));
|
|
241
|
+
return hits;
|
|
236
242
|
}
|
|
237
243
|
export function list(scopeKey, opts = {}) {
|
|
238
244
|
const limit = Math.max(1, Math.min(opts.limit ?? 20, 100));
|
|
@@ -257,9 +263,14 @@ export function list(scopeKey, opts = {}) {
|
|
|
257
263
|
if (opts.include === "all") {
|
|
258
264
|
// D68: the audit view — every row as stored (superseded versions,
|
|
259
265
|
// retracted, archived), no chain collapsing, capped at limit.
|
|
266
|
+
// NOT an exposure (D77-L2): the audit view is inspection for pruning
|
|
267
|
+
// decisions; counting it would inflate memories the user never saw.
|
|
260
268
|
return raw.slice(0, limit).map(toHit);
|
|
261
269
|
}
|
|
262
|
-
|
|
270
|
+
const hits = resolveVisible(raw, limit);
|
|
271
|
+
if (opts.record && hits.length > 0)
|
|
272
|
+
recordRetrieved(hits.map((h) => h.id));
|
|
273
|
+
return hits;
|
|
263
274
|
}
|
|
264
275
|
/**
|
|
265
276
|
* True totals for the inventory's truncation disclosure (D68). Under
|
package/dist/review.js
CHANGED
|
@@ -26,6 +26,7 @@ import { resolveProjectScope } from "./scope.js";
|
|
|
26
26
|
import { parse as parseMemory, serialize, atomicWriteTextSync, ulid, writeMemoryFile, } from "./store/markdown.js";
|
|
27
27
|
import { findMemoryFile } from "./store/lifecycle.js";
|
|
28
28
|
import { upsertFromFile } from "./store/sync.js";
|
|
29
|
+
import { recordUseful } from "./store/usage.js";
|
|
29
30
|
/** Best-effort author identity: git user.name, else the OS user. */
|
|
30
31
|
export function currentAuthor() {
|
|
31
32
|
try {
|
|
@@ -202,6 +203,12 @@ export function promoteMemory(id, opts = {}) {
|
|
|
202
203
|
};
|
|
203
204
|
atomicWriteTextSync(mf.filePath, serialize(fm, mf.body));
|
|
204
205
|
upsertFromFile({ fm, body: mf.body, filePath: mf.filePath, mtimeMs: Date.now() });
|
|
206
|
+
// D77-L2: a human approve at review is exactly the "explicit confirmation"
|
|
207
|
+
// the D77 useful definition names. One tick per approve step — the later
|
|
208
|
+
// published transition passes through approved and does not re-count.
|
|
209
|
+
// Always useful_team: promoteMemory is project-only by contract above.
|
|
210
|
+
if (to === "approved")
|
|
211
|
+
recordUseful(id, "team", "promote");
|
|
205
212
|
return { id, from, to, history: fm.review_history };
|
|
206
213
|
}
|
|
207
214
|
/** Render a memory's audit trail as compact human-readable lines (D29). */
|
package/dist/store/db.js
CHANGED
|
@@ -111,6 +111,24 @@ END;
|
|
|
111
111
|
`;
|
|
112
112
|
/** Current index schema version. Bump when TABLE_SCHEMA/FTS_SCHEMA change. */
|
|
113
113
|
const SCHEMA_VERSION = 9;
|
|
114
|
+
// D77-L2: reuse counters live in their own table, keyed by memory id. It is
|
|
115
|
+
// created on every open (CREATE IF NOT EXISTS) and deliberately NOT part of
|
|
116
|
+
// the rebuildable index: `rebuildIndexSchema` drops memories/memories_fts
|
|
117
|
+
// and re-derives them from the Markdown files, but the counters are
|
|
118
|
+
// accumulated telemetry with no source-of-truth file to rebuild from — so
|
|
119
|
+
// they must survive a rebuild (ids are stable: the files carry them).
|
|
120
|
+
// No SCHEMA_VERSION bump: the table is additive with IF NOT EXISTS.
|
|
121
|
+
const USAGE_SCHEMA = `
|
|
122
|
+
CREATE TABLE IF NOT EXISTS memory_usage (
|
|
123
|
+
id TEXT PRIMARY KEY,
|
|
124
|
+
retrieved_count INTEGER NOT NULL DEFAULT 0,
|
|
125
|
+
useful_self INTEGER NOT NULL DEFAULT 0,
|
|
126
|
+
useful_team INTEGER NOT NULL DEFAULT 0,
|
|
127
|
+
last_retrieved_at TEXT NOT NULL DEFAULT '',
|
|
128
|
+
last_useful_at TEXT,
|
|
129
|
+
updated_at TEXT NOT NULL DEFAULT ''
|
|
130
|
+
);
|
|
131
|
+
`;
|
|
114
132
|
function userVersion(d) {
|
|
115
133
|
const row = d.prepare("PRAGMA user_version").get();
|
|
116
134
|
return row.user_version;
|
|
@@ -165,6 +183,7 @@ export function db() {
|
|
|
165
183
|
rebuildIndexSchema(d);
|
|
166
184
|
d.exec(TABLE_SCHEMA);
|
|
167
185
|
d.exec(FTS_SCHEMA);
|
|
186
|
+
d.exec(USAGE_SCHEMA);
|
|
168
187
|
if (userVersion(d) < SCHEMA_VERSION)
|
|
169
188
|
rebuildIndexSchema(d);
|
|
170
189
|
_db = d;
|
package/dist/store/lifecycle.js
CHANGED
|
@@ -6,6 +6,7 @@ import { paths, projectRoot, inRepoMemoriesDirPath, } from "../paths.js";
|
|
|
6
6
|
import { loadConfig } from "../config.js";
|
|
7
7
|
import { cjkIndexText } from "../retrieve/cjk.js";
|
|
8
8
|
import { isTurnEcho } from "../capture/handoff.js";
|
|
9
|
+
import { recordUseful, usefulKindFor } from "./usage.js";
|
|
9
10
|
import { parse, serialize, atomicWriteTextSync, ulid, msToRfc3339, } from "./markdown.js";
|
|
10
11
|
/**
|
|
11
12
|
* Dedup + lifecycle (V2-DESIGN §3.3, §3.4).
|
|
@@ -207,6 +208,10 @@ export function supersede(oldId, input) {
|
|
|
207
208
|
if (oldMf.fm.status !== "active") {
|
|
208
209
|
throw new Error(`cannot supersede memory with status '${oldMf.fm.status}' (id ${oldId}); only active memories can be superseded`);
|
|
209
210
|
}
|
|
211
|
+
// D77-L2: the replacement's chain pointer back to this memory is a
|
|
212
|
+
// behavioral useful signal — something here was worth carrying forward.
|
|
213
|
+
// Classified from the OLD memory's state (captured before any flips).
|
|
214
|
+
const usefulKind = usefulKindFor(oldMf.fm.scope, oldMf.fm.review_state);
|
|
210
215
|
const now = msToRfc3339(Date.now());
|
|
211
216
|
const newFm = {
|
|
212
217
|
...oldMf.fm,
|
|
@@ -250,6 +255,9 @@ export function supersede(oldId, input) {
|
|
|
250
255
|
oldMf.fm.superseded_by = newFm.id;
|
|
251
256
|
oldMf.fm.updated_at = now;
|
|
252
257
|
rewriteMemoryFile(oldMf);
|
|
258
|
+
// Behavioral useful (D77) — recorded after both aliases of the chain are
|
|
259
|
+
// settled, so a crash mid-supersede never half-records.
|
|
260
|
+
recordUseful(oldId, usefulKind, "supersede");
|
|
253
261
|
return { oldMf, newMf };
|
|
254
262
|
}
|
|
255
263
|
const SETTABLE_STATUSES = [
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* D77-L2: per-memory online reuse counters — `retrieved_count` (exposure:
|
|
3
|
+
* returned by search / list / first-turn injection) and useful counts,
|
|
4
|
+
* split into `useful_self` (the author's own reuse — personal memories and
|
|
5
|
+
* unpublished project drafts) and `useful_team` (reuse of reviewed project
|
|
6
|
+
* knowledge). Derived: reuse_rate = (useful_self + useful_team) /
|
|
7
|
+
* retrieved_count; "zombie memories" (retrieved, never useful) surface in
|
|
8
|
+
* the D77-L3 report.
|
|
9
|
+
*
|
|
10
|
+
* Counters live in SQLite, NOT in frontmatter (D77): they are volatile
|
|
11
|
+
* local telemetry, the Markdown source of truth never rewrites itself with
|
|
12
|
+
* every retrieval, and they never leave the machine. The table is keyed by
|
|
13
|
+
* memory id and deliberately sits OUTSIDE the rebuildable index schema —
|
|
14
|
+
* `rebuildIndexSchema` drops `memories`/`memories_fts` but must not touch
|
|
15
|
+
* counters (the ids survive a rebuild because the files carry them).
|
|
16
|
+
*
|
|
17
|
+
* Restraint rules (D77): useful only via explicit signal — `memory_useful`,
|
|
18
|
+
* a human approve at review, or a behavioral reference (supersede).
|
|
19
|
+
* Passive surfacing increments ONLY retrieved_count; unguarded exposure
|
|
20
|
+
* must never refresh usefulness (the self-reinforcing retrieval loop).
|
|
21
|
+
*
|
|
22
|
+
* `reuse_rate` is the useful/retrieved ratio, not a probability: an explicit
|
|
23
|
+
* confirmation does not require a matching recorded exposure in the same
|
|
24
|
+
* counter window (a human can confirm a memory that paid off before counters
|
|
25
|
+
* existed, or confirm the same payoff twice), so the ratio can exceed 1.0.
|
|
26
|
+
* Read it as signal strength, not a percentage.
|
|
27
|
+
*/
|
|
28
|
+
import { db } from "./db.js";
|
|
29
|
+
export function usefulKindFor(scope, reviewState) {
|
|
30
|
+
if (scope === "personal")
|
|
31
|
+
return "self";
|
|
32
|
+
// No identity system (D77): reviewed project knowledge reused = the team
|
|
33
|
+
// story; everything else still reads as the author's own utility.
|
|
34
|
+
if (reviewState === "approved" || reviewState === "published")
|
|
35
|
+
return "team";
|
|
36
|
+
return "self";
|
|
37
|
+
}
|
|
38
|
+
const INSERT_RETRIEVED_SQL = `
|
|
39
|
+
INSERT INTO memory_usage (id, retrieved_count, useful_self, useful_team, last_retrieved_at, last_useful_at, updated_at)
|
|
40
|
+
VALUES (?, 1, 0, 0, ?, NULL, ?)
|
|
41
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
42
|
+
retrieved_count = memory_usage.retrieved_count + 1,
|
|
43
|
+
last_retrieved_at = excluded.last_retrieved_at,
|
|
44
|
+
updated_at = excluded.updated_at
|
|
45
|
+
`;
|
|
46
|
+
function insertUsefulSql(self) {
|
|
47
|
+
const col = self ? "useful_self" : "useful_team";
|
|
48
|
+
return `
|
|
49
|
+
INSERT INTO memory_usage (id, retrieved_count, useful_self, useful_team, last_retrieved_at, last_useful_at, updated_at)
|
|
50
|
+
VALUES (?, 0, ${self ? 1 : 0}, ${self ? 0 : 1}, '', ?, ?)
|
|
51
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
52
|
+
${col} = memory_usage.${col} + 1,
|
|
53
|
+
last_useful_at = excluded.last_useful_at,
|
|
54
|
+
updated_at = excluded.updated_at
|
|
55
|
+
`;
|
|
56
|
+
}
|
|
57
|
+
function rfc(ms) {
|
|
58
|
+
return new Date(ms).toISOString().replace(/\.000Z$/, "Z");
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Count one exposure each for the ids actually returned to a caller
|
|
62
|
+
* (already limited/filtered — callers record the final hits, not the
|
|
63
|
+
* candidate pool). Unknown/id-side dupes are absorbed: ids arrive deduped
|
|
64
|
+
* (resolution collapses chains anyway); anything not in the index yet is
|
|
65
|
+
* still counted — a just-saved memory can be hit in the same query that
|
|
66
|
+
* created it only after upsert, so the index row exists by contract; a
|
|
67
|
+
* missing one gets a row with last_retrieved_at set and no harm done.
|
|
68
|
+
*/
|
|
69
|
+
export function recordRetrieved(ids, atMs = Date.now()) {
|
|
70
|
+
if (ids.length === 0)
|
|
71
|
+
return 0;
|
|
72
|
+
// No explicit transaction wrapper: both drivers' .transaction() returns a
|
|
73
|
+
// deferred callable (calling it must NOT execute), and the common surface
|
|
74
|
+
// here is stmt-exec only. Per-row autocommit on WAL is plenty for the
|
|
75
|
+
// ≤50 ids one retrieval returns.
|
|
76
|
+
const d = db();
|
|
77
|
+
const at = rfc(atMs);
|
|
78
|
+
const stmt = d.prepare(INSERT_RETRIEVED_SQL);
|
|
79
|
+
for (const id of ids)
|
|
80
|
+
stmt.run(id, at, at);
|
|
81
|
+
return new Set(ids).size;
|
|
82
|
+
}
|
|
83
|
+
export const VIA_VALUES = ["tool", "supersede", "promote"];
|
|
84
|
+
/**
|
|
85
|
+
* Count one explicit useful signal. Returns the updated row, or null when
|
|
86
|
+
* the id is not in the index (callers surface that as not-found — a useful
|
|
87
|
+
* tick for a memory nobody has must not create phantom telemetry).
|
|
88
|
+
*/
|
|
89
|
+
export function recordUseful(id, kind, _via, atMs = Date.now()) {
|
|
90
|
+
const d = db();
|
|
91
|
+
const mem = d.prepare(`SELECT id FROM memories WHERE id = ?`).get(id);
|
|
92
|
+
if (!mem)
|
|
93
|
+
return null;
|
|
94
|
+
const at = rfc(atMs);
|
|
95
|
+
d.prepare(insertUsefulSql(kind === "self")).run(id, at, at);
|
|
96
|
+
return getUsage(id);
|
|
97
|
+
}
|
|
98
|
+
export function getUsage(id) {
|
|
99
|
+
const row = db()
|
|
100
|
+
.prepare(`SELECT id, retrieved_count, useful_self, useful_team,
|
|
101
|
+
last_retrieved_at, last_useful_at, updated_at
|
|
102
|
+
FROM memory_usage WHERE id = ?`)
|
|
103
|
+
.get(id);
|
|
104
|
+
if (!row)
|
|
105
|
+
return null;
|
|
106
|
+
row.retrieved_count = Number(row.retrieved_count) || 0;
|
|
107
|
+
row.useful_self = Number(row.useful_self) || 0;
|
|
108
|
+
row.useful_team = Number(row.useful_team) || 0;
|
|
109
|
+
return row;
|
|
110
|
+
}
|
|
111
|
+
/** D77: useful_count = useful_self + useful_team — both count as useful. */
|
|
112
|
+
export function usefulCount(u) {
|
|
113
|
+
return u.useful_self + u.useful_team;
|
|
114
|
+
}
|
|
115
|
+
/** reuse_rate = useful / retrieved (0 when the memory was never retrieved). */
|
|
116
|
+
export function reuseRate(u) {
|
|
117
|
+
const n = usefulCount(u);
|
|
118
|
+
if (u.retrieved_count <= 0)
|
|
119
|
+
return null;
|
|
120
|
+
return n / u.retrieved_count;
|
|
121
|
+
}
|
|
122
|
+
/** D77-L3's selection helpers ride the same table scan for free. */
|
|
123
|
+
export function listUsage(scopeKey) {
|
|
124
|
+
const sql = scopeKey
|
|
125
|
+
? `SELECT u.id, u.retrieved_count, u.useful_self, u.useful_team,
|
|
126
|
+
u.last_retrieved_at, u.last_useful_at, u.updated_at
|
|
127
|
+
FROM memory_usage u JOIN memories m ON m.id = u.id
|
|
128
|
+
WHERE m.scope_key = ?`
|
|
129
|
+
: `SELECT u.id, u.retrieved_count, u.useful_self, u.useful_team,
|
|
130
|
+
u.last_retrieved_at, u.last_useful_at, u.updated_at
|
|
131
|
+
FROM memory_usage u`;
|
|
132
|
+
const args = scopeKey ? [scopeKey] : [];
|
|
133
|
+
const rows = db().prepare(sql).all(...args);
|
|
134
|
+
for (const r of rows) {
|
|
135
|
+
r.retrieved_count = Number(r.retrieved_count) || 0;
|
|
136
|
+
r.useful_self = Number(r.useful_self) || 0;
|
|
137
|
+
r.useful_team = Number(r.useful_team) || 0;
|
|
138
|
+
}
|
|
139
|
+
return rows;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Drop one memory's telemetry. ONLY the hard-forget path calls this (the
|
|
143
|
+
* memory is gone for good); plain index removal — which fires on a branch
|
|
144
|
+
* switch, when in-repo files transiently disappear — must NOT prune here,
|
|
145
|
+
* or switching branches would wipe counters the files will resurrect.
|
|
146
|
+
* Superseded/deprecated/retracted memories keep their rows: their history
|
|
147
|
+
* is part of the reuse story.
|
|
148
|
+
*/
|
|
149
|
+
export function deleteUsage(id) {
|
|
150
|
+
db().prepare(`DELETE FROM memory_usage WHERE id = ?`).run(id);
|
|
151
|
+
}
|