open-memex 0.8.2 → 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.
Files changed (52) hide show
  1. package/AGENTS.md +21 -5
  2. package/CHANGELOG.md +10 -0
  3. package/README.md +46 -13
  4. package/README.zh-CN.md +25 -11
  5. package/dist/.build-stamp +1 -1
  6. package/dist/cli.js +103 -6
  7. package/dist/config.js +9 -0
  8. package/dist/doctor.js +4 -2
  9. package/dist/index.js +6 -1
  10. package/dist/init.js +13 -3
  11. package/dist/mcp.js +28 -5
  12. package/dist/opencode-v2.js +6 -2
  13. package/dist/plugin-core.js +28 -1
  14. package/dist/retrieve/inject.js +6 -0
  15. package/dist/retrieve/search.js +13 -2
  16. package/dist/review.js +7 -0
  17. package/dist/store/audit.js +14 -0
  18. package/dist/store/db.js +19 -0
  19. package/dist/store/lifecycle.js +8 -0
  20. package/dist/store/usage.js +151 -0
  21. package/dist/tools/memory.js +21 -2
  22. package/dist/tools/ops.js +123 -1
  23. package/dist/working-state.js +118 -0
  24. package/docs/CONCEPTS.md +16 -0
  25. package/docs/CONCEPTS.zh-CN.md +13 -0
  26. package/docs/V2-DESIGN.md +42 -1039
  27. package/docs/design/decisions.md +1146 -0
  28. package/docs/design/knowledge-graph.md +86 -0
  29. package/package.json +66 -66
  30. package/scripts/smoke-mcp.ts +67 -4
  31. package/scripts/smoke-pure.ts +70 -0
  32. package/scripts/test-full.ts +83 -0
  33. package/server.json +2 -2
  34. package/skills/open-memex/SKILL.md +19 -0
  35. package/src/cli.ts +111 -6
  36. package/src/config.ts +16 -0
  37. package/src/doctor.ts +4 -2
  38. package/src/index.ts +6 -0
  39. package/src/init.ts +13 -3
  40. package/src/mcp.ts +41 -4
  41. package/src/opencode-v2.ts +7 -2
  42. package/src/plugin-core.ts +32 -1
  43. package/src/retrieve/inject.ts +7 -0
  44. package/src/retrieve/search.ts +19 -3
  45. package/src/review.ts +6 -0
  46. package/src/store/audit.ts +20 -0
  47. package/src/store/db.ts +20 -0
  48. package/src/store/lifecycle.ts +9 -0
  49. package/src/store/usage.ts +178 -0
  50. package/src/tools/memory.ts +26 -1
  51. package/src/tools/ops.ts +158 -1
  52. package/src/working-state.ts +153 -0
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 {
@@ -23,6 +24,7 @@ import {
23
24
  import { loadConfig, configSource } from "./config.ts";
24
25
  import { paths, projectRoot, isInRepoMemoryFile } from "./paths.ts";
25
26
  import { redact } from "./redact.ts";
27
+ import { readWorkingState, clearWorkingState, workingStatePath } from "./working-state.ts";
26
28
  import { resolveMcpCommand } from "./init.ts";
27
29
  import fs from "node:fs";
28
30
  import path from "node:path";
@@ -163,6 +165,18 @@ Retraction is one-way: a retracted memory cannot be set back to active
163
165
  Example:
164
166
  open-memex status 01ABC deprecated`,
165
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
+
166
180
  forget: `Delete a memory by id. With --soft, hide it instead: the memory
167
181
  is retracted (out of lists and search, file kept). Retraction is one-way —
168
182
  save the content as a new memory to bring it back. If the memory lives in
@@ -428,7 +442,7 @@ Example:
428
442
  doctor: `Environment health check: Node version, config source, scope resolution,
429
443
  storage writability, VS Code MCP enablement (settings.json + system policy),
430
444
  then boots a real MCP server and runs initialize + tools/list against it —
431
- all eleven tools must show up.
445
+ all thirteen tools must show up.
432
446
 
433
447
  Usage: open-memex doctor
434
448
 
@@ -437,8 +451,8 @@ Example:
437
451
 
438
452
  audit: `Memory health audit (read-only, reports never mutates): near-duplicate
439
453
  pairs among active memories, stale actives untouched for 90+ days, broken
440
- supersede chains, personal files found inside the repo memory dir, and
441
- index/file drift.
454
+ supersede chains, personal files found inside the repo memory dir, index/file
455
+ drift, and expired working-state notes (D89).
442
456
 
443
457
  Usage: open-memex audit [--scope project|personal|both]
444
458
 
@@ -447,6 +461,19 @@ Flags:
447
461
 
448
462
  Example:
449
463
  open-memex audit --scope both`,
464
+
465
+ wstate: `Show the project's session working-state note (D89, §3.6) — the
466
+ ephemeral scratch note the agent refreshes at wrap-up so an interrupted task
467
+ can resume. The file itself is plain Markdown and editable directly.
468
+
469
+ Usage: open-memex wstate [--clear]
470
+
471
+ Flags:
472
+ --clear delete the note (no tombstone — it is scratch, not knowledge)
473
+
474
+ Examples:
475
+ open-memex wstate
476
+ open-memex wstate --clear`,
450
477
  };
451
478
 
452
479
  function usage(exitCode = 1): never {
@@ -459,6 +486,7 @@ Usage:
459
486
  open-memex add "content" [--scope project|personal] [--type T] [--tag t1,t2]
460
487
  open-memex supersede <id> "new content" [--type T] [--tag t1,t2]
461
488
  open-memex status <id> active|deprecated|retracted|archived
489
+ open-memex useful <id...>
462
490
  open-memex forget <id> [--soft]
463
491
  open-memex propose <id...> --to project [--local-approve]
464
492
  open-memex promote <id> [--reject] [--resubmit] [--note "..."] [--by NAME]
@@ -474,6 +502,7 @@ Usage:
474
502
  open-memex pr-status [--apply]
475
503
  open-memex reindex
476
504
  open-memex audit [--scope project|personal|both]
505
+ open-memex wstate [--clear]
477
506
  open-memex scopes
478
507
  open-memex migrate [--from <key>] [--to <key>]
479
508
  [--dry-run] [--on-conflict newer|overwrite|skip]
@@ -506,8 +535,8 @@ first-turn injection); \`--yes\` accepts all defaults, and non-terminal runs nev
506
535
  \`open-memex config set <key> <value>\` changes those settings after install.
507
536
 
508
537
  Once installed globally (\`npm i -g open-memex\`) the \`open-memex\` command is
509
- available directly: \`open-memex mcp\` starts the stdio MCP server (11 tools, a superset of
510
- the opencode plugin's five memory_* tools); \`open-memex mcp --print-config <client>\`
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>\`
511
540
  prints a copy-paste MCP client config snippet.
512
541
 
513
542
  Scope defaults to \`project\` (derived from cwd's git remote or path).
@@ -733,6 +762,40 @@ async function main() {
733
762
  const cfg = loadConfig();
734
763
  const project = resolveProjectScope(process.cwd());
735
764
 
765
+ // §3.6 (D89): human convenience surface for the working-state note —
766
+ // print it (with age/expiry) or delete it on request. The file itself is
767
+ // always editable directly; audit reports expired notes either way.
768
+ if (cmd === "wstate") {
769
+ const flags = parseFlags(rest);
770
+ if (flags["clear"] === "true") {
771
+ const gone = clearWorkingState(project.key);
772
+ console.log(
773
+ gone
774
+ ? `working-state note cleared (${project.key})`
775
+ : "nothing to clear — the note is still on disk; delete it manually if it exists",
776
+ );
777
+ return;
778
+ }
779
+ const note = readWorkingState(project.key, cfg.workingStateTtlDays);
780
+ if (!note) {
781
+ console.log(`no working-state note for ${project.key} — the agent writes one at wrap-up (memory_workingstate); you can edit the file directly`);
782
+ return;
783
+ }
784
+ if (!cfg.workingStateEnabled) {
785
+ console.log("(working state is disabled in config — workingStateEnabled=false)");
786
+ }
787
+ console.log(
788
+ note.expired
789
+ ? `EXPIRED — ${note.ageDays} day(s) old, ttl ${note.ttlDays} (ignored at session start; ` +
790
+ `audit keeps reporting it until the next wrap-up write or 'wstate --clear')`
791
+ : `updated ${note.ageDays} day(s) ago — expires after ${note.ttlDays} day(s)`,
792
+ );
793
+ console.log();
794
+ console.log(note.content || "(empty note)");
795
+ console.log(`\nfile: ${workingStatePath(project.key)}`);
796
+ return;
797
+ }
798
+
736
799
  // `migrate --to-v2` is a pure file operation (V2-DESIGN §19) — it runs
737
800
  // before the index is opened so it also works where the DB driver
738
801
  // isn't available.
@@ -840,6 +903,11 @@ async function main() {
840
903
  console.log(
841
904
  ` index drift: ${r.drift.filesNotIndexed} files not indexed, ${r.drift.rowsMissingFiles} rows missing files`,
842
905
  );
906
+ // D89: expired working-state notes — reports only, never auto-deletes.
907
+ console.log(` expired working-state notes: ${r.workingStateExpired.length}`);
908
+ for (const w of r.workingStateExpired) {
909
+ console.log(` ${w.filePath} — ${w.ageDays} days old (ttl ${w.ttlDays}); 'wstate --clear' or the next wrap-up write refreshes`);
910
+ }
843
911
  return;
844
912
  }
845
913
 
@@ -920,7 +988,7 @@ async function main() {
920
988
  return;
921
989
  }
922
990
 
923
- // `mcp` starts the stdio MCP server (11 tools; the opencode plugin exposes 5).
991
+ // `mcp` starts the stdio MCP server (12 tools; the opencode plugin exposes 6).
924
992
  // Branched before db() — runMcpServer() does its own init, and stdout must
925
993
  // stay clean for the MCP protocol.
926
994
  if (cmd === "mcp") {
@@ -973,6 +1041,7 @@ async function main() {
973
1041
  type: flags.type,
974
1042
  limit: flags.limit ? Number(flags.limit) : undefined,
975
1043
  include,
1044
+ record: true,
976
1045
  });
977
1046
  const total = countList(s.key, { type: flags.type, include });
978
1047
  if (scopes.length > 1) {
@@ -1020,6 +1089,7 @@ async function main() {
1020
1089
  limit: flags.limit ? Number(flags.limit) : undefined,
1021
1090
  type: flags.type,
1022
1091
  stats,
1092
+ record: true,
1023
1093
  });
1024
1094
  if (explain && stats) {
1025
1095
  console.log(`fts: ${stats.ftsQuery || "(empty query)"}`);
@@ -1244,10 +1314,45 @@ async function main() {
1244
1314
  }
1245
1315
  }
1246
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);
1247
1321
  console.log(`deleted ${id}`);
1248
1322
  return;
1249
1323
  }
1250
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
+
1251
1356
  /** Positional args with flags (and their values) skipped. */
1252
1357
  function positionalArgs(argv: string[]): string[] {
1253
1358
  const out: string[] = [];
package/src/config.ts CHANGED
@@ -15,6 +15,14 @@ export interface MyOMemoryConfig {
15
15
  * at init, default on; off = aliases passed by agents are dropped.
16
16
  */
17
17
  captureAliases: boolean;
18
+ /**
19
+ * D89: session working state note. `enabled` gates both the tool write
20
+ * path and the session-start surfacing; `ttlDays` is the default TTL the
21
+ * note's frontmatter stamps at write time (per-note `ttl_days` edits
22
+ * survive config changes afterwards).
23
+ */
24
+ workingStateEnabled: boolean;
25
+ workingStateTtlDays: number;
18
26
  /** Patterns whose capture group 1 becomes the memory body; saved to the current scope. */
19
27
  keywordPatterns: string[];
20
28
  /** Same shape, but hits are forced into the personal scope (e.g. "remember for me"). */
@@ -43,6 +51,8 @@ export const DEFAULT_CONFIG: MyOMemoryConfig = {
43
51
  injectOnFirstTurn: true,
44
52
  keywordCaptureEnabled: true,
45
53
  captureAliases: true,
54
+ workingStateEnabled: true,
55
+ workingStateTtlDays: 7,
46
56
  keywordPatterns: [
47
57
  "^\\s*remember(?!\\s+for\\s+me)(?:\\s+that|\\s+to)?[:,]?\\s+(.+)$",
48
58
  "^\\s*(?:please\\s+)?note(?:\\s+that)?[:,]?\\s+(.+)$",
@@ -183,6 +193,12 @@ export const SETTABLE_KEYS: Record<string, (v: unknown) => unknown> = {
183
193
  injectOnFirstTurn: toBool,
184
194
  keywordCaptureEnabled: toBool,
185
195
  captureAliases: toBool,
196
+ workingStateEnabled: toBool,
197
+ workingStateTtlDays: (v) => {
198
+ const n = toNonNegInt(v);
199
+ if (n < 1) throw new Error("must be a positive integer (days)");
200
+ return n;
201
+ },
186
202
  memoryDir: toRelativeDir,
187
203
  "sync.autoPull": toBool,
188
204
  logLevel: (v) => {
package/src/doctor.ts CHANGED
@@ -24,7 +24,7 @@ interface Check {
24
24
  detail: string;
25
25
  }
26
26
 
27
- // D64: the MCP server exposes eleven tools; checking only the five the
27
+ // D64: the MCP server exposes thirteen tools; checking only the seven the
28
28
  // opencode plugin carries let a half-registered server pass as healthy.
29
29
  const EXPECTED_TOOLS = [
30
30
  "memory_add",
@@ -32,6 +32,8 @@ const EXPECTED_TOOLS = [
32
32
  "memory_list",
33
33
  "memory_supersede",
34
34
  "memory_forget",
35
+ "memory_useful",
36
+ "memory_workingstate",
35
37
  "memory_status",
36
38
  "memory_submit",
37
39
  "memory_propose",
@@ -412,7 +414,7 @@ function opencodePluginCheck(): Check {
412
414
  }
413
415
  }
414
416
 
415
- /** Spawn the real MCP server, handshake, and verify the five tools list. */
417
+ /** Spawn the real MCP server, handshake, and verify the twelve tools list. */
416
418
  function mcpCheck(): Promise<Check> {
417
419
  const name = "mcp";
418
420
  return new Promise((resolve) => {
package/src/index.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  captureFromText,
6
6
  captureHandoff,
7
7
  injectOnce,
8
+ surfaceWorkingStateOnce,
8
9
  } from "./plugin-core.ts";
9
10
  import { pickScopeRoot } from "./scope.ts";
10
11
  import { makeTools } from "./tools/memory.ts";
@@ -43,6 +44,11 @@ const server: Plugin = async ({ worktree, directory }) => {
43
44
  injectOnce(sessionID, state, (block) => {
44
45
  output.system.push(block);
45
46
  });
47
+ // D89: the working-state note rides the same one-time pass — with a
48
+ // fresh note it surfaces even when the memory lists are empty.
49
+ surfaceWorkingStateOnce(sessionID, state, (block) => {
50
+ output.system.push(block);
51
+ });
46
52
  // D73: runs on every request, so the note lands on the very turn whose
47
53
  // message the hook just captured. Delivered once per capture.
48
54
  const handoff = captureHandoff(sessionID, state);
package/src/init.ts CHANGED
@@ -63,9 +63,9 @@ const INSTRUCTIONS = `${MARKER}
63
63
 
64
64
  You have a local memory MCP server (\`open-memex\`). Its tools are
65
65
  \`memory_add\`, \`memory_search\`, \`memory_list\`, \`memory_supersede\`,
66
- \`memory_forget\`, \`memory_status\`, \`memory_submit\`, \`memory_propose\`,
67
- \`memory_promote\`, \`memory_resolve\`, \`memory_pr_status\` — always call them by
68
- these full names.
66
+ \`memory_forget\`, \`memory_useful\`, \`memory_workingstate\`, \`memory_status\`,
67
+ \`memory_submit\`, \`memory_propose\`, \`memory_promote\`, \`memory_resolve\`,
68
+ \`memory_pr_status\` — always call them by these full names.
69
69
 
70
70
  - The server tells you when project outbox drafts are waiting for review — in
71
71
  tool results. When it does (or when the user asks), call \`memory_status\`
@@ -97,6 +97,16 @@ these full names.
97
97
  about the user that hold across all projects. When a saved fact becomes
98
98
  outdated, call \`memory_supersede\` (find the old memory's id with
99
99
  \`memory_search\` first) instead of adding a duplicate.
100
+ - When the user signals the session or task is wrapping up, refresh the
101
+ working-state note: call \`memory_workingstate\` (action=write) with a short
102
+ note — task summary, open files, last commands, where the work stands, next
103
+ step — so an interrupted task can resume in a fresh session. It is scratch
104
+ state, not durable knowledge: never save it as a memory.
105
+ - When a person confirms a memory was useful, or accepts work that clearly
106
+ relied on one, call \`memory_useful\` on it. NEVER call it just because a
107
+ memory appeared in search results or the session-start block: passive
108
+ exposure is counted separately and never counts as useful. Superseding a
109
+ memory or approving it at review already records its useful signal.
100
110
 
101
111
  ## Syncing project memories for review (D26)
102
112
 
package/src/mcp.ts CHANGED
@@ -3,8 +3,10 @@
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_status / memory_submit / memory_propose /
7
- * memory_promote / memory_resolve / memory_pr_status) over the Model Context Protocol, so any MCP client —
6
+ * memory_forget, plus memory_useful + memory_workingstate + memory_status /
7
+ * memory_submit / memory_propose / memory_promote / memory_resolve /
8
+ * memory_pr_status)
9
+ * over the Model Context Protocol, so any MCP client —
8
10
  * VS Code Copilot Chat, Cursor, Claude Code, etc. — can use open-memex
9
11
  * without a host-specific plugin.
10
12
  *
@@ -34,12 +36,14 @@ import {
34
36
  listMemories,
35
37
  supersedeMemory,
36
38
  forgetMemory,
39
+ markMemoryUseful,
37
40
  statusMemories,
38
41
  submitMemoriesOp,
39
42
  proposeMemoriesOp,
40
43
  promoteMemoryOp,
41
44
  resolveMemoryOp,
42
45
  prStatusOp,
46
+ workingStateMemory,
43
47
  memoryAddArgs,
44
48
  memorySearchArgs,
45
49
  memoryListArgs,
@@ -51,6 +55,8 @@ import {
51
55
  memoryPromoteArgs,
52
56
  memoryResolveArgs,
53
57
  memoryPrStatusArgs,
58
+ memoryWorkingStateArgs,
59
+ memoryUsefulArgs,
54
60
  TOOL_DESCRIPTIONS,
55
61
  withOutboxNote,
56
62
  type ToolResult,
@@ -79,8 +85,9 @@ const SERVER_VERSION: string = (() => {
79
85
  */
80
86
  const SERVER_INSTRUCTIONS = `You are connected to an open-memex local memory MCP server.
81
87
  Its tools are memory_add, memory_search, memory_list, memory_supersede,
82
- memory_forget, memory_status, memory_submit, memory_propose, memory_promote,
83
- memory_resolve, memory_pr_status — always call them by these full names.
88
+ memory_forget, memory_useful, memory_workingstate, memory_status, memory_submit,
89
+ memory_propose, memory_promote, memory_resolve, memory_pr_status — always call
90
+ them by these full names.
84
91
 
85
92
  - The server tells you when project outbox drafts are waiting for review —
86
93
  in tool results, and in these session-start instructions. When it does,
@@ -129,6 +136,16 @@ memory_resolve, memory_pr_status — always call them by these full names.
129
136
  about the user that hold across all projects. When a saved fact becomes
130
137
  outdated, call memory_supersede (find the old memory's id with memory_search
131
138
  first) instead of adding a duplicate.
139
+ - When the user signals the session or task is wrapping up, call
140
+ memory_workingstate (action=write) with a short note: task summary, open
141
+ files, last commands, where the work stands, next step — so an interrupted
142
+ task can resume. It is scratch state, not knowledge: do not save it as a
143
+ memory; durable conclusions still follow the propose-first flow above.
144
+ - When a person confirms a memory was useful, or accepted work that clearly
145
+ relied on one, call memory_useful on it. NEVER call memory_useful just
146
+ because a memory appeared in results or the session-start block — passive
147
+ exposure never counts as useful. (Superseding or approving a memory also
148
+ auto-records its useful signal; no need to duplicate those.)
132
149
  `;
133
150
 
134
151
  /** Adapt a framework-agnostic op result to an MCP tool response. */
@@ -254,6 +271,16 @@ export async function runMcpServer() {
254
271
  withSync((args) => toMcp(withOutboxNote(getScope().key, forgetMemory(args), "call memory_status to review"))),
255
272
  );
256
273
 
274
+ server.registerTool(
275
+ "memory_useful",
276
+ {
277
+ description: TOOL_DESCRIPTIONS.memory_useful,
278
+ inputSchema: z.object(memoryUsefulArgs),
279
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
280
+ },
281
+ withSync((args) => toMcp(markMemoryUseful(args))),
282
+ );
283
+
257
284
  server.registerTool(
258
285
  "memory_status",
259
286
  {
@@ -314,6 +341,16 @@ export async function runMcpServer() {
314
341
  withSync((args) => toMcp(prStatusOp(args))),
315
342
  );
316
343
 
344
+ server.registerTool(
345
+ "memory_workingstate",
346
+ {
347
+ description: TOOL_DESCRIPTIONS.memory_workingstate,
348
+ inputSchema: z.object(memoryWorkingStateArgs),
349
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
350
+ },
351
+ withSync((args) => toMcp(workingStateMemory(getScope, cfg, args))),
352
+ );
353
+
317
354
  const transport = new StdioServerTransport();
318
355
  await server.connect(transport);
319
356
  }
@@ -5,6 +5,7 @@ import {
5
5
  captureFromText,
6
6
  captureHandoff,
7
7
  injectOnce,
8
+ surfaceWorkingStateOnce,
8
9
  type PluginState,
9
10
  } from "./plugin-core.ts";
10
11
  import { makeTools } from "./tools/memory.ts";
@@ -30,7 +31,7 @@ import { makeTools } from "./tools/memory.ts";
30
31
  * verified on 2.0.1): by default the host exposes plugin tools only
31
32
  * through an `execute` meta-tool that runs model-written JS, and a model
32
33
  * that calls the tool by name instead gets "Unknown tool" — flaky,
33
- * model-dependent behavior. With the opt-out the five tools are plain
34
+ * model-dependent behavior. With the opt-out the seven tools are plain
34
35
  * function calls, same as on v1 and MCP.
35
36
  */
36
37
 
@@ -70,7 +71,7 @@ interface V2ContextEvent {
70
71
  system: unknown[];
71
72
  }
72
73
 
73
- /** Register the five memory tools on a v2 host. */
74
+ /** Register the seven memory tools on a v2 host. */
74
75
  async function registerTools(ctx: V2PluginContext, state: PluginState): Promise<void> {
75
76
  const tools = makeTools(() => state.scope, state.cfg);
76
77
  await ctx.tool.transform((editor) => {
@@ -111,6 +112,10 @@ export const v2Plugin = {
111
112
  injectOnce(sessionID, state, (block) => {
112
113
  ev.system.push({ type: "text", text: block });
113
114
  });
115
+ // D89: the working-state note rides the same one-time pass.
116
+ surfaceWorkingStateOnce(sessionID, state, (block) => {
117
+ ev.system.push({ type: "text", text: block });
118
+ });
114
119
  // D73: tell the agent what the keyword hook already stored this turn.
115
120
  const handoff = captureHandoff(sessionID, state);
116
121
  if (handoff) ev.system.push({ type: "text", text: handoff });
@@ -11,6 +11,7 @@ import {
11
11
  type Frontmatter,
12
12
  } from "./store/markdown.ts";
13
13
  import { buildContextBlock } from "./retrieve/inject.ts";
14
+ import { workingStateBlock } from "./working-state.ts";
14
15
  import { detectKeywords } from "./capture/keywords.ts";
15
16
  import {
16
17
  TURN_ECHO_WINDOW_MS,
@@ -34,6 +35,8 @@ export interface PluginState {
34
35
  scope: Scope;
35
36
  /** Sessions that already received the one-time context injection. */
36
37
  injectedSessions: Set<string>;
38
+ /** Sessions that already received the D89 working-state surfacing. */
39
+ workingStateSessions: Set<string>;
37
40
  /**
38
41
  * D73: what the keyword hook stored this session, so the agent can be told
39
42
  * before it re-saves the same statement. In memory only, like
@@ -72,7 +75,7 @@ export function bootstrapPlugin(root: string): PluginState {
72
75
  } catch (err) {
73
76
  console.error("[open-memex] init failed:", err);
74
77
  }
75
- return { cfg, scope, injectedSessions: new Set<string>(), captures: new Map() };
78
+ return { cfg, scope, injectedSessions: new Set<string>(), workingStateSessions: new Set<string>(), captures: new Map() };
76
79
  }
77
80
 
78
81
  /**
@@ -209,3 +212,31 @@ export function injectOnce(
209
212
  }
210
213
  return false;
211
214
  }
215
+
216
+ /**
217
+ * §3.6 (D89): surface the working-state note once per session, alongside
218
+ * the context injection. Scratch state, not knowledge — the block itself
219
+ * says what it is. Exactly-once uses the same in-memory Set discipline as
220
+ * `injectOnce` (not persisted; restarting the host re-surfaces). Expired
221
+ * or missing notes surface nothing.
222
+ */
223
+ export function surfaceWorkingStateOnce(
224
+ sessionID: string,
225
+ state: PluginState,
226
+ push: (block: string) => void,
227
+ ): boolean {
228
+ const { cfg, scope } = state;
229
+ if (!cfg.workingStateEnabled) return false;
230
+ if (state.workingStateSessions.has(sessionID)) return false;
231
+ state.workingStateSessions.add(sessionID);
232
+ try {
233
+ const block = workingStateBlock(scope.key, scope.projectName, cfg);
234
+ if (block) {
235
+ push(block);
236
+ return true;
237
+ }
238
+ } catch (err) {
239
+ console.error("[open-memex] working-state surfacing failed:", err);
240
+ }
241
+ return false;
242
+ }
@@ -1,4 +1,5 @@
1
1
  import { list, hitStateLabel } from "./search.ts";
2
+ import { recordRetrieved } from "../store/usage.ts";
2
3
  import type { Scope } from "../scope.ts";
3
4
  import { PERSONAL_SCOPE } from "../scope.ts";
4
5
  import type { MyOMemoryConfig } from "../config.ts";
@@ -14,6 +15,12 @@ export function buildContextBlock(scope: Scope, cfg: MyOMemoryConfig): string |
14
15
 
15
16
  if (project.length === 0 && user.length === 0) return null;
16
17
 
18
+ // D77-L2: the injection is a retrieval surface — the memories it puts in
19
+ // front of the agent were "returned", so they count as exposure. It must
20
+ // NOT touch the useful counters: passive surfacing never refreshes
21
+ // usefulness (D77).
22
+ recordRetrieved([...project.map((m) => m.id), ...user.map((m) => m.id)]);
23
+
17
24
  const lines: string[] = ["[OPEN-MEMEX]"];
18
25
 
19
26
  if (user.length > 0) {
@@ -6,6 +6,7 @@ import {
6
6
  planAliasExpansions,
7
7
  mergeRounds,
8
8
  } from "./alias-memory.ts";
9
+ import { recordRetrieved } from "../store/usage.ts";
9
10
 
10
11
  /** D83: which indexed column a hit's match came from. */
11
12
  export type MatchedVia = "body" | "alias" | "expansion" | "other";
@@ -222,6 +223,13 @@ export function search(
222
223
  * fixture can pick the value; not a per-call tuning surface.
223
224
  */
224
225
  expansionsWeight?: number;
226
+ /**
227
+ * D77-L2: count an exposure for every id this call returns
228
+ * (retrieved_count). Opt-in: the tool surfaces (memory_search /
229
+ * memory_list) and the CLI read commands pass true; eval/bench scripts
230
+ * leave it off so fixture runs never pollute real telemetry.
231
+ */
232
+ record?: boolean;
225
233
  } = {},
226
234
  ): SearchHit[] {
227
235
  const qflags = { stopwords: opts.stopwords, orJoin: opts.orJoin, prefix: opts.prefix };
@@ -329,12 +337,16 @@ export function search(
329
337
  // expands variants into the indexed aliases column at sync time), so
330
338
  // without a user alias the query side stays a single FTS round.
331
339
  if (opts.stats) opts.stats.candidates = merged.length;
332
- return resolveVisible(merged, limit, opts.stats);
340
+ const hits = resolveVisible(merged, limit, opts.stats);
341
+ // D77-L2: record only the ids actually returned — the candidate pool is
342
+ // not an exposure, and #53 guarantees the cut below is the final result.
343
+ if (opts.record && hits.length > 0) recordRetrieved(hits.map((h) => h.id));
344
+ return hits;
333
345
  }
334
346
 
335
347
  export function list(
336
348
  scopeKey: string,
337
- opts: { type?: string; limit?: number; include?: "active" | "all" } = {},
349
+ opts: { type?: string; limit?: number; include?: "active" | "all"; record?: boolean } = {},
338
350
  ): SearchHit[] {
339
351
  const limit = Math.max(1, Math.min(opts.limit ?? 20, 100));
340
352
  const fetchLimit = Math.min(limit * 3 + 10, 150);
@@ -372,9 +384,13 @@ export function list(
372
384
  if (opts.include === "all") {
373
385
  // D68: the audit view — every row as stored (superseded versions,
374
386
  // retracted, archived), no chain collapsing, capped at limit.
387
+ // NOT an exposure (D77-L2): the audit view is inspection for pruning
388
+ // decisions; counting it would inflate memories the user never saw.
375
389
  return raw.slice(0, limit).map(toHit);
376
390
  }
377
- return resolveVisible(raw, limit);
391
+ const hits = resolveVisible(raw, limit);
392
+ if (opts.record && hits.length > 0) recordRetrieved(hits.map((h) => h.id));
393
+ return hits;
378
394
  }
379
395
 
380
396
  /**
package/src/review.ts CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  } from "./store/markdown.ts";
37
37
  import { findMemoryFile } from "./store/lifecycle.ts";
38
38
  import { upsertFromFile } from "./store/sync.ts";
39
+ import { recordUseful } from "./store/usage.ts";
39
40
 
40
41
  /** Best-effort author identity: git user.name, else the OS user. */
41
42
  export function currentAuthor(): string {
@@ -249,6 +250,11 @@ export function promoteMemory(
249
250
  };
250
251
  atomicWriteTextSync(mf.filePath, serialize(fm, mf.body));
251
252
  upsertFromFile({ fm, body: mf.body, filePath: mf.filePath, mtimeMs: Date.now() });
253
+ // D77-L2: a human approve at review is exactly the "explicit confirmation"
254
+ // the D77 useful definition names. One tick per approve step — the later
255
+ // published transition passes through approved and does not re-count.
256
+ // Always useful_team: promoteMemory is project-only by contract above.
257
+ if (to === "approved") recordUseful(id, "team", "promote");
252
258
  return { id, from, to, history: fm.review_history };
253
259
  }
254
260
 
@@ -8,6 +8,7 @@ import {
8
8
  import { similarity, NEAR_DUP_THRESHOLD } from "./lifecycle.ts";
9
9
  import { projectRoot } from "../paths.ts";
10
10
  import { loadConfig } from "../config.ts";
11
+ import { readWorkingState, workingStatePath } from "../working-state.ts";
11
12
 
12
13
  // Memory health audit (D57). Read-only: reports, never mutates.
13
14
  // Checks, per open question "retrieval explainability & memory health":
@@ -46,6 +47,9 @@ export interface AuditReport {
46
47
  brokenChains: { id: string; scopeKey: string; missingTarget: string }[];
47
48
  personalInRepo: string[];
48
49
  drift: { filesNotIndexed: number; rowsMissingFiles: number };
50
+ /** D89: working-state notes past their TTL. Reports only, never
51
+ * auto-deletes (D57 posture) — the next wrap-up write overwrites. */
52
+ workingStateExpired: { scopeKey: string; filePath: string; ageDays: number; ttlDays: number }[];
49
53
  }
50
54
 
51
55
  export function runAudit(scopeKeys: string[]): AuditReport {
@@ -125,6 +129,21 @@ export function runAudit(scopeKeys: string[]): AuditReport {
125
129
  }
126
130
  }
127
131
 
132
+ // D89: expired working-state notes. Reports only, never auto-deletes
133
+ // (D57 posture) — the next wrap-up write overwrites them.
134
+ const cfg = loadConfig();
135
+ const workingStateExpired = scopeKeys
136
+ .map((key) => ({ key, note: readWorkingState(key, cfg.workingStateTtlDays) }))
137
+ .filter((e): e is { key: string; note: NonNullable<ReturnType<typeof readWorkingState>> } =>
138
+ Boolean(e.note?.expired),
139
+ )
140
+ .map((e) => ({
141
+ scopeKey: e.key,
142
+ filePath: workingStatePath(e.key),
143
+ ageDays: e.note!.ageDays,
144
+ ttlDays: e.note!.ttlDays,
145
+ }));
146
+
128
147
  return {
129
148
  totalMemories: inScope.length,
130
149
  duplicatePairs: pairs,
@@ -132,5 +151,6 @@ export function runAudit(scopeKeys: string[]): AuditReport {
132
151
  brokenChains,
133
152
  personalInRepo,
134
153
  drift: { filesNotIndexed, rowsMissingFiles },
154
+ workingStateExpired,
135
155
  };
136
156
  }