open-memex 0.9.0-alpha.2 → 0.9.0-alpha.3

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.
@@ -1,178 +1,319 @@
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.ts";
29
-
30
- export type UsefulKind = "self" | "team";
31
-
32
- export interface MemoryUsage {
33
- id: string;
34
- retrieved_count: number;
35
- useful_self: number;
36
- useful_team: number;
37
- last_retrieved_at: string; // RFC 3339, "" when never
38
- last_useful_at: string | null; // RFC 3339
39
- updated_at: string; // RFC 3339
40
- }
41
-
42
- export function usefulKindFor(scope: unknown, reviewState: unknown): UsefulKind {
43
- if (scope === "personal") return "self";
44
- // No identity system (D77): reviewed project knowledge reused = the team
45
- // story; everything else still reads as the author's own utility.
46
- if (reviewState === "approved" || reviewState === "published") return "team";
47
- return "self";
48
- }
49
-
50
- const INSERT_RETRIEVED_SQL = `
51
- INSERT INTO memory_usage (id, retrieved_count, useful_self, useful_team, last_retrieved_at, last_useful_at, updated_at)
52
- VALUES (?, 1, 0, 0, ?, NULL, ?)
53
- ON CONFLICT(id) DO UPDATE SET
54
- retrieved_count = memory_usage.retrieved_count + 1,
55
- last_retrieved_at = excluded.last_retrieved_at,
56
- updated_at = excluded.updated_at
57
- `;
58
-
59
- function insertUsefulSql(self: boolean): string {
60
- const col = self ? "useful_self" : "useful_team";
61
- return `
62
- INSERT INTO memory_usage (id, retrieved_count, useful_self, useful_team, last_retrieved_at, last_useful_at, updated_at)
63
- VALUES (?, 0, ${self ? 1 : 0}, ${self ? 0 : 1}, '', ?, ?)
64
- ON CONFLICT(id) DO UPDATE SET
65
- ${col} = memory_usage.${col} + 1,
66
- last_useful_at = excluded.last_useful_at,
67
- updated_at = excluded.updated_at
68
- `;
69
- }
70
-
71
- function rfc(ms: number): string {
72
- return new Date(ms).toISOString().replace(/\.000Z$/, "Z");
73
- }
74
-
75
- /**
76
- * Count one exposure each for the ids actually returned to a caller
77
- * (already limited/filtered — callers record the final hits, not the
78
- * candidate pool). Unknown/id-side dupes are absorbed: ids arrive deduped
79
- * (resolution collapses chains anyway); anything not in the index yet is
80
- * still counted — a just-saved memory can be hit in the same query that
81
- * created it only after upsert, so the index row exists by contract; a
82
- * missing one gets a row with last_retrieved_at set and no harm done.
83
- */
84
- export function recordRetrieved(ids: readonly string[], atMs: number = Date.now()): number {
85
- if (ids.length === 0) return 0;
86
- // No explicit transaction wrapper: both drivers' .transaction() returns a
87
- // deferred callable (calling it must NOT execute), and the common surface
88
- // here is stmt-exec only. Per-row autocommit on WAL is plenty for the
89
- // ≤50 ids one retrieval returns.
90
- const d = db();
91
- const at = rfc(atMs);
92
- const stmt = d.prepare(INSERT_RETRIEVED_SQL);
93
- for (const id of ids) stmt.run(id, at, at);
94
- return new Set(ids).size;
95
- }
96
-
97
- export const VIA_VALUES = ["tool", "supersede", "promote"] as const;
98
- export type UsefulVia = (typeof VIA_VALUES)[number];
99
-
100
- /**
101
- * Count one explicit useful signal. Returns the updated row, or null when
102
- * the id is not in the index (callers surface that as not-found — a useful
103
- * tick for a memory nobody has must not create phantom telemetry).
104
- */
105
- export function recordUseful(
106
- id: string,
107
- kind: UsefulKind,
108
- _via: UsefulVia,
109
- atMs: number = Date.now(),
110
- ): MemoryUsage | null {
111
- const d = db();
112
- const mem = d.prepare(`SELECT id FROM memories WHERE id = ?`).get(id) as
113
- | { id: string }
114
- | undefined;
115
- if (!mem) return null;
116
- const at = rfc(atMs);
117
- d.prepare(insertUsefulSql(kind === "self")).run(id, at, at);
118
- return getUsage(id);
119
- }
120
-
121
- export function getUsage(id: string): MemoryUsage | null {
122
- const row = db()
123
- .prepare(
124
- `SELECT id, retrieved_count, useful_self, useful_team,
125
- last_retrieved_at, last_useful_at, updated_at
126
- FROM memory_usage WHERE id = ?`,
127
- )
128
- .get(id) as MemoryUsage | undefined;
129
- if (!row) return null;
130
- row.retrieved_count = Number(row.retrieved_count) || 0;
131
- row.useful_self = Number(row.useful_self) || 0;
132
- row.useful_team = Number(row.useful_team) || 0;
133
- return row;
134
- }
135
-
136
- /** D77: useful_count = useful_self + useful_team — both count as useful. */
137
- export function usefulCount(u: Pick<MemoryUsage, "useful_self" | "useful_team">): number {
138
- return u.useful_self + u.useful_team;
139
- }
140
-
141
- /** reuse_rate = useful / retrieved (0 when the memory was never retrieved). */
142
- export function reuseRate(u: MemoryUsage): number | null {
143
- const n = usefulCount(u);
144
- if (u.retrieved_count <= 0) return null;
145
- return n / u.retrieved_count;
146
- }
147
-
148
- /** D77-L3's selection helpers ride the same table scan for free. */
149
- export function listUsage(scopeKey?: string): MemoryUsage[] {
150
- const sql = scopeKey
151
- ? `SELECT u.id, u.retrieved_count, u.useful_self, u.useful_team,
152
- u.last_retrieved_at, u.last_useful_at, u.updated_at
153
- FROM memory_usage u JOIN memories m ON m.id = u.id
154
- WHERE m.scope_key = ?`
155
- : `SELECT u.id, u.retrieved_count, u.useful_self, u.useful_team,
156
- u.last_retrieved_at, u.last_useful_at, u.updated_at
157
- FROM memory_usage u`;
158
- const args = scopeKey ? [scopeKey] : [];
159
- const rows = db().prepare(sql).all(...(args as unknown[])) as MemoryUsage[];
160
- for (const r of rows) {
161
- r.retrieved_count = Number(r.retrieved_count) || 0;
162
- r.useful_self = Number(r.useful_self) || 0;
163
- r.useful_team = Number(r.useful_team) || 0;
164
- }
165
- return rows;
166
- }
167
-
168
- /**
169
- * Drop one memory's telemetry. ONLY the hard-forget path calls this (the
170
- * memory is gone for good); plain index removal — which fires on a branch
171
- * switch, when in-repo files transiently disappear — must NOT prune here,
172
- * or switching branches would wipe counters the files will resurrect.
173
- * Superseded/deprecated/retracted memories keep their rows: their history
174
- * is part of the reuse story.
175
- */
176
- export function deleteUsage(id: string): void {
177
- db().prepare(`DELETE FROM memory_usage WHERE id = ?`).run(id);
178
- }
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.ts";
29
+ import type { ReuseEntry, ReuseReport, ReuseScopeStat } from "../reuse-report.ts";
30
+
31
+ export type UsefulKind = "self" | "team";
32
+
33
+ export interface MemoryUsage {
34
+ id: string;
35
+ retrieved_count: number;
36
+ useful_self: number;
37
+ useful_team: number;
38
+ last_retrieved_at: string; // RFC 3339, "" when never
39
+ last_useful_at: string | null; // RFC 3339
40
+ updated_at: string; // RFC 3339
41
+ }
42
+
43
+ export function usefulKindFor(scope: unknown, reviewState: unknown): UsefulKind {
44
+ if (scope === "personal") return "self";
45
+ // No identity system (D77): reviewed project knowledge reused = the team
46
+ // story; everything else still reads as the author's own utility.
47
+ if (reviewState === "approved" || reviewState === "published") return "team";
48
+ return "self";
49
+ }
50
+
51
+ const INSERT_RETRIEVED_SQL = `
52
+ INSERT INTO memory_usage (id, retrieved_count, useful_self, useful_team, last_retrieved_at, last_useful_at, updated_at)
53
+ VALUES (?, 1, 0, 0, ?, NULL, ?)
54
+ ON CONFLICT(id) DO UPDATE SET
55
+ retrieved_count = memory_usage.retrieved_count + 1,
56
+ last_retrieved_at = excluded.last_retrieved_at,
57
+ updated_at = excluded.updated_at
58
+ `;
59
+
60
+ function insertUsefulSql(self: boolean): string {
61
+ const col = self ? "useful_self" : "useful_team";
62
+ return `
63
+ INSERT INTO memory_usage (id, retrieved_count, useful_self, useful_team, last_retrieved_at, last_useful_at, updated_at)
64
+ VALUES (?, 0, ${self ? 1 : 0}, ${self ? 0 : 1}, '', ?, ?)
65
+ ON CONFLICT(id) DO UPDATE SET
66
+ ${col} = memory_usage.${col} + 1,
67
+ last_useful_at = excluded.last_useful_at,
68
+ updated_at = excluded.updated_at
69
+ `;
70
+ }
71
+
72
+ function rfc(ms: number): string {
73
+ return new Date(ms).toISOString().replace(/\.000Z$/, "Z");
74
+ }
75
+
76
+ /**
77
+ * Count one exposure each for the ids actually returned to a caller
78
+ * (already limited/filtered — callers record the final hits, not the
79
+ * candidate pool). Unknown/id-side dupes are absorbed: ids arrive deduped
80
+ * (resolution collapses chains anyway); anything not in the index yet is
81
+ * still counted — a just-saved memory can be hit in the same query that
82
+ * created it only after upsert, so the index row exists by contract; a
83
+ * missing one gets a row with last_retrieved_at set and no harm done.
84
+ */
85
+ export function recordRetrieved(ids: readonly string[], atMs: number = Date.now()): number {
86
+ if (ids.length === 0) return 0;
87
+ // No explicit transaction wrapper: both drivers' .transaction() returns a
88
+ // deferred callable (calling it must NOT execute), and the common surface
89
+ // here is stmt-exec only. Per-row autocommit on WAL is plenty for the
90
+ // ≤50 ids one retrieval returns.
91
+ const d = db();
92
+ const at = rfc(atMs);
93
+ const stmt = d.prepare(INSERT_RETRIEVED_SQL);
94
+ for (const id of ids) stmt.run(id, at, at);
95
+ return new Set(ids).size;
96
+ }
97
+
98
+ export const VIA_VALUES = ["tool", "supersede", "promote"] as const;
99
+ export type UsefulVia = (typeof VIA_VALUES)[number];
100
+
101
+ /**
102
+ * Count one explicit useful signal. The upsert is a single statement, so it
103
+ * is atomic on both drivers — there is deliberately no separate existence
104
+ * check: a memory can be valid on disk while its index row is momentarily
105
+ * missing (schema rebuild, or `findMemoryFile`'s file-scan fallback), and a
106
+ * guard keyed on `memories` would silently drop a real supersede/approve
107
+ * signal. The explicit surfaces (`memory_useful`, CLI `useful`) do their own
108
+ * not-found check before calling, so an agent's typo id never lands here.
109
+ * A concurrent hard forget can still leave an orphaned row; `listUsage`
110
+ * inner-joins `memories`, so orphans never surface in reports.
111
+ */
112
+ export function recordUseful(
113
+ id: string,
114
+ kind: UsefulKind,
115
+ _via: UsefulVia,
116
+ atMs: number = Date.now(),
117
+ ): MemoryUsage {
118
+ const d = db();
119
+ const at = rfc(atMs);
120
+ d.prepare(insertUsefulSql(kind === "self")).run(id, at, at);
121
+ // getUsage cannot miss the row just upserted.
122
+ return getUsage(id)!;
123
+ }
124
+
125
+ export function getUsage(id: string): MemoryUsage | null {
126
+ const row = db()
127
+ .prepare(
128
+ `SELECT id, retrieved_count, useful_self, useful_team,
129
+ last_retrieved_at, last_useful_at, updated_at
130
+ FROM memory_usage WHERE id = ?`,
131
+ )
132
+ .get(id) as MemoryUsage | undefined;
133
+ if (!row) return null;
134
+ row.retrieved_count = Number(row.retrieved_count) || 0;
135
+ row.useful_self = Number(row.useful_self) || 0;
136
+ row.useful_team = Number(row.useful_team) || 0;
137
+ return row;
138
+ }
139
+
140
+ /** D77: useful_count = useful_self + useful_team — both count as useful. */
141
+ export function usefulCount(u: Pick<MemoryUsage, "useful_self" | "useful_team">): number {
142
+ return u.useful_self + u.useful_team;
143
+ }
144
+
145
+ /** reuse_rate = useful / retrieved (0 when the memory was never retrieved). */
146
+ export function reuseRate(u: MemoryUsage): number | null {
147
+ const n = usefulCount(u);
148
+ if (u.retrieved_count <= 0) return null;
149
+ return n / u.retrieved_count;
150
+ }
151
+
152
+ /** D77-L3's selection helpers ride the same table scan for free. */
153
+ export function listUsage(scopeKey?: string): MemoryUsage[] {
154
+ const sql = scopeKey
155
+ ? `SELECT u.id, u.retrieved_count, u.useful_self, u.useful_team,
156
+ u.last_retrieved_at, u.last_useful_at, u.updated_at
157
+ FROM memory_usage u JOIN memories m ON m.id = u.id
158
+ WHERE m.scope_key = ?`
159
+ : `SELECT u.id, u.retrieved_count, u.useful_self, u.useful_team,
160
+ u.last_retrieved_at, u.last_useful_at, u.updated_at
161
+ FROM memory_usage u`;
162
+ const args = scopeKey ? [scopeKey] : [];
163
+ const rows = db().prepare(sql).all(...(args as unknown[])) as MemoryUsage[];
164
+ for (const r of rows) {
165
+ r.retrieved_count = Number(r.retrieved_count) || 0;
166
+ r.useful_self = Number(r.useful_self) || 0;
167
+ r.useful_team = Number(r.useful_team) || 0;
168
+ }
169
+ return rows;
170
+ }
171
+
172
+ /** One telemetry row joined to its memory's display fields (D77-L3). */
173
+ interface JoinedUsageRow {
174
+ id: string;
175
+ scope_key: string;
176
+ type: string;
177
+ review_state: string;
178
+ status: string;
179
+ content: string;
180
+ retrieved_count: number;
181
+ useful_self: number;
182
+ useful_team: number;
183
+ }
184
+
185
+ function oneLine(s: string, max = 120): string {
186
+ const t = s.replace(/\s+/g, " ").trim();
187
+ return t.length > max ? t.slice(0, max - 1) + "…" : t;
188
+ }
189
+
190
+ /**
191
+ * D77-L3: assemble the reuse report for the given scopes (personal and the
192
+ * current project on every surface). One join query, computed in JS — the
193
+ * store is local and the row count is a corpus, not a warehouse.
194
+ *
195
+ * Scope totals include every row with telemetry (retracted/archived too:
196
+ * their exposure was real while it lasted) and keep the useful split —
197
+ * D77 requires self vs team reported separately. The two actionable lists —
198
+ * top reused and zombies — exclude retracted/archived, because neither
199
+ * pruning nor celebrating a withdrawn memory helps; superseded/deprecated
200
+ * rows stay (their reuse is real) and carry their status so the render can
201
+ * mark them as history rather than current guidance.
202
+ */
203
+ export function loadReuseReport(
204
+ scopes: ReadonlyArray<{ scopeKey: string; label: string }>,
205
+ opts: { topLimit?: number; zombieLimit?: number } = {},
206
+ ): ReuseReport {
207
+ const topLimit = opts.topLimit ?? 5;
208
+ const zombieLimit = opts.zombieLimit ?? 5;
209
+ const labels = new Map(scopes.map((s) => [s.scopeKey, s.label]));
210
+ const empty: ReuseReport = {
211
+ scopes: scopes.map((s) => ({
212
+ label: s.label,
213
+ scopeKey: s.scopeKey,
214
+ tracked: 0,
215
+ retrieved: 0,
216
+ useful: 0,
217
+ usefulSelf: 0,
218
+ usefulTeam: 0,
219
+ rate: null,
220
+ })),
221
+ top: [],
222
+ topTotal: 0,
223
+ zombies: [],
224
+ zombieTotal: 0,
225
+ tracked: 0,
226
+ };
227
+ if (scopes.length === 0) return empty;
228
+
229
+ const keys = scopes.map((s) => s.scopeKey);
230
+ const rows = db()
231
+ .prepare(
232
+ `SELECT u.id, u.retrieved_count, u.useful_self, u.useful_team,
233
+ m.scope_key, m.type, m.review_state, m.status,
234
+ substr(m.content, 1, 200) AS content
235
+ FROM memory_usage u JOIN memories m ON m.id = u.id
236
+ WHERE m.scope_key IN (${keys.map(() => "?").join(",")})`,
237
+ )
238
+ .all(...(keys as unknown[])) as JoinedUsageRow[];
239
+
240
+ const byScope = new Map<string, ReuseScopeStat>();
241
+ for (const s of empty.scopes) byScope.set(s.scopeKey, s);
242
+
243
+ const tracked: ReuseEntry[] = [];
244
+ for (const r of rows) {
245
+ const retrieved = Number(r.retrieved_count) || 0;
246
+ const usefulSelf = Number(r.useful_self) || 0;
247
+ const usefulTeam = Number(r.useful_team) || 0;
248
+ const useful = usefulSelf + usefulTeam;
249
+ const stat = byScope.get(r.scope_key);
250
+ if (stat) {
251
+ stat.tracked++;
252
+ stat.retrieved += retrieved;
253
+ stat.useful += useful;
254
+ stat.usefulSelf += usefulSelf;
255
+ stat.usefulTeam += usefulTeam;
256
+ }
257
+ tracked.push({
258
+ id: r.id,
259
+ scopeKey: r.scope_key,
260
+ scopeLabel: labels.get(r.scope_key) ?? r.scope_key,
261
+ type: r.type,
262
+ reviewState: r.review_state ?? "draft",
263
+ status: r.status,
264
+ retrieved,
265
+ useful,
266
+ usefulSelf,
267
+ usefulTeam,
268
+ snippet: oneLine(r.content ?? ""),
269
+ });
270
+ }
271
+ for (const stat of byScope.values()) {
272
+ stat.rate = stat.retrieved > 0 ? stat.useful / stat.retrieved : null;
273
+ }
274
+
275
+ const actionable = tracked.filter(
276
+ (e) => e.status !== "retracted" && e.status !== "archived",
277
+ );
278
+ const top = actionable
279
+ .filter((e) => e.useful > 0)
280
+ .sort((a, b) => b.useful - a.useful || b.retrieved - a.retrieved || a.id.localeCompare(b.id));
281
+ const zombies = actionable
282
+ .filter((e) => e.retrieved > 0 && e.useful === 0)
283
+ .sort((a, b) => b.retrieved - a.retrieved || a.id.localeCompare(b.id));
284
+
285
+ const strip = (e: ReuseEntry): ReuseEntry => ({
286
+ id: e.id,
287
+ scopeKey: e.scopeKey,
288
+ scopeLabel: e.scopeLabel,
289
+ type: e.type,
290
+ reviewState: e.reviewState,
291
+ status: e.status,
292
+ retrieved: e.retrieved,
293
+ useful: e.useful,
294
+ usefulSelf: e.usefulSelf,
295
+ usefulTeam: e.usefulTeam,
296
+ snippet: e.snippet,
297
+ });
298
+
299
+ return {
300
+ scopes: empty.scopes,
301
+ top: top.slice(0, topLimit).map(strip),
302
+ topTotal: top.length,
303
+ zombies: zombies.slice(0, zombieLimit).map(strip),
304
+ zombieTotal: zombies.length,
305
+ tracked: tracked.length,
306
+ };
307
+ }
308
+
309
+ /**
310
+ * Drop one memory's telemetry. ONLY the hard-forget path calls this (the
311
+ * memory is gone for good); plain index removal — which fires on a branch
312
+ * switch, when in-repo files transiently disappear — must NOT prune here,
313
+ * or switching branches would wipe counters the files will resurrect.
314
+ * Superseded/deprecated/retracted memories keep their rows: their history
315
+ * is part of the reuse story.
316
+ */
317
+ export function deleteUsage(id: string): void {
318
+ db().prepare(`DELETE FROM memory_usage WHERE id = ?`).run(id);
319
+ }
package/src/tools/ops.ts CHANGED
@@ -32,7 +32,9 @@ import {
32
32
  usefulKindFor,
33
33
  usefulCount,
34
34
  deleteUsage,
35
+ loadReuseReport,
35
36
  } from "../store/usage.ts";
