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/dist/tools/memory.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { PERSONAL_SCOPE } from "../scope.js";
|
|
2
2
|
import { syncScope } from "../store/sync.js";
|
|
3
|
-
import { addMemory, searchMemories, listMemories, supersedeMemory, forgetMemory, workingStateMemory, memoryAddArgs, memorySearchArgs, memoryListArgs, memorySupersedeArgs, memoryForgetArgs, memoryWorkingStateArgs, TOOL_DESCRIPTIONS, withOutboxNote, } from "./ops.js";
|
|
3
|
+
import { addMemory, searchMemories, listMemories, supersedeMemory, forgetMemory, markMemoryUseful, workingStateMemory, memoryAddArgs, memorySearchArgs, memoryListArgs, memorySupersedeArgs, memoryForgetArgs, memoryUsefulArgs, memoryWorkingStateArgs, TOOL_DESCRIPTIONS, withOutboxNote, } from "./ops.js";
|
|
4
4
|
// Local stand-in for the SDK's tool() helper — same signature, and the SDK
|
|
5
5
|
// function is a runtime identity (`return input`). Do NOT import it from
|
|
6
6
|
// @opencode-ai/plugin at runtime: that package is a devDependency, and when
|
|
@@ -72,6 +72,16 @@ export function makeTools(getScope, cfg) {
|
|
|
72
72
|
return withOutboxNote(getScope().key, forgetMemory(args));
|
|
73
73
|
},
|
|
74
74
|
});
|
|
75
|
+
// D77-L2: explicit useful confirmation. Needs a fresh index read to
|
|
76
|
+
// classify (scope/review_state), hence syncFirst like the mutators.
|
|
77
|
+
const memory_useful = tool({
|
|
78
|
+
description: TOOL_DESCRIPTIONS.memory_useful,
|
|
79
|
+
args: memoryUsefulArgs,
|
|
80
|
+
async execute(args) {
|
|
81
|
+
syncFirst();
|
|
82
|
+
return markMemoryUseful(args);
|
|
83
|
+
},
|
|
84
|
+
});
|
|
75
85
|
// §3.6 (D89): no scope/index work needed — the note lives beside the
|
|
76
86
|
// store, not in it.
|
|
77
87
|
const memory_workingstate = tool({
|
|
@@ -81,5 +91,5 @@ export function makeTools(getScope, cfg) {
|
|
|
81
91
|
return workingStateMemory(getScope, cfg, args);
|
|
82
92
|
},
|
|
83
93
|
});
|
|
84
|
-
return { memory_add, memory_search, memory_list, memory_forget, memory_supersede, memory_workingstate };
|
|
94
|
+
return { memory_add, memory_search, memory_list, memory_forget, memory_supersede, memory_useful, memory_workingstate };
|
|
85
95
|
}
|
package/dist/tools/ops.js
CHANGED
|
@@ -15,6 +15,7 @@ import { writeMemoryFile, readMemoryFile, ulid, msToRfc3339, MEMORY_TYPE_TAXONOM
|
|
|
15
15
|
import { upsertFromFile, deleteFromIndex } from "../store/sync.js";
|
|
16
16
|
import { findDuplicates, findTurnEcho, supersede, setStatus } from "../store/lifecycle.js";
|
|
17
17
|
import { TURN_ECHO_WINDOW_MS } from "../capture/handoff.js";
|
|
18
|
+
import { getUsage, recordUseful, reuseRate, usefulKindFor, usefulCount, deleteUsage, } from "../store/usage.js";
|
|
18
19
|
import { db } from "../store/db.js";
|
|
19
20
|
import { redact } from "../redact.js";
|
|
20
21
|
import { getSyncStatus, formatSyncStatus, submitMemories, outboxDraftCount } from "../submit.js";
|
|
@@ -51,6 +52,7 @@ export const TOOL_DESCRIPTIONS = {
|
|
|
51
52
|
memory_resolve: "List git-conflicted memory files, or attempt a field-level 3-way merge of one. Semantic conflicts are reported, never auto-resolved. Run it when a git pull or merge leaves memory files conflicted; the merged file is written in place (undo with git if the merge is wrong). For PR review state rather than file conflicts, use memory_pr_status. (MCP server and the `open-memex resolve` CLI; the opencode native plugin does not expose this tool.)",
|
|
52
53
|
memory_pr_status: "Read the current branch's GitHub PR and map its review state onto each in-repo memory: merged PR → published, PR approval → approved (approved_by = reviewer), changes-requested → suggestion only. Report by default — that mode changes nothing; apply=true writes the mapped transitions to the local files (still no push). (MCP server and the `open-memex pr-status` CLI; the opencode native plugin does not expose this tool.)",
|
|
53
54
|
memory_workingstate: "Read, write, or clear the one ephemeral per-project working-state note (§3.6, D89): where an interrupted task stands, so a fresh session can resume. Scratch state, NOT durable knowledge — it never enters memory retrieval or a review ladder; any conclusion here that should outlive the task goes through the normal memory_add/checkpoint-proposal path instead. WRITE it (action=write, content required) when the user signals the session or task is wrapping up — body rubric: task summary (one paragraph), open files, last commands, where the work stands, next step; short by design, a scratch note, not a transcript. READ it when resuming work or when the user asks what they were doing. CLEAR it on the user's request only. The note lives outside memories/, the user can edit the plain file directly, and it expires after ttl_days (default 7) — expired notes are ignored and `audit` reports them.",
|
|
55
|
+
memory_useful: "Mark an existing memory as useful (D77): record that it demonstrably paid off. Call it ONLY on an explicit signal — the user confirmed it helped ('that was the one', 'saved me again'), or your completed/accepted work clearly relied on that memory and the user saw the result. NEVER call it because a memory appeared in memory_search results, a memory_list inventory, or the session-start block: passive exposure never refreshes usefulness. Exposure is counted automatically under retrieved_count; the useful buckets increment only through this tool, a human approval at review, or a supersede. Useful is split automatically: useful_self for personal memories and unpublished project drafts (the author's own utility), useful_team for approved/published project memories (team knowledge reused) — pass kind only to override. Returns the cumulative counts and reuse_rate (useful / retrieved). The counters live in the local SQLite index, not in the Markdown source of truth, and never leave this machine.",
|
|
54
56
|
};
|
|
55
57
|
/** Shared zod input shapes (raw shape, not z.object — hosts wrap as needed). */
|
|
56
58
|
export const scopeArg = z
|
|
@@ -186,6 +188,16 @@ export const memoryWorkingStateArgs = {
|
|
|
186
188
|
.optional()
|
|
187
189
|
.describe("Note body, Markdown, short by design (required for write). Rubric: task summary (one paragraph), open files, last commands, where the work stands, next step. A scratch note, not a transcript."),
|
|
188
190
|
};
|
|
191
|
+
export const memoryUsefulArgs = {
|
|
192
|
+
id: z
|
|
193
|
+
.string()
|
|
194
|
+
.min(1)
|
|
195
|
+
.describe("ID of the memory being confirmed useful (memory_search / memory_list return ids)."),
|
|
196
|
+
kind: z
|
|
197
|
+
.enum(["self", "team"])
|
|
198
|
+
.optional()
|
|
199
|
+
.describe("Which useful counter. Default: auto — personal memories and unpublished project drafts count useful_self; approved/published project memories count useful_team. Pass only to override the auto split."),
|
|
200
|
+
};
|
|
189
201
|
function resolveScope(getScope, kind) {
|
|
190
202
|
return kind === "personal" ? PERSONAL_SCOPE : getScope();
|
|
191
203
|
}
|
|
@@ -294,10 +306,12 @@ export async function searchMemories(getScope, args) {
|
|
|
294
306
|
: args.scope === "project"
|
|
295
307
|
? [project.key]
|
|
296
308
|
: [project.key, PERSONAL_SCOPE.key];
|
|
309
|
+
// D77-L2: every surface that hands hits to a caller counts as exposure.
|
|
297
310
|
const hits = search(args.query, {
|
|
298
311
|
scopeKeys,
|
|
299
312
|
limit: args.limit,
|
|
300
313
|
type: args.type,
|
|
314
|
+
record: true,
|
|
301
315
|
});
|
|
302
316
|
if (hits.length === 0) {
|
|
303
317
|
return {
|
|
@@ -318,7 +332,7 @@ export async function listMemories(getScope, args) {
|
|
|
318
332
|
// #3" names exactly one memory. A per-section counter emitted two "#1"s.
|
|
319
333
|
let seq = 0;
|
|
320
334
|
const render = (scopeKey) => {
|
|
321
|
-
const hits = list(scopeKey, { type: args.type, limit: args.limit, include });
|
|
335
|
+
const hits = list(scopeKey, { type: args.type, limit: args.limit, include, record: true });
|
|
322
336
|
const total = countList(scopeKey, { type: args.type, include });
|
|
323
337
|
const lines = hits.map((h) => formatInventoryLine(seq++, h, PERSONAL_SCOPE.key));
|
|
324
338
|
const note = truncationNote(hits.length, total);
|
|
@@ -441,6 +455,10 @@ export async function forgetMemory(args) {
|
|
|
441
455
|
}
|
|
442
456
|
}
|
|
443
457
|
deleteFromIndex(args.id);
|
|
458
|
+
// D77-L2: the memory is gone for good — its telemetry has no subject left.
|
|
459
|
+
// Only the hard path prunes the usage row; status flips and index removal
|
|
460
|
+
// (branch switches remove in-repo files transiently) keep it.
|
|
461
|
+
deleteUsage(args.id);
|
|
444
462
|
// D64: forgetting an in-repo memory deletes a file inside the user's
|
|
445
463
|
// git working tree. Say so — the deletion should ride a commit, or the
|
|
446
464
|
// file silently diverges from what teammates have.
|
|
@@ -456,6 +474,42 @@ export async function forgetMemory(args) {
|
|
|
456
474
|
// 2B/D26: review workflow ops (also exposed over MCP so agents can drive the
|
|
457
475
|
// sync loop: status → ask user → submit → push/PR on approval).
|
|
458
476
|
// ---------------------------------------------------------------------------
|
|
477
|
+
/**
|
|
478
|
+
* D77-L2: the explicit confirmation route to the useful counters. The
|
|
479
|
+
* restraint rules live in the tool description and the MCP handshake —
|
|
480
|
+
* an unguarded call path here would create the self-reinforcing retrieval
|
|
481
|
+
* loop D77 warns about, so nothing silently routes exposure into useful.
|
|
482
|
+
* Classification proxy (no identity system): personal scope / unreviewed
|
|
483
|
+
* project draft → useful_self; approved/published project memory → useful_team.
|
|
484
|
+
*/
|
|
485
|
+
export async function markMemoryUseful(args) {
|
|
486
|
+
const row = db()
|
|
487
|
+
.prepare(`SELECT scope, review_state FROM memories WHERE id = ?`)
|
|
488
|
+
.get(args.id);
|
|
489
|
+
if (!row) {
|
|
490
|
+
return {
|
|
491
|
+
title: "memory: useful not found",
|
|
492
|
+
output: `No memory with id ${args.id} in the index — memory_search or memory_list returns current ids.`,
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
const kind = args.kind ?? usefulKindFor(row.scope, row.review_state);
|
|
496
|
+
const after = recordUseful(args.id, kind, "tool");
|
|
497
|
+
// recordUseful re-checks existence; both branches above agree on not-found.
|
|
498
|
+
if (!after) {
|
|
499
|
+
return {
|
|
500
|
+
title: "memory: useful not found",
|
|
501
|
+
output: `No memory with id ${args.id} in the index.`,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
const u = getUsage(args.id);
|
|
505
|
+
const rate = reuseRate(u);
|
|
506
|
+
const useful = usefulCount(u);
|
|
507
|
+
return {
|
|
508
|
+
title: `memory: useful (${kind}) ${args.id}`,
|
|
509
|
+
output: `Marked useful (${kind}). retrieved: ${u.retrieved_count}, useful_self: ${u.useful_self}, useful_team: ${u.useful_team}, reuse_rate: ${rate === null ? "n/a (never retrieved)" : rate.toFixed(2)}.` +
|
|
510
|
+
`\nA supersede or a human approval also counts — no need to duplicate those with an explicit call.`,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
459
513
|
export async function statusMemories() {
|
|
460
514
|
const st = getSyncStatus();
|
|
461
515
|
const n = st.outbox.length +
|
package/docs/V2-DESIGN.md
CHANGED
|
@@ -580,7 +580,7 @@ requirement: personal data never touches third-party services). Benchmarks to tr
|
|
|
580
580
|
- **Phase 4 — Future, signal-gated.** Cloud `RemoteProvider` customization only on: multi-private-repo
|
|
581
581
|
sharing needs, fine-grained ACL, audit/compliance mandates · optional API-backed exporters/providers
|
|
582
582
|
for enterprise knowledge systems.
|
|
583
|
-
- **Near-term backlog — committed direction, not yet built (2026-10-07).** Stone's rule: anything said as "later" is written down here. D77-L2: per-memory `retrieved_count`/`useful_count` (`useful_self` vs `useful_team`) + `memory_useful` tool. D77-L3: `memory_status` reuse report (top reused, zero-reuse, per-scope reuse rate) feeding the Spark Tank pilot metrics. D77: external bench — LongMemEval-S run 2026-10-07 (`scripts/bench-longmemeval.ts`, 470 questions, recall_any@k: R@5 97.0% / MRR 0.909 per-question, R@5 40.6% on a pooled 22k corpus; ahead of agentmemory’s BM25-only, level with their BM25+vector). MemoryAgentBench still open as a second external data point. D79 follow-up SUPERSEDED → built as **D80** (2026-10-07): index-time synonym/translation expansion shipped; 41-query fixture recall@5 0.854 → 0.976, MRR 0.791 → 0.859. Embedding-model configurability (Stone 2026-10-07): the multilingual model is his personal need (EN↔ZH), not everyone’s — the model must be user-configurable. Timing: (1) NOW in the bench only — a `--model` flag to measure the multilingual tax (multilingual vs English-only on English data), which decides the DEFAULT. (2) AT SHIP TIME — `embedding.model` in `MyOMemoryConfig` + `SETTABLE_KEYS`, model-agnostic storage from day one (dim + model id stored with vectors, cache dir), download UX and `doctor` checks. Not before the gate passes: building config UX for a layer we haven’t decided to ship is premature. If multilingual tax ≈ 0, default multilingual (covers everyone); else default English-only with a docs note.D78: curate+submit — pre-submit lint, then confidence-tier auto-curation (auto-apply / batch-confirm / explicit human). D79 follow-ups: feedback-weighted ranking once D77 counters land; embeddings gate decision against the published baseline; reranker evaluation. Cross-lingual embedding rerank (Stone 2026-10-16, from obsidian-mind comparison): ablation showed multilingual vectors beat BM25 by +12pp R@5 on the cross-lingual slice — the one gap lexical can't cover. Design as opt-in rerank for EN↔ZH queries only, not a default path; local stays BM25-first per the retrieval split above. TDQS nit (separate PR): tighten search/list `type` to `z.enum`. Retrieval eval: grow the fixture (project-scope tier cases) as retrieval logic evolves. Retrieval split — local vs share server (Stone 2026-10-07): the two environments emphasize different mechanisms. Local (personal machine): BM25 + curated index-time expansion as the primary — deterministic, zero model download (D7), fast on CPU, index bloat bounded by the small corpus; embeddings opt-in only. Share server (team/org, enterprise): embeddings + ANN + reranker as the primary — server-grade compute with models resident, corpus too large and multi-author for any curated map; the curated map stays as a precision layer plus org glossary. The server additionally aggregates D77 useful_count across users into feedback-weighted ranking (already in D79 follow-ups) — a signal a single machine can never have. Bottom-up loop: curated pairs that many users converge on locally become org-glossary candidates. Economics flip: N users each downloading a model vs one model amortized on the server. OptMem lessons (Stone 2026-10-16, from kafkaup's OptMem post): three friction-reduction ideas worth stealing from the minimalist end of the spectrum. (1) **Token cost as spec** — measure and publish open-memex's prompt/token overhead in the README, the way OptMem advertises its "426-token prompt"; acquisition copy, not just engineering. (2) **`wake` convention** — document a session-start ritual (one `memory_recall` call at the beginning of every session), mirroring OptMem's `memo wake`; the MCP tools exist but the habit isn't specified. (3) **Capture length nudge** — a soft length cap or conciseness hint at capture time, inspired by OptMem's 280-byte hard cap; forces conciseness at write time, cheap to implement, aligned with the distill-to-AGENTS.md direction (D40). Three-tier memory zones (Stone 2026-10-18, from Westenberg "I Deleted My Second Brain" + his own reflection): the second brain should have zones like cache vs database, not "keep everything" vs "delete everything". **Hot** (active zone, cache-like: small, curated, always in context — D81 aliases, WHAT-level) · **Warm** (compost/incubation: not active but not cold; periodic review, rotted items deleted — this is "forget on purpose" as engineering) · **Cold** (full archive, searchable, not resident). The hard part is the **promotion/demotion policy** — what moves between zones, when, by what rule (the cache-replacement problem for knowledge; "useful" ≠ "recently used"). Capture restraint is a separate gate: not everything deserves to enter even cold storage. Spec the policy before building the zones. Auto-capture design brief (Stone 2026-10-19, from ai-memory comparison): open-memex wants auto-capture but under the restraint philosophy (not ai-memory's capture-everything). Five design questions: (1) **End-session trigger** — what hooks does opencode actually expose? (check before designing; ai-memory built finalize-session fallback for harnesses without SessionEnd); candidates: native hook / idle timeout / explicit command / context-near-full. (2) **Distillation** — rules first (what happened: git diff, tool calls, decision sentences; zero LLM), interpretation layer (what it means) left to human/LLM. (3) **Save-value triage** — three tiers: clearly valuable → save; clearly noise → drop; ambiguous → ask human. Boundary principle: **rather over-ask than over-save** (polluted retrieval costs more than a missed memory). (4) **Routing** — four exits: project memory / personal memory / AGENTS.md proposal (distill-agents exists) / discard; keep v1 routing rules simple. (5) **Human interaction** — one batch confirmation at session end ("save these 3? [y/n/edit]"), never per-item popups. Relations: D73 keyword capture is turn-level (no conflict); `wake` convention is session-start (this is session-end — the other bookend); three-tier zones govern where auto-captured items land. Cross-agent study (Stone 2026-10-19): open-memex has cross-agent on the roadmap — study how ai-memory does it (handoff claim-once semantics, lifecycle hooks per harness, VSCode support via MCP-only) before designing ours; borrow the semantics, not the push-injection behavior (discoverability > injection). Injection cost discipline (Stone 2026-10-19, from Harness² paper arXiv:2610.14224): "ALWAYS-ON PROSE IS THE EXPENSIVE OPTION" — every always-on word competes with the agent's output budget. Current session-start injection (8 project + 5 personal) is the expensive path; direction: move "important but not needed every turn" memories to on-demand (tool/skill-triggered loading), keep only truly every-turn items resident. Tolerable now, better not to tolerate. Component cost ladder for reference: SKILL (default, zero-cost until invoked) > SCRIPT > SUBAGENT > PLUGIN ("prose can be skipped, a hook cannot") > ALWAYS-ON TEXT (last resort). Read-less compression (Stone 2026-10-19, from caveman https://github.com/JuliusBrussee/caveman): the execution layer of injection cost discipline — compress what the agent READS before it reaches context, not just what we inject. Caveman's measured numbers: 33.2% fewer input tokens per session (CSV 98.9%, logs 98.5%, YAML 99.1%, JSON 98.5% per-file; HTML has no compressor yet). Direction for open-memex: a pre-retrieval compression pass on tool outputs and retrieved passages (structured data → compact form), originals stay on disk and pullable on demand. Two design principles borrowed: (1) never compress the user's own prompt/input (Adobe CAVEWOMAN finding: cavemanning user prompts makes answers worse); (2) leave code/tool calls/payloads verbatim — compress the wrapper, not the payload. Caveats: caveman's own rules cost ~1,160 input tokens fixed; per-request billing (Copilot-style) nullifies the saving — compression pays off on per-token billing only. Knowledge upkeep as a first-class direction (Stone 2026-10-23; external validation: Hedy Zhang's FDE field retrospective on enterprise AI knowledge bases, X article 2026-10-22 — enterprise knowledge bases die on unowned upkeep, not on retrieval: stale answers served silently, conflicts with no owner, updates nobody owns after delivery). The mechanisms already exist (supersede chains, lifecycle states, `audit` health check, curator convention); the direction is driving the human cost of upkeep toward zero: (1) staleness signals — age, contradiction with newer captures, D77 zero-reuse counters — feeding a standing review queue instead of waiting for someone to remember to run `audit`; (2) a conflict inbox — semantic conflicts and broken chains as a persistent todo; (3) the endgame is D78 confidence-tier auto-curation (auto-apply the safe tier, batch-confirm the rest). Success metric: the base stays trustworthy on minutes-per-week of human attention, not a curator shift. README pitches the shipped half of this as core concept 4 (Knowledge stays current) plus a "When facts change" comparison row. Session working state note (D89, 2026-11-02) → BUILT, shipped 2026-11-03 as D90: 12th tool `memory_workingstate` on both hosts, session-start surfacing, `audit` expiry report, `wstate` CLI; opencode write path is instruction + tool (plugin API has no Stop hook).
|
|
583
|
+
- **Near-term backlog — committed direction, not yet built (2026-10-07).** Stone's rule: anything said as "later" is written down here. D77-L2 ✅ built 2026-11-03 (0.9.0-alpha.2): per-memory `retrieved_count`/`useful_count` (`useful_self` vs `useful_team`) + `memory_useful` tool, counters in a `memory_usage` table beside the rebuildable index. D77-L3: `memory_status` reuse report (top reused, zero-reuse, per-scope reuse rate) feeding the Spark Tank pilot metrics. D77: external bench — LongMemEval-S run 2026-10-07 (`scripts/bench-longmemeval.ts`, 470 questions, recall_any@k: R@5 97.0% / MRR 0.909 per-question, R@5 40.6% on a pooled 22k corpus; ahead of agentmemory’s BM25-only, level with their BM25+vector). MemoryAgentBench still open as a second external data point. D79 follow-up SUPERSEDED → built as **D80** (2026-10-07): index-time synonym/translation expansion shipped; 41-query fixture recall@5 0.854 → 0.976, MRR 0.791 → 0.859. Embedding-model configurability (Stone 2026-10-07): the multilingual model is his personal need (EN↔ZH), not everyone’s — the model must be user-configurable. Timing: (1) NOW in the bench only — a `--model` flag to measure the multilingual tax (multilingual vs English-only on English data), which decides the DEFAULT. (2) AT SHIP TIME — `embedding.model` in `MyOMemoryConfig` + `SETTABLE_KEYS`, model-agnostic storage from day one (dim + model id stored with vectors, cache dir), download UX and `doctor` checks. Not before the gate passes: building config UX for a layer we haven’t decided to ship is premature. If multilingual tax ≈ 0, default multilingual (covers everyone); else default English-only with a docs note.D78: curate+submit — pre-submit lint, then confidence-tier auto-curation (auto-apply / batch-confirm / explicit human). D79 follow-ups: feedback-weighted ranking once D77 counters land; embeddings gate decision against the published baseline; reranker evaluation. Cross-lingual embedding rerank (Stone 2026-10-16, from obsidian-mind comparison): ablation showed multilingual vectors beat BM25 by +12pp R@5 on the cross-lingual slice — the one gap lexical can't cover. Design as opt-in rerank for EN↔ZH queries only, not a default path; local stays BM25-first per the retrieval split above. TDQS nit (separate PR): tighten search/list `type` to `z.enum`. Retrieval eval: grow the fixture (project-scope tier cases) as retrieval logic evolves. Retrieval split — local vs share server (Stone 2026-10-07): the two environments emphasize different mechanisms. Local (personal machine): BM25 + curated index-time expansion as the primary — deterministic, zero model download (D7), fast on CPU, index bloat bounded by the small corpus; embeddings opt-in only. Share server (team/org, enterprise): embeddings + ANN + reranker as the primary — server-grade compute with models resident, corpus too large and multi-author for any curated map; the curated map stays as a precision layer plus org glossary. The server additionally aggregates D77 useful_count across users into feedback-weighted ranking (already in D79 follow-ups) — a signal a single machine can never have. Bottom-up loop: curated pairs that many users converge on locally become org-glossary candidates. Economics flip: N users each downloading a model vs one model amortized on the server. OptMem lessons (Stone 2026-10-16, from kafkaup's OptMem post): three friction-reduction ideas worth stealing from the minimalist end of the spectrum. (1) **Token cost as spec** — measure and publish open-memex's prompt/token overhead in the README, the way OptMem advertises its "426-token prompt"; acquisition copy, not just engineering. (2) **`wake` convention** — document a session-start ritual (one `memory_recall` call at the beginning of every session), mirroring OptMem's `memo wake`; the MCP tools exist but the habit isn't specified. (3) **Capture length nudge** — a soft length cap or conciseness hint at capture time, inspired by OptMem's 280-byte hard cap; forces conciseness at write time, cheap to implement, aligned with the distill-to-AGENTS.md direction (D40). Three-tier memory zones (Stone 2026-10-18, from Westenberg "I Deleted My Second Brain" + his own reflection): the second brain should have zones like cache vs database, not "keep everything" vs "delete everything". **Hot** (active zone, cache-like: small, curated, always in context — D81 aliases, WHAT-level) · **Warm** (compost/incubation: not active but not cold; periodic review, rotted items deleted — this is "forget on purpose" as engineering) · **Cold** (full archive, searchable, not resident). The hard part is the **promotion/demotion policy** — what moves between zones, when, by what rule (the cache-replacement problem for knowledge; "useful" ≠ "recently used"). Capture restraint is a separate gate: not everything deserves to enter even cold storage. Spec the policy before building the zones. Auto-capture design brief (Stone 2026-10-19, from ai-memory comparison): open-memex wants auto-capture but under the restraint philosophy (not ai-memory's capture-everything). Five design questions: (1) **End-session trigger** — what hooks does opencode actually expose? (check before designing; ai-memory built finalize-session fallback for harnesses without SessionEnd); candidates: native hook / idle timeout / explicit command / context-near-full. (2) **Distillation** — rules first (what happened: git diff, tool calls, decision sentences; zero LLM), interpretation layer (what it means) left to human/LLM. (3) **Save-value triage** — three tiers: clearly valuable → save; clearly noise → drop; ambiguous → ask human. Boundary principle: **rather over-ask than over-save** (polluted retrieval costs more than a missed memory). (4) **Routing** — four exits: project memory / personal memory / AGENTS.md proposal (distill-agents exists) / discard; keep v1 routing rules simple. (5) **Human interaction** — one batch confirmation at session end ("save these 3? [y/n/edit]"), never per-item popups. Relations: D73 keyword capture is turn-level (no conflict); `wake` convention is session-start (this is session-end — the other bookend); three-tier zones govern where auto-captured items land. Cross-agent study (Stone 2026-10-19): open-memex has cross-agent on the roadmap — study how ai-memory does it (handoff claim-once semantics, lifecycle hooks per harness, VSCode support via MCP-only) before designing ours; borrow the semantics, not the push-injection behavior (discoverability > injection). Injection cost discipline (Stone 2026-10-19, from Harness² paper arXiv:2610.14224): "ALWAYS-ON PROSE IS THE EXPENSIVE OPTION" — every always-on word competes with the agent's output budget. Current session-start injection (8 project + 5 personal) is the expensive path; direction: move "important but not needed every turn" memories to on-demand (tool/skill-triggered loading), keep only truly every-turn items resident. Tolerable now, better not to tolerate. Component cost ladder for reference: SKILL (default, zero-cost until invoked) > SCRIPT > SUBAGENT > PLUGIN ("prose can be skipped, a hook cannot") > ALWAYS-ON TEXT (last resort). Read-less compression (Stone 2026-10-19, from caveman https://github.com/JuliusBrussee/caveman): the execution layer of injection cost discipline — compress what the agent READS before it reaches context, not just what we inject. Caveman's measured numbers: 33.2% fewer input tokens per session (CSV 98.9%, logs 98.5%, YAML 99.1%, JSON 98.5% per-file; HTML has no compressor yet). Direction for open-memex: a pre-retrieval compression pass on tool outputs and retrieved passages (structured data → compact form), originals stay on disk and pullable on demand. Two design principles borrowed: (1) never compress the user's own prompt/input (Adobe CAVEWOMAN finding: cavemanning user prompts makes answers worse); (2) leave code/tool calls/payloads verbatim — compress the wrapper, not the payload. Caveats: caveman's own rules cost ~1,160 input tokens fixed; per-request billing (Copilot-style) nullifies the saving — compression pays off on per-token billing only. Knowledge upkeep as a first-class direction (Stone 2026-10-23; external validation: Hedy Zhang's FDE field retrospective on enterprise AI knowledge bases, X article 2026-10-22 — enterprise knowledge bases die on unowned upkeep, not on retrieval: stale answers served silently, conflicts with no owner, updates nobody owns after delivery). The mechanisms already exist (supersede chains, lifecycle states, `audit` health check, curator convention); the direction is driving the human cost of upkeep toward zero: (1) staleness signals — age, contradiction with newer captures, D77 zero-reuse counters — feeding a standing review queue instead of waiting for someone to remember to run `audit`; (2) a conflict inbox — semantic conflicts and broken chains as a persistent todo; (3) the endgame is D78 confidence-tier auto-curation (auto-apply the safe tier, batch-confirm the rest). Success metric: the base stays trustworthy on minutes-per-week of human attention, not a curator shift. README pitches the shipped half of this as core concept 4 (Knowledge stays current) plus a "When facts change" comparison row. Session working state note (D89, 2026-11-02) → BUILT, shipped 2026-11-03 as D90: 12th tool `memory_workingstate` on both hosts, session-start surfacing, `audit` expiry report, `wstate` CLI; opencode write path is instruction + tool (plugin API has no Stop hook).
|
|
584
584
|
|
|
585
585
|
- **Phase 5 — Candidates recorded 2026-10-04 (not committed).** From the competitor scan (D75): an offline FTS5 retrieval eval with a published recall number (gates any semantic-layer decision) [promoted to next build, D77] · per-client trust levels on the review ladder · cold-start Markdown import into outbox drafts · `doctor` check that each editor's MCP registration points at the intended data root (mis-rooted servers are a real failure mode elsewhere). Sequencing and scope TBD per candidate.
|
|
586
586
|
- **Phase 5 — Candidates recorded 2026-10-11 (not committed).** From the XERJ review (xerj-org/xerj, Apache-2.0; founder Ivan N requested open-memex D81 for the XERJ Corpus Hub — agreed 2026-10-11, attribution + repo link): schema-first querying (`xerj_map` — agent fetches the field map before writing query DSL; candidate: a schema/describe helper ahead of `memory_search` to cut dead queries) · token-budgeted MCP results (their `token_budget.rs` — truncate to a token budget, not a fixed row limit) · hybrid retrieval as the scale answer (BM25 + vector kNN with fused ranking, e.g. RRF — the reference pattern for the eventual embedding layer; our lexical ceiling is already measured at R@5 40.6% pooled) · NL-to-validated-query planning (`xerj_plan` — natural language in, validated query out; candidate: a query lint/validate step before search executes) · evidence-carrying memory links (typed links with evidence + confidence, soft-retire never hard-delete — same spirit as our review-state ladder; prior art for a future memory-graph direction) · honest isolation docs (state what a namespace guarantees and does NOT — query-level vs trust boundary; same spirit as our Limitations section) · cost-accounted evals (report tokens + dollars per approach, as in their case studies — the format for proving "memory makes agents cheaper"). Sequencing and scope TBD per candidate.
|
package/docs/design/decisions.md
CHANGED
|
@@ -1110,7 +1110,7 @@
|
|
|
1110
1110
|
*Status (2026-11-02): 已实现 — CHANGELOG 0.7.3 "Tool-definition quality pass (Glama TDQS 4.0/5 on v0.7.2): D76".*
|
|
1111
1111
|
|
|
1112
1112
|
- **D77 — measure usefulness by reuse, not storage (2026-10-07).** The Spark Tank submission commits the metric: "measured by reuse — fewer repeated questions, less context-prep time, approved memories reused by non-authors — not by memory count." Three layers, in build order: (1) **Offline retrieval eval.** A synthetic fixture (memories + queries with gold ids) run against the FTS5 baseline; publish recall@k/MRR in the README. This also answers the D75 "retrieval evaluation gate" open question — the number gates any future semantic-layer decision (reference points: agentmemory's published LongMemEval-S R@5 95.2%; lotargo/memory_plugin's BM25-only vs hybrid table). Later, run the MemoryAgentBench harness for directly comparable numbers (Knowl 90 / Mem0 18 / MIRIX 14 / Zep 7). (2) **Online reuse counters.** Per memory: `retrieved_count` (returned by search/list/first-turn injection) and `useful_count`, split into `useful_self` (author's own reuse — the personal-utility story) and `useful_team` (reuse of published project memories across sessions — the Spark Tank "reused by non-authors" story; no identity system needed: published state plus session diversity is the proxy). Both count as useful; reporting them separately keeps the team-knowledge claim honest. Explicit confirmation: a `memory_useful` tool call, human approve at review; behavioral: supersede/promote referencing it. Passive surfacing must never refresh usefulness — the opencode-memory lesson: unguarded exposure creates a self-reinforcing retrieval loop. Derived: `reuse_rate = useful / retrieved`; "zombie memories" (retrieved but never confirmed useful) surface in `memory_status` as decay/prune candidates. Counters live in SQLite, not frontmatter; local-only. (3) **Status surfaces.** `memory_status` gains a reuse report: top reused, zero-reuse list, per-scope reuse rate — feeding the Spark Tank pilot metrics. Moat note: competitors' "useful" is agent self-reported; our review ladder gives a human-grounded signal — approved/published means a human already said it is worth sharing. **Priority: this is the next build after 0.7.3** — fixture eval first (1–2 days, publishable number), then counters + `memory_useful`, then the status report, then the external bench.
|
|
1113
|
-
*Status (2026-11-
|
|
1113
|
+
*Status (2026-11-03): 部分实现 — 第 1 层 eval 已发;第 2 层已实现(0.9.0-alpha.2:`memory_usage` 表(独立于可重建索引,跨 rebuild 存活)+ `retrieved_count`/`useful_self`/`useful_team` + `memory_useful` 工具与 `open-memex useful` CLI;分类代理:personal 或未评审项目草稿→self,approved/published 项目记忆→team;supersede 与评审 approve 各自动计一次 useful;曝光只走 search/list/injection 的显式 `record` 开关);第 3 层(reuse 报告)未实现.*
|
|
1114
1114
|
|
|
1115
1115
|
- **D78 — pre-submit curation: human-on-the-loop, not in-the-loop (2026-10-07).** Fragmented captures must be organized before submit, but the submitter's patience is the scarce resource — every manual gate lowers the submit rate, so curation defaults to automatic and the human handles exceptions. Confidence tiers: **auto-apply** (exact duplicates, trivial fragments, inferred type/tags, title normalization); **batch-confirm** (semantic merges, splits — one summary screen, one tap to accept or undo, never per-item approval); **explicit human decision** (dropping substantive content, and submit itself — the D-hard boundary "project scope never auto-submits" stands: automation covers organizing, sharing stays human). The safety net is the supersede chain: every auto-merge preserves provenance and is undoable, so pre-approval is replaced by reversibility (undo-send, not confirm-dialog). Trigger: no new step to remember — `submit` becomes curate+submit in one command, with the curation summary attached to the PR description; session wrap-up is the alternative hook (batch-silent, per the D61 checkpoint posture). Closed loop: human undos feed back into confidence thresholds, consuming the D77 `useful_count` signals. This revises the earlier review-ladder instinct of per-item approval: the human moves from in-the-loop to on-the-loop.
|
|
1116
1116
|
*Status (2026-11-02): 未实现 — 纯设计条目:confidence 三档(auto-apply / batch-confirm / explicit human)、`submit` 变 curate+submit、undo-send 替代 pre-approval 均无代码.*
|
package/package.json
CHANGED
|
@@ -1,66 +1,66 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "open-memex",
|
|
3
|
-
"version": "0.9.0-alpha.
|
|
4
|
-
"mcpName": "io.github.stoneskin/open-memex",
|
|
5
|
-
"description": "Local-first memory layer and protocol for AI coding agents. Markdown source of truth, SQLite FTS5 index, zero cloud.",
|
|
6
|
-
"keywords": [
|
|
7
|
-
"mcp",
|
|
8
|
-
"model-context-protocol",
|
|
9
|
-
"mcp-server",
|
|
10
|
-
"opencode",
|
|
11
|
-
"ai-agents",
|
|
12
|
-
"agent-memory",
|
|
13
|
-
"persistent-memory",
|
|
14
|
-
"local-first",
|
|
15
|
-
"sqlite",
|
|
16
|
-
"fts5",
|
|
17
|
-
"markdown",
|
|
18
|
-
"memory",
|
|
19
|
-
"copilot",
|
|
20
|
-
"cursor",
|
|
21
|
-
"claude-code",
|
|
22
|
-
"vscode",
|
|
23
|
-
"knowledge-management",
|
|
24
|
-
"developer-tools",
|
|
25
|
-
"synonyms"
|
|
26
|
-
],
|
|
27
|
-
"type": "module",
|
|
28
|
-
"license": "Apache-2.0",
|
|
29
|
-
"repository": {
|
|
30
|
-
"type": "git",
|
|
31
|
-
"url": "git+https://github.com/stoneskin/open-memex.git"
|
|
32
|
-
},
|
|
33
|
-
"homepage": "https://github.com/stoneskin/open-memex#readme",
|
|
34
|
-
"bugs": {
|
|
35
|
-
"url": "https://github.com/stoneskin/open-memex/issues"
|
|
36
|
-
},
|
|
37
|
-
"main": "src/index.ts",
|
|
38
|
-
"scripts": {
|
|
39
|
-
"typecheck": "tsc --noEmit",
|
|
40
|
-
"cli": "node --experimental-strip-types src/cli.ts",
|
|
41
|
-
"mcp": "node --experimental-strip-types src/mcp.ts",
|
|
42
|
-
"build": "tsc -p tsconfig.build.json && node scripts/build-stamp.mjs",
|
|
43
|
-
"prepublishOnly": "npm run build",
|
|
44
|
-
"postinstall": "node scripts/postinstall.js",
|
|
45
|
-
"test-full": "node --experimental-strip-types scripts/test-full.ts"
|
|
46
|
-
},
|
|
47
|
-
"dependencies": {
|
|
48
|
-
"@modelcontextprotocol/sdk": "^1.30.1",
|
|
49
|
-
"better-sqlite3": "^13.0.3",
|
|
50
|
-
"js-yaml": "^4.1.0",
|
|
51
|
-
"zod": "^4.1.8"
|
|
52
|
-
},
|
|
53
|
-
"devDependencies": {
|
|
54
|
-
"@opencode-ai/plugin": "^1.18.30",
|
|
55
|
-
"@types/better-sqlite3": "^7.6.11",
|
|
56
|
-
"@types/js-yaml": "^4.0.9",
|
|
57
|
-
"@types/node": "^22.0.0",
|
|
58
|
-
"typescript": "^5.6.0"
|
|
59
|
-
},
|
|
60
|
-
"bin": {
|
|
61
|
-
"open-memex": "dist/cli.js"
|
|
62
|
-
},
|
|
63
|
-
"engines": {
|
|
64
|
-
"node": ">=22.14.0"
|
|
65
|
-
}
|
|
66
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "open-memex",
|
|
3
|
+
"version": "0.9.0-alpha.2",
|
|
4
|
+
"mcpName": "io.github.stoneskin/open-memex",
|
|
5
|
+
"description": "Local-first memory layer and protocol for AI coding agents. Markdown source of truth, SQLite FTS5 index, zero cloud.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"mcp",
|
|
8
|
+
"model-context-protocol",
|
|
9
|
+
"mcp-server",
|
|
10
|
+
"opencode",
|
|
11
|
+
"ai-agents",
|
|
12
|
+
"agent-memory",
|
|
13
|
+
"persistent-memory",
|
|
14
|
+
"local-first",
|
|
15
|
+
"sqlite",
|
|
16
|
+
"fts5",
|
|
17
|
+
"markdown",
|
|
18
|
+
"memory",
|
|
19
|
+
"copilot",
|
|
20
|
+
"cursor",
|
|
21
|
+
"claude-code",
|
|
22
|
+
"vscode",
|
|
23
|
+
"knowledge-management",
|
|
24
|
+
"developer-tools",
|
|
25
|
+
"synonyms"
|
|
26
|
+
],
|
|
27
|
+
"type": "module",
|
|
28
|
+
"license": "Apache-2.0",
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/stoneskin/open-memex.git"
|
|
32
|
+
},
|
|
33
|
+
"homepage": "https://github.com/stoneskin/open-memex#readme",
|
|
34
|
+
"bugs": {
|
|
35
|
+
"url": "https://github.com/stoneskin/open-memex/issues"
|
|
36
|
+
},
|
|
37
|
+
"main": "src/index.ts",
|
|
38
|
+
"scripts": {
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"cli": "node --experimental-strip-types src/cli.ts",
|
|
41
|
+
"mcp": "node --experimental-strip-types src/mcp.ts",
|
|
42
|
+
"build": "tsc -p tsconfig.build.json && node scripts/build-stamp.mjs",
|
|
43
|
+
"prepublishOnly": "npm run build",
|
|
44
|
+
"postinstall": "node scripts/postinstall.js",
|
|
45
|
+
"test-full": "node --experimental-strip-types scripts/test-full.ts"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@modelcontextprotocol/sdk": "^1.30.1",
|
|
49
|
+
"better-sqlite3": "^13.0.3",
|
|
50
|
+
"js-yaml": "^4.1.0",
|
|
51
|
+
"zod": "^4.1.8"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@opencode-ai/plugin": "^1.18.30",
|
|
55
|
+
"@types/better-sqlite3": "^7.6.11",
|
|
56
|
+
"@types/js-yaml": "^4.0.9",
|
|
57
|
+
"@types/node": "^22.0.0",
|
|
58
|
+
"typescript": "^5.6.0"
|
|
59
|
+
},
|
|
60
|
+
"bin": {
|
|
61
|
+
"open-memex": "dist/cli.js"
|
|
62
|
+
},
|
|
63
|
+
"engines": {
|
|
64
|
+
"node": ">=22.14.0"
|
|
65
|
+
}
|
|
66
|
+
}
|
package/scripts/smoke-mcp.ts
CHANGED
|
@@ -80,9 +80,9 @@ try {
|
|
|
80
80
|
const tools = await req("tools/list", {});
|
|
81
81
|
const names = (tools.result?.tools ?? []).map((t: any) => t.name).sort();
|
|
82
82
|
check(
|
|
83
|
-
"tools/list has
|
|
83
|
+
"tools/list has 13 memory tools",
|
|
84
84
|
JSON.stringify(names) ===
|
|
85
|
-
JSON.stringify(["memory_add", "memory_forget", "memory_list", "memory_pr_status", "memory_promote", "memory_propose", "memory_resolve", "memory_search", "memory_status", "memory_submit", "memory_supersede", "memory_workingstate"]),
|
|
85
|
+
JSON.stringify(["memory_add", "memory_forget", "memory_list", "memory_pr_status", "memory_promote", "memory_propose", "memory_resolve", "memory_search", "memory_status", "memory_submit", "memory_supersede", "memory_useful", "memory_workingstate"]),
|
|
86
86
|
names.join(","),
|
|
87
87
|
);
|
|
88
88
|
// D76: annotations must tell the truth — pr_status mutates with apply=true.
|
|
@@ -124,8 +124,7 @@ try {
|
|
|
124
124
|
|
|
125
125
|
const list = await req("tools/call", { name: "memory_list", arguments: {} });
|
|
126
126
|
const listText = list.result?.content?.[0]?.text ?? "";
|
|
127
|
-
check("memory_list works", listText.includes(savedId));
|
|
128
|
-
// D68: the list is the user's inventory — numbered, plain language,
|
|
127
|
+
check("memory_list works", listText.includes(savedId)); // D68: the list is the user's inventory — numbered, plain language,
|
|
129
128
|
// with provenance and age, not the raw developer format.
|
|
130
129
|
check("memory_list is numbered structured lines (D68)", /^\d+\. \[fact\] id=/m.test(listText), listText.slice(0, 120));
|
|
131
130
|
check("memory_list keeps raw provenance field (D68)", listText.includes("source=tool"), listText.slice(0, 160));
|
|
@@ -189,6 +188,43 @@ try {
|
|
|
189
188
|
const search2 = await req("tools/call", { name: "memory_search", arguments: { query: "mcp e2e probe" } });
|
|
190
189
|
check("memory gone after forget", !(search2.result?.content?.[0]?.text ?? "").includes(savedId));
|
|
191
190
|
|
|
191
|
+
// D77-L2:reuse counters — explicit useful only; exposure counts retrieved.
|
|
192
|
+
const missing = await req("tools/call", {
|
|
193
|
+
name: "memory_useful",
|
|
194
|
+
arguments: { id: "01NEVEREXISTED0000000000" },
|
|
195
|
+
});
|
|
196
|
+
check(
|
|
197
|
+
"memory_useful refuses an unknown id (D77-L2)",
|
|
198
|
+
!missing.result?.isError && /No memory with id/.test(missing.result?.content?.[0]?.text ?? ""),
|
|
199
|
+
(missing.result?.content?.[0]?.text ?? "").slice(0, 120),
|
|
200
|
+
);
|
|
201
|
+
|
|
202
|
+
const add3 = await req("tools/call", {
|
|
203
|
+
name: "memory_add",
|
|
204
|
+
arguments: { content: "mcp e2e probe: useful counter memory for D77", type: "fact" },
|
|
205
|
+
});
|
|
206
|
+
const savedId3 = ((add3.result?.content?.[0]?.text ?? "").match(/id=([A-Za-z0-9_]+)/) ?? [])[1];
|
|
207
|
+
check("D77 probe memory added", !!savedId3, (add3.result?.content?.[0]?.text ?? "").slice(0, 120));
|
|
208
|
+
|
|
209
|
+
const useful1 = await req("tools/call", {
|
|
210
|
+
name: "memory_useful",
|
|
211
|
+
arguments: { id: savedId3 },
|
|
212
|
+
});
|
|
213
|
+
const useful1Text: string = useful1.result?.content?.[0]?.text ?? "";
|
|
214
|
+
check("memory_useful marks useful_self (auto split: project draft)", useful1Text.includes("Marked useful (self)") && useful1Text.includes("useful_self: 1"), useful1Text.slice(0, 160));
|
|
215
|
+
check("memory_useful reports unretrieved honestly (D77-L2)", useful1Text.includes("n/a"), useful1Text.slice(0, 160));
|
|
216
|
+
|
|
217
|
+
await req("tools/call", { name: "memory_search", arguments: { query: "useful counter memory for D77" } });
|
|
218
|
+
const useful2 = await req("tools/call", {
|
|
219
|
+
name: "memory_useful",
|
|
220
|
+
arguments: { id: savedId3, kind: "team" },
|
|
221
|
+
});
|
|
222
|
+
const useful2Text: string = useful2.result?.content?.[0]?.text ?? "";
|
|
223
|
+
check("exposure was recorded by memory_search (D77-L2)", useful2Text.includes("retrieved: 1"), useful2Text.slice(0, 160));
|
|
224
|
+
check("memory_useful kind override lands in useful_team (D77-L2)", useful2Text.includes("useful_team: 1") && useful2Text.includes("Marked useful (team)"), useful2Text.slice(0, 160));
|
|
225
|
+
const forgetUseful = await req("tools/call", { name: "memory_forget", arguments: { id: savedId3 } });
|
|
226
|
+
check("D77 probe memory cleaned up", (forgetUseful.result?.content?.[0]?.text ?? "").includes("Deleted"), (forgetUseful.result?.content?.[0]?.text ?? "").slice(0, 120));
|
|
227
|
+
|
|
192
228
|
// §3.6 (D89): the working-state note round-trips, expires honestly, and
|
|
193
229
|
// its file lives OUTSIDE memories/ so the index never picks it up.
|
|
194
230
|
const wsRead0 = await req("tools/call", { name: "memory_workingstate", arguments: {} });
|
package/scripts/test-full.ts
CHANGED
|
@@ -802,6 +802,89 @@ ${body}
|
|
|
802
802
|
r.out.slice(0, 200),
|
|
803
803
|
);
|
|
804
804
|
|
|
805
|
+
// ---------- D77-L2: reuse counters + useful ----------
|
|
806
|
+
// Counters are SQLite-local telemetry (memory_usage table), never written
|
|
807
|
+
// into frontmatter. Exposure counts retrieved_count from search/list/
|
|
808
|
+
// CLI reads; useful only via `useful`/memory_useful, supersede, or a
|
|
809
|
+
// human promote to approved.
|
|
810
|
+
console.log("== usage counters (D77-L2) ==");
|
|
811
|
+
const d77Proj = mkproj("d77-proj");
|
|
812
|
+
const uId = addMem(["fulltest D77 useful-signal memory"], d77Proj);
|
|
813
|
+
ok("D77 probe memory added", !!uId);
|
|
814
|
+
|
|
815
|
+
// No exposure yet: never searched/listed (add alone is not a retrieval).
|
|
816
|
+
r = cliRetry(["useful", uId], d77Proj);
|
|
817
|
+
ok(
|
|
818
|
+
"cli useful marks self (unreviewed project draft) with 0 retrieved",
|
|
819
|
+
/useful \(self\) /.test(r.out) && /retrieved: 0/.test(r.out) && /useful_self: 1/.test(r.out),
|
|
820
|
+
r.out.slice(0, 200),
|
|
821
|
+
);
|
|
822
|
+
|
|
823
|
+
// The retrieval surfaces count exposures; the audit view does not.
|
|
824
|
+
cliRetry(["search", "useful-signal memory"], d77Proj);
|
|
825
|
+
cliRetry(["list"], d77Proj);
|
|
826
|
+
r = cliRetry(["list", "--include", "all"], d77Proj);
|
|
827
|
+
r = cliRetry(["useful", uId], d77Proj);
|
|
828
|
+
ok(
|
|
829
|
+
"search + list recorded exposures, audit view did not",
|
|
830
|
+
/retrieved: 2/.test(r.out) && /useful_self: 2/.test(r.out) && /reuse_rate: 1\.00/.test(r.out),
|
|
831
|
+
r.out.slice(0, 220),
|
|
832
|
+
);
|
|
833
|
+
|
|
834
|
+
// Unknown id fails the batch.
|
|
835
|
+
r = cliRetry(["useful", "01MISSING000000000000000000"], d77Proj);
|
|
836
|
+
ok("cli useful reports not found", /not found/.test(r.out + r.err), (r.out + r.err).slice(0, 120));
|
|
837
|
+
|
|
838
|
+
// Behavioral: supersede records a useful tick on the OLD memory.
|
|
839
|
+
const oldId = addMem(["fulltest D77 supersede-then-count target"], d77Proj);
|
|
840
|
+
r = cliRetry(["supersede", oldId, "fulltest D77 supersede target replaced"], d77Proj);
|
|
841
|
+
ok("supersede works (setup)", !!grabArrowId(r.out), r.out.slice(0, 120));
|
|
842
|
+
r = cliRetry(["useful", oldId], d77Proj);
|
|
843
|
+
// supersede already ticked useful_self on the old memory; the probe adds
|
|
844
|
+
// one explicit tick, so the printed counter reads 2.
|
|
845
|
+
ok(
|
|
846
|
+
"supersede counted as useful on the old memory (D77)",
|
|
847
|
+
/useful_self: 2/.test(r.out),
|
|
848
|
+
r.out.slice(0, 200),
|
|
849
|
+
);
|
|
850
|
+
|
|
851
|
+
// Behavioral: human approve at review records useful_team (no memory_useful call).
|
|
852
|
+
// Approved is reachable only through the review ladder: personal → propose
|
|
853
|
+
// (outbox draft) → submit (repo, proposed) → promote (approved).
|
|
854
|
+
const tId = addMem(["fulltest D77 review-approved memory", "--scope", "personal"], d77Proj);
|
|
855
|
+
const proposed = proposeMem(tId, d77Proj);
|
|
856
|
+
const submitted = cliRetry(["submit", proposed], d77Proj);
|
|
857
|
+
ok("approved-path submit works (setup)", submitted.code === 0, (submitted.err || submitted.out).slice(0, 150));
|
|
858
|
+
r = cliRetry(["promote", proposed], d77Proj);
|
|
859
|
+
ok("promote to approved works (setup)", /\bapproved\b/.test(r.out), r.out.slice(0, 160));
|
|
860
|
+
r = cliRetry(["useful", proposed], d77Proj);
|
|
861
|
+
// promote itself already ticked useful_team; the useful probe below adds
|
|
862
|
+
// one explicit tick on top, so the printed counter reads 2.
|
|
863
|
+
ok(
|
|
864
|
+
"promote → approved counted useful_team (D77)",
|
|
865
|
+
/useful_team: 2/.test(r.out) && /useful \(team\)/.test(r.out) && /useful_self: 0/.test(r.out),
|
|
866
|
+
r.out.slice(0, 220),
|
|
867
|
+
);
|
|
868
|
+
|
|
869
|
+
// Hard forget prunes the telemetry row (no phantom counters).
|
|
870
|
+
const deadId = addMem(["fulltest D77 to-be-forgotten memory"], d77Proj);
|
|
871
|
+
cliRetry(["forget", deadId], d77Proj);
|
|
872
|
+
r = cliRetry(["useful", deadId], d77Proj);
|
|
873
|
+
ok("forget pruned the usage row (D77-L2)", r.code !== 0 && /not found/.test(r.out + r.err), (r.out + r.err).slice(0, 120));
|
|
874
|
+
|
|
875
|
+
// Counters survive a full schema rebuild (memory_usage sits outside the
|
|
876
|
+
// rebuilt index tables; D77-L2 store design).
|
|
877
|
+
cliRetry(["reindex"], d77Proj);
|
|
878
|
+
r = cliRetry(["useful", uId], d77Proj);
|
|
879
|
+
ok(
|
|
880
|
+
"counters survive reindex",
|
|
881
|
+
/retrieved: 2/.test(r.out) || /retrieved: 3/.test(r.out),
|
|
882
|
+
r.out.slice(0, 160),
|
|
883
|
+
);
|
|
884
|
+
// NOTE: the reindex section's useful tick bumps useful_self by 1 — that is
|
|
885
|
+
// the probe itself, not persistence; the retrieved floor above is what
|
|
886
|
+
// proves the table survived the rebuild.
|
|
887
|
+
|
|
805
888
|
// JSON: no absolute local paths, and the format id records the change.
|
|
806
889
|
r = cliRetry(["inventory", "--format", "json"], PROJ);
|
|
807
890
|
const invJson2 = JSON.parse(r.out.slice(r.out.indexOf("{")));
|
|
@@ -80,6 +80,15 @@ try 2–3 phrasings per concept — synonyms, the user's other language, shorter
|
|
|
80
80
|
keyword forms — and check the other scope too, before concluding nothing is
|
|
81
81
|
stored.
|
|
82
82
|
|
|
83
|
+
## Record what paid off (D77)
|
|
84
|
+
|
|
85
|
+
When a person explicitly confirms a memory helped (or accepts work that
|
|
86
|
+
visibly relied on one), mark it: the `memory_useful` tool if available, else
|
|
87
|
+
`open-memex useful <id>`. Never mark a memory just because it appeared in
|
|
88
|
+
search results, a listing, or the session-start block — passive exposure is
|
|
89
|
+
counted automatically as `retrieved_count` and is not usefulness. Superseding
|
|
90
|
+
a memory or a human approving it at review already records a useful signal.
|
|
91
|
+
|
|
83
92
|
## Seeing and removing what is remembered
|
|
84
93
|
|
|
85
94
|
When the user asks "what do you remember about me?" (or wants to check or
|
package/src/cli.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { proposeMemories, promoteMemory, listConflicts, resolveConflict, formatR
|
|
|
10
10
|
import { getSyncStatus, formatSyncStatus, submitMemories } from "./submit.ts";
|
|
11
11
|
import { getPrStatus, formatPrStatus, applyPrStatus } from "./github.ts";
|
|
12
12
|
import { search, list, countList, hitStateLabel } from "./retrieve/search.ts";
|
|
13
|
+
import { recordUseful, getUsage, reuseRate, usefulCount, usefulKindFor, deleteUsage } from "./store/usage.ts";
|
|
13
14
|
import { DEFAULT_EXPANSIONS_WEIGHT } from "./retrieve/weights.ts";
|
|
14
15
|
import { formatInventoryLine, truncationNote } from "./retrieve/display.ts";
|
|
15
16
|
import {
|
|
@@ -164,6 +165,18 @@ Retraction is one-way: a retracted memory cannot be set back to active
|
|
|
164
165
|
Example:
|
|
165
166
|
open-memex status 01ABC deprecated`,
|
|
166
167
|
|
|
168
|
+
useful: `Mark a memory as useful (D77): record that it demonstrably paid
|
|
169
|
+
off. Useful is split automatically — useful_self for personal memories and
|
|
170
|
+
unpublished project drafts, useful_team for approved/published project
|
|
171
|
+
memories. Only explicit confirmation counts; passive retrieval (search/
|
|
172
|
+
list/injection) is counted separately as retrieved_count, never as useful.
|
|
173
|
+
A supersede or a human approval also records a useful signal on its own.
|
|
174
|
+
|
|
175
|
+
Usage: open-memex useful <id...>
|
|
176
|
+
|
|
177
|
+
Example:
|
|
178
|
+
open-memex useful 01ABC`,
|
|
179
|
+
|
|
167
180
|
forget: `Delete a memory by id. With --soft, hide it instead: the memory
|
|
168
181
|
is retracted (out of lists and search, file kept). Retraction is one-way —
|
|
169
182
|
save the content as a new memory to bring it back. If the memory lives in
|
|
@@ -429,7 +442,7 @@ Example:
|
|
|
429
442
|
doctor: `Environment health check: Node version, config source, scope resolution,
|
|
430
443
|
storage writability, VS Code MCP enablement (settings.json + system policy),
|
|
431
444
|
then boots a real MCP server and runs initialize + tools/list against it —
|
|
432
|
-
all
|
|
445
|
+
all thirteen tools must show up.
|
|
433
446
|
|
|
434
447
|
Usage: open-memex doctor
|
|
435
448
|
|
|
@@ -473,6 +486,7 @@ Usage:
|
|
|
473
486
|
open-memex add "content" [--scope project|personal] [--type T] [--tag t1,t2]
|
|
474
487
|
open-memex supersede <id> "new content" [--type T] [--tag t1,t2]
|
|
475
488
|
open-memex status <id> active|deprecated|retracted|archived
|
|
489
|
+
open-memex useful <id...>
|
|
476
490
|
open-memex forget <id> [--soft]
|
|
477
491
|
open-memex propose <id...> --to project [--local-approve]
|
|
478
492
|
open-memex promote <id> [--reject] [--resubmit] [--note "..."] [--by NAME]
|
|
@@ -521,8 +535,8 @@ first-turn injection); \`--yes\` accepts all defaults, and non-terminal runs nev
|
|
|
521
535
|
\`open-memex config set <key> <value>\` changes those settings after install.
|
|
522
536
|
|
|
523
537
|
Once installed globally (\`npm i -g open-memex\`) the \`open-memex\` command is
|
|
524
|
-
available directly: \`open-memex mcp\` starts the stdio MCP server (
|
|
525
|
-
the opencode plugin's
|
|
538
|
+
available directly: \`open-memex mcp\` starts the stdio MCP server (13 tools, a superset of
|
|
539
|
+
the opencode plugin's seven memory_* tools); \`open-memex mcp --print-config <client>\`
|
|
526
540
|
prints a copy-paste MCP client config snippet.
|
|
527
541
|
|
|
528
542
|
Scope defaults to \`project\` (derived from cwd's git remote or path).
|
|
@@ -1027,6 +1041,7 @@ async function main() {
|
|
|
1027
1041
|
type: flags.type,
|
|
1028
1042
|
limit: flags.limit ? Number(flags.limit) : undefined,
|
|
1029
1043
|
include,
|
|
1044
|
+
record: true,
|
|
1030
1045
|
});
|
|
1031
1046
|
const total = countList(s.key, { type: flags.type, include });
|
|
1032
1047
|
if (scopes.length > 1) {
|
|
@@ -1074,6 +1089,7 @@ async function main() {
|
|
|
1074
1089
|
limit: flags.limit ? Number(flags.limit) : undefined,
|
|
1075
1090
|
type: flags.type,
|
|
1076
1091
|
stats,
|
|
1092
|
+
record: true,
|
|
1077
1093
|
});
|
|
1078
1094
|
if (explain && stats) {
|
|
1079
1095
|
console.log(`fts: ${stats.ftsQuery || "(empty query)"}`);
|
|
@@ -1298,10 +1314,45 @@ async function main() {
|
|
|
1298
1314
|
}
|
|
1299
1315
|
}
|
|
1300
1316
|
deleteFromIndex(id);
|
|
1317
|
+
// D77-L2: hard forget prunes the usage row with the memory (the tool
|
|
1318
|
+
// path does the same); branch-switch removals go through syncScope and
|
|
1319
|
+
// keep counters for that reason.
|
|
1320
|
+
deleteUsage(id);
|
|
1301
1321
|
console.log(`deleted ${id}`);
|
|
1302
1322
|
return;
|
|
1303
1323
|
}
|
|
1304
1324
|
|
|
1325
|
+
if (cmd === "useful") {
|
|
1326
|
+
// D77-L2: the explicit confirmation route for humans. Auto-split like
|
|
1327
|
+
// the memory_useful tool; unknown ids fail that id without touching
|
|
1328
|
+
// the rest of the batch.
|
|
1329
|
+
const ids = rest;
|
|
1330
|
+
if (ids.length === 0) usage();
|
|
1331
|
+
syncScope(project.key, "cli");
|
|
1332
|
+
syncScope(PERSONAL_SCOPE.key, "cli");
|
|
1333
|
+
let notFound = 0;
|
|
1334
|
+
for (const id of ids) {
|
|
1335
|
+
const row = db()
|
|
1336
|
+
.prepare(`SELECT scope, review_state FROM memories WHERE id = ?`)
|
|
1337
|
+
.get(id) as { scope: string; review_state: string } | undefined;
|
|
1338
|
+
if (!row) {
|
|
1339
|
+
console.error(`not found: ${id}`);
|
|
1340
|
+
notFound++;
|
|
1341
|
+
continue;
|
|
1342
|
+
}
|
|
1343
|
+
const kind = usefulKindFor(row.scope, row.review_state);
|
|
1344
|
+
recordUseful(id, kind, "tool");
|
|
1345
|
+
const u = getUsage(id)!;
|
|
1346
|
+
const rate = reuseRate(u);
|
|
1347
|
+
const useful = usefulCount(u);
|
|
1348
|
+
console.log(
|
|
1349
|
+
`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})`,
|
|
1350
|
+
);
|
|
1351
|
+
}
|
|
1352
|
+
if (notFound > 0) process.exit(1);
|
|
1353
|
+
return;
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1305
1356
|
/** Positional args with flags (and their values) skipped. */
|
|
1306
1357
|
function positionalArgs(argv: string[]): string[] {
|
|
1307
1358
|
const out: string[] = [];
|