37
+ import { formatReuseReport } from "../reuse-report.ts";
36
38
  import { db } from "../store/db.ts";
37
39
  import { redact } from "../redact.ts";
38
40
  import { getSyncStatus, formatSyncStatus, submitMemories, outboxDraftCount } from "../submit.ts";
@@ -89,7 +91,7 @@ export const TOOL_DESCRIPTIONS = {
89
91
  memory_forget:
90
92
  "Delete a memory by id. Use when the user asks to forget something. To replace an outdated fact with a corrected one instead of deleting it, use memory_supersede. Deletion is permanent: before deleting, restate the memory's content to the user and get a confirmation. With soft=true the memory is hidden instead (retracted: out of lists and search, file kept, one-way).",
91
93
  memory_status:
92
- "Show the project memory sync pipeline: drafts waiting in the outbox (appdata), memories in the repo awaiting review or published, and any repo files not yet committed. Call this at session start, when the server reports drafts waiting for review, or when the user says 'sync memory' (or '同步记忆'); then ask the user which drafts to sync. For the memories themselves use memory_list; for PR review state use memory_pr_status. (MCP server and the `open-memex sync-status` CLI; the opencode native plugin does not expose this tool.)",
94
+ "Show the project memory sync pipeline: drafts waiting in the outbox (appdata), memories in the repo awaiting review or published, and any repo files not yet committed — plus the D77 reuse report: per-scope retrieved/useful rates, the most-reused memories, and \"zombies\" (retrieved but never confirmed useful). Call this at session start, when the server reports drafts waiting for review, when the user says 'sync memory' (or '同步记忆'), or when they ask what memory is pulling its weight. Then ask the user which drafts to sync. For the memories themselves use memory_list; for PR review state use memory_pr_status. (MCP server and the `open-memex sync-status` CLI; the opencode native plugin does not expose this tool.)",
93
95
  memory_submit:
94
96
  "Move outbox drafts into the repo memory dir for review: copies the drafts in as proposed (or keeps a local approval), commits locally on the current branch, and moves the outbox originals out. Never creates a branch on its own — pass branch= only with the user's explicit approval for the full chain. Prints the push and PR commands — those need the user's explicit approval and are never run automatically. (MCP server and the `open-memex submit` CLI; the opencode native plugin does not expose this tool.) Unknown ids or a failed local commit abort the submit with the reason; nothing is published automatically.",
95
97
  memory_propose:
@@ -660,14 +662,7 @@ export async function markMemoryUseful(
660
662
  };
661
663
  }
662
664
  const kind = args.kind ?? usefulKindFor(row.scope, row.review_state);
663
- const after = recordUseful(args.id, kind, "tool");
664
- // recordUseful re-checks existence; both branches above agree on not-found.
665
- if (!after) {
666
- return {
667
- title: "memory: useful not found",
668
- output: `No memory with id ${args.id} in the index.`,
669
- };
670
- }
665
+ recordUseful(args.id, kind, "tool");
671
666
  const u = getUsage(args.id)!;
672
667
  const rate = reuseRate(u);
673
668
  const useful = usefulCount(u);
@@ -684,9 +679,16 @@ export async function statusMemories(): Promise<ToolResult> {
684
679
  const n =
685
680
  st.outbox.length +
686
681
  st.inRepo.filter((e) => e.reviewState === "proposed" || e.reviewState === "approved").length;
682
+ // D77-L3: the reuse report rides the status surface (the D77 text calls
683
+ // memory_status out by name). Personal + this project, capped for an agent
684
+ // result; the CLI prints the same block uncapped.
685
+ const reuse = loadReuseReport([
686
+ { scopeKey: st.scopeKey, label: "this project" },
687
+ { scopeKey: PERSONAL_SCOPE.key, label: "personal" },
688
+ ]);
687
689
  return {
688
690
  title: `memory: sync status (${n} pending)`,
689
- output: formatSyncStatus(st),
691
+ output: [formatSyncStatus(st), "", ...formatReuseReport(reuse)].join("\n"),
690
692
  };
691
693
  }
692
694