open-memex 0.7.0-alpha.8 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/AGENTS.md +8 -3
  2. package/CHANGELOG.md +40 -0
  3. package/README.md +17 -3
  4. package/README.zh-CN.md +12 -3
  5. package/dist/.build-stamp +1 -1
  6. package/dist/capture/handoff.js +59 -0
  7. package/dist/cli.js +188 -19
  8. package/dist/distill-agents.js +4 -1
  9. package/dist/index.js +14 -6
  10. package/dist/inventory-html.js +150 -0
  11. package/dist/inventory.js +176 -0
  12. package/dist/mcp.js +9 -0
  13. package/dist/opencode-v2.js +8 -3
  14. package/dist/paths.js +18 -0
  15. package/dist/plugin-core.js +48 -3
  16. package/dist/retrieve/display.js +161 -0
  17. package/dist/retrieve/search.js +33 -3
  18. package/dist/scope.js +17 -0
  19. package/dist/store/lifecycle.js +42 -0
  20. package/dist/tools/ops.js +92 -22
  21. package/docs/TEST-PLAN.md +1 -1
  22. package/docs/V2-DESIGN.md +117 -2
  23. package/docs/memory-visibility-design.md +130 -0
  24. package/package.json +2 -2
  25. package/scripts/build-stamp.mjs +62 -62
  26. package/scripts/smoke-mcp.ts +47 -1
  27. package/scripts/smoke-pure.ts +85 -1
  28. package/scripts/test-full.ts +192 -5
  29. package/skills/open-memex/SKILL.md +29 -0
  30. package/src/capture/handoff.ts +74 -0
  31. package/src/cli.ts +202 -19
  32. package/src/distill-agents.ts +7 -0
  33. package/src/index.ts +13 -5
  34. package/src/inventory-html.ts +191 -0
  35. package/src/inventory.ts +242 -0
  36. package/src/mcp.ts +9 -0
  37. package/src/opencode-v2.ts +7 -2
  38. package/src/paths.ts +19 -0
  39. package/src/plugin-core.ts +62 -3
  40. package/src/retrieve/display.ts +174 -0
  41. package/src/retrieve/search.ts +49 -4
  42. package/src/scope.ts +18 -0
  43. package/src/store/lifecycle.ts +52 -0
  44. package/src/tools/ops.ts +99 -27
@@ -0,0 +1,150 @@
1
+ /**
2
+ * HTML renderer for the inventory (D68 follow-up): a single local file
3
+ * a user opens in any browser to read what the store remembers. It
4
+ * renders the SAME data layer as the text/JSON formats
5
+ * (`src/inventory.ts`) — one source, three renderings, no drift.
6
+ *
7
+ * Design rules (3-C v2) enforced here:
8
+ * - Every byte of memory content is HTML-escaped. Memory text can come
9
+ * from an imported bundle or a pasted web page; under file:// an
10
+ * unescaped <script> would execute in the user's own browser.
11
+ * - The filter box is plain show/hide over server-rendered entries
12
+ * (no innerHTML, no network, no external resources).
13
+ * - History (superseded versions, retracted, archived) is a folded
14
+ * section with supersede-chain pointers — auditable, never mixed
15
+ * into "what is remembered now". At scale (>50 current entries) the
16
+ * scope sections fold too.
17
+ * - Read-only: no delete buttons, no server callback. Deletion stays a
18
+ * confirmed conversation; the page says so, with the id to quote.
19
+ */
20
+ import path from "node:path";
21
+ import { PERSONAL_SCOPE } from "./scope.js";
22
+ import { escapeHtml, relativeTime, reviewStateLabel, sourceLabel, } from "./retrieve/display.js";
23
+ const FOLD_THRESHOLD = 50;
24
+ function entryHtml(row, now) {
25
+ const meta = [escapeHtml(sourceLabel(row.source))];
26
+ const when = relativeTime(row.created_at, now);
27
+ if (when)
28
+ meta.push(escapeHtml(when));
29
+ if (row.scope_key !== PERSONAL_SCOPE.key) {
30
+ meta.push(escapeHtml(reviewStateLabel(row.review_state)));
31
+ if (row.review_state !== "draft") {
32
+ meta.push(row.file_path.replace(/\\/g, "/").includes("/.ai/open-memex/")
33
+ ? "file is in the repo"
34
+ : "file is not in the repo yet");
35
+ }
36
+ }
37
+ if (row.status !== "active")
38
+ meta.push(escapeHtml(`marked ${row.status}`));
39
+ return ` <article class="entry">
40
+ <p class="body">${escapeHtml(row.content.trim())}</p>
41
+ <p class="meta">${meta.join(" · ")} · <span class="id">id ${escapeHtml(row.id)}</span></p>
42
+ </article>`;
43
+ }
44
+ function hiddenEntryHtml(row, now) {
45
+ const when = relativeTime(row.created_at, now);
46
+ const chain = row.superseded_by
47
+ ? ` · replaced by <span class="id">${escapeHtml(row.superseded_by)}</span>`
48
+ : "";
49
+ return ` <article class="entry hidden-entry">
50
+ <p class="body">${escapeHtml(row.content.trim())}</p>
51
+ <p class="meta">${escapeHtml(row.status)}${when ? ` · saved ${escapeHtml(when)}` : ""}${chain} · <span class="id">id ${escapeHtml(row.id)}</span></p>
52
+ </article>`;
53
+ }
54
+ function sectionHtml(title, blurb, entries, count, fold, open) {
55
+ if (fold) {
56
+ return ` <details${open ? " open" : ""}>
57
+ <summary>${escapeHtml(title)} <span class="count">${count}</span></summary>
58
+ <p class="blurb">${escapeHtml(blurb)}</p>
59
+ ${entries}
60
+ </details>`;
61
+ }
62
+ return ` <section>
63
+ <h2>${escapeHtml(title)} <span class="count">${count}</span></h2>
64
+ <p class="blurb">${escapeHtml(blurb)}</p>
65
+ ${entries || ' <p class="empty">(nothing here yet)</p>'}
66
+ </section>`;
67
+ }
68
+ export function renderInventoryHtml(data) {
69
+ const now = Date.now();
70
+ const fold = data.total > FOLD_THRESHOLD;
71
+ const personalCount = data.scopes
72
+ .filter((s) => s.scopeKey === PERSONAL_SCOPE.key)
73
+ .reduce((n, s) => n + s.rows.length, 0);
74
+ const parts = [];
75
+ data.scopes.forEach((s, i) => {
76
+ const isPersonal = s.scopeKey === PERSONAL_SCOPE.key;
77
+ parts.push(sectionHtml(isPersonal ? "About you — personal" : `Project: ${s.projectName}`, isPersonal
78
+ ? "These describe you, apply in every project, and never leave this machine."
79
+ : "Project memories. Each entry says whether it is still only on this machine (the outbox) or has reached the repo.", s.rows.map((r) => entryHtml(r, now)).join("\n"), s.rows.length, fold, isPersonal || i === 0));
80
+ });
81
+ if (data.outbox.length > 0) {
82
+ parts.push(sectionHtml("Not in the repo yet — outbox drafts", "These drafts exist only on this machine. They reach the repo through review (submit → promote), never automatically.", data.outbox.map((r) => entryHtml(r, now)).join("\n"), data.outbox.length, fold, false));
83
+ }
84
+ if (data.hiddenEntries.length > 0) {
85
+ const h = data.hiddenEntries.map((r) => hiddenEntryHtml(r, now)).join("\n");
86
+ parts.push(` <details>
87
+ <summary>Replaced &amp; hidden history <span class="count">${data.hiddenEntries.length}</span></summary>
88
+ <p class="blurb">Older versions and withdrawn memories. Kept so you can audit how a fact changed; none of this is used for recall.</p>
89
+ ${h}
90
+ </details>`);
91
+ }
92
+ return `<!doctype html>
93
+ <html lang="en">
94
+ <head>
95
+ <meta charset="utf-8">
96
+ <meta name="viewport" content="width=device-width, initial-scale=1">
97
+ <!-- D70: the page claims it makes no network requests - enforce it. Inline
98
+ style/script are the only allowances; anything else (a stray <img
99
+ src>, a remote font) is blocked by the browser, not just by our promise. -->
100
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'">
101
+ <title>What OpenMemex remembers</title>
102
+ <style>
103
+ body { font-family: system-ui, sans-serif; margin: 2rem auto; max-width: 44rem; padding: 0 1rem; color: #1a1a1a; background: #fdfdfb; }
104
+ h1 { font-size: 1.4rem; margin-bottom: 0.25rem; }
105
+ h2, summary { font-size: 1.1rem; font-weight: 600; }
106
+ summary { cursor: pointer; margin: 1.2rem 0 0.4rem; }
107
+ .sub { color: #666; font-size: 0.9rem; margin-top: 0; }
108
+ .count { color: #888; font-weight: normal; font-size: 0.85em; }
109
+ .blurb { color: #555; font-size: 0.9rem; }
110
+ .entry { border-top: 1px solid #e5e2d9; padding: 0.75rem 0; }
111
+ .hidden-entry { opacity: 0.75; }
112
+ .body { white-space: pre-wrap; margin: 0 0 0.35rem; }
113
+ .meta { color: #666; font-size: 0.82rem; margin: 0; }
114
+ .id { font-family: ui-monospace, monospace; font-size: 0.78rem; }
115
+ .empty { color: #888; }
116
+ .howto { background: #f4f1e8; border-radius: 6px; padding: 0.75rem 1rem; font-size: 0.9rem; }
117
+ input[type="search"] { width: 100%; padding: 0.5rem; font-size: 1rem; margin: 1rem 0; box-sizing: border-box; }
118
+ .hidden { display: none; }
119
+ </style>
120
+ </head>
121
+ <body>
122
+ <h1>What OpenMemex remembers about you</h1>
123
+ <p class="sub">Generated ${escapeHtml(data.generatedAt)} · ${data.total} memories (${personalCount} personal, ${data.total - personalCount} project incl. outbox). Read-only report.</p>
124
+ <input type="search" id="filter" placeholder="Filter memories…" aria-label="Filter memories">
125
+ <div class="howto">
126
+ <strong>Checking my work:</strong> every entry shows where it came from.
127
+ “I inferred this” means I wrote it from context, not from your words — those are the ones to check.
128
+ To remove one, tell your agent <em>“forget the memory about …”</em> (quote the id if you like) and it will read the entry back before deleting it — deletion is permanent, there is no undo.
129
+ A memory that lives in a repo is only truly gone once the deletion is committed.
130
+ </div>
131
+ ${parts.join("\n")}
132
+ <script>
133
+ var input = document.getElementById('filter');
134
+ input.addEventListener('input', function () {
135
+ var q = input.value.trim().toLowerCase();
136
+ var entries = document.querySelectorAll('.entry');
137
+ for (var i = 0; i < entries.length; i++) {
138
+ var el = entries[i];
139
+ el.classList.toggle('hidden', q !== '' && el.textContent.toLowerCase().indexOf(q) === -1);
140
+ }
141
+ });
142
+ </script>
143
+ </body>
144
+ </html>
145
+ `;
146
+ }
147
+ /** Default report location: the data dir, never a working tree. */
148
+ export function defaultHtmlOutPath(dataRoot) {
149
+ return path.join(dataRoot, "inventory.html");
150
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * `open-memex inventory` (D68): what the store remembers, in the open.
3
+ * One data layer, three renderers (text / json / html). The HTML
4
+ * renderer lives in inventory-html.ts; this module owns the data and
5
+ * the two renderers an agent or a terminal consumes directly.
6
+ *
7
+ * Design rules (3-C v2) enforced here:
8
+ * - Default scope is personal + the current project — "can't see it"
9
+ * is the disease this surface treats.
10
+ * - Nothing truncates silently: every section states its totals, and
11
+ * hidden history (superseded versions, retracted, archived) is
12
+ * counted and pointed at, never just omitted.
13
+ * - Drafts that have not reached the repo (the outbox) are their own
14
+ * section, consistent with what memory_status reports.
15
+ * - The report is read-only. Deleting stays a confirmed conversation.
16
+ */
17
+ import { db } from "./store/db.js";
18
+ import { PERSONAL_SCOPE } from "./scope.js";
19
+ import { formatInventoryLine } from "./retrieve/display.js";
20
+ const BASE_COLS = `id, scope_key, project_name, type, status, review_state,
21
+ source, created_at, updated_at, content, file_path`;
22
+ /**
23
+ * Load the inventory for the given scopes. `projectScopeKey` separates the
24
+ * outbox drafts (they belong to that scope's draft rows).
25
+ *
26
+ * D70: `hidden: "entries"` fetches the hidden rows themselves (HTML audit
27
+ * view); the default keeps the cheap COUNT query, because pulling every
28
+ * superseded body for a text report nobody reads is pure waste.
29
+ */
30
+ export function loadInventory(scopeKeys, opts = {}) {
31
+ const inList = scopeKeys.map(() => "?").join(",");
32
+ const current = db()
33
+ .prepare(`SELECT ${BASE_COLS} FROM memories
34
+ WHERE scope_key IN (${inList}) AND status IN ('active', 'deprecated')
35
+ ORDER BY scope_key, updated_at DESC`)
36
+ .all(...scopeKeys);
37
+ const hiddenEntries = opts.hidden === "entries"
38
+ ? db()
39
+ .prepare(`SELECT ${BASE_COLS}, superseded_by FROM memories
40
+ WHERE scope_key IN (${inList}) AND status IN ('superseded', 'retracted', 'archived')
41
+ ORDER BY updated_at DESC`)
42
+ .all(...scopeKeys)
43
+ : [];
44
+ const hidden = { superseded: 0, retracted: 0, archived: 0 };
45
+ if (hiddenEntries.length > 0) {
46
+ for (const r of hiddenEntries) {
47
+ if (r.status === "superseded")
48
+ hidden.superseded++;
49
+ if (r.status === "retracted")
50
+ hidden.retracted++;
51
+ if (r.status === "archived")
52
+ hidden.archived++;
53
+ }
54
+ }
55
+ else {
56
+ const counted = db()
57
+ .prepare(`SELECT status, COUNT(*) AS n FROM memories
58
+ WHERE scope_key IN (${inList}) AND status IN ('superseded', 'retracted', 'archived')
59
+ GROUP BY status`)
60
+ .all(...scopeKeys);
61
+ for (const r of counted) {
62
+ if (r.status === "superseded")
63
+ hidden.superseded = r.n;
64
+ if (r.status === "retracted")
65
+ hidden.retracted = r.n;
66
+ if (r.status === "archived")
67
+ hidden.archived = r.n;
68
+ }
69
+ }
70
+ const outbox = current.filter((r) => r.scope_key !== PERSONAL_SCOPE.key && r.review_state === "draft");
71
+ const outboxIds = new Set(outbox.map((r) => r.id));
72
+ const byScope = new Map();
73
+ for (const r of current) {
74
+ if (outboxIds.has(r.id))
75
+ continue;
76
+ const arr = byScope.get(r.scope_key) ?? [];
77
+ arr.push(r);
78
+ byScope.set(r.scope_key, arr);
79
+ }
80
+ // Personal first, then project scopes by key for a stable order.
81
+ // D70: every requested scope appears, including one with nothing in it —
82
+ // "this project has no memories" is part of the answer, and dropping the
83
+ // section made the report look like the project was never looked at.
84
+ const orderedKeys = [
85
+ ...scopeKeys.filter((k) => k === PERSONAL_SCOPE.key),
86
+ ...scopeKeys.filter((k) => k !== PERSONAL_SCOPE.key).sort(),
87
+ ];
88
+ const scopes = orderedKeys.map((k) => {
89
+ const rows = byScope.get(k) ?? [];
90
+ return {
91
+ scopeKey: k,
92
+ projectName: rows[0]?.project_name || k,
93
+ rows,
94
+ };
95
+ });
96
+ return {
97
+ generatedAt: new Date().toISOString(),
98
+ scopes,
99
+ outbox,
100
+ hidden,
101
+ hiddenEntries,
102
+ total: current.length,
103
+ };
104
+ }
105
+ function hiddenLine(data) {
106
+ const { superseded, retracted, archived } = data.hidden;
107
+ if (superseded + retracted + archived === 0)
108
+ return "";
109
+ return `Not shown: ${superseded} superseded version(s), ${retracted} retracted, ${archived} archived — inspect with \`open-memex list --include all\`.`;
110
+ }
111
+ function entriesText(rows, startAt = 0) {
112
+ if (rows.length === 0)
113
+ return "(nothing remembered in this scope yet)";
114
+ return rows
115
+ .map((r, i) => formatInventoryLine(startAt + i, { ...r, snippet: r.content }, PERSONAL_SCOPE.key))
116
+ .join("\n");
117
+ }
118
+ /** Plain-text rendering: diffable in any terminal or CI log. */
119
+ export function renderInventoryText(data) {
120
+ const out = [];
121
+ out.push(`What OpenMemex remembers — ${data.generatedAt}`);
122
+ out.push(`${data.total} memories (${data.scopes.reduce((n, s) => n + (s.scopeKey === PERSONAL_SCOPE.key ? s.rows.length : 0), 0)} personal, ${data.outbox.length} in the outbox).`);
123
+ // D70: one running counter across every section, so a number quoted back
124
+ // ("delete #3") names exactly one entry in this report.
125
+ let seq = 0;
126
+ for (const s of data.scopes) {
127
+ const title = s.scopeKey === PERSONAL_SCOPE.key
128
+ ? "About you — personal (never leaves this machine)"
129
+ : `Project: ${s.projectName}`;
130
+ out.push("", `## ${title} (${s.rows.length})`, entriesText(s.rows, seq));
131
+ seq += s.rows.length;
132
+ }
133
+ if (data.outbox.length > 0) {
134
+ out.push("", `## Not in the repo yet — outbox drafts (${data.outbox.length})`, "These exist only on this machine. They reach the repo through review (submit → promote), never automatically.", entriesText(data.outbox, seq));
135
+ seq += data.outbox.length;
136
+ }
137
+ const hidden = hiddenLine(data);
138
+ if (hidden)
139
+ out.push("", hidden);
140
+ out.push("", "Read-only report. To remove a memory, tell your agent to forget it — it will read the entry back before deleting (deletion is permanent).");
141
+ return out.join("\n") + "\n";
142
+ }
143
+ /**
144
+ * JSON rendering: same data, for agents. Mirrors the export field names.
145
+ *
146
+ * D70: format `/2` drops the absolute `file` path. This artifact is meant
147
+ * to be handed to an agent — i.e. pasted into a cloud conversation — and it
148
+ * carried the user's home directory and name with it. The id locates the
149
+ * file (`open-memex where` prints the data root).
150
+ */
151
+ export function renderInventoryJson(data) {
152
+ const entry = (r) => ({
153
+ id: r.id,
154
+ scope: r.scope_key,
155
+ project: r.project_name,
156
+ type: r.type,
157
+ status: r.status,
158
+ review_state: r.review_state,
159
+ source: r.source,
160
+ created_at: new Date(r.created_at).toISOString(),
161
+ updated_at: new Date(r.updated_at).toISOString(),
162
+ content: r.content,
163
+ });
164
+ return (JSON.stringify({
165
+ format: "open-memex-inventory/2",
166
+ generated_at: data.generatedAt,
167
+ total: data.total,
168
+ scopes: data.scopes.map((s) => ({
169
+ scope: s.scopeKey,
170
+ project: s.projectName,
171
+ memories: s.rows.map(entry),
172
+ })),
173
+ outbox: data.outbox.map(entry),
174
+ hidden: data.hidden,
175
+ }, null, 2) + "\n");
176
+ }
package/dist/mcp.js CHANGED
@@ -89,6 +89,15 @@ memory_resolve, memory_pr_status — always call them by these full names.
89
89
  question into its concepts and try 2–3 phrasings per concept (synonyms, the
90
90
  user's other language, shorter keyword forms), and check the other scope too,
91
91
  before concluding nothing is stored.
92
+ - When the user asks what you remember (about them, or in this project),
93
+ call memory_list with scope=both and present it conversationally — turn
94
+ the structured fields into plain words (source=user → "you told me
95
+ this"; source=inference → "I inferred this, check me"), and don't read
96
+ raw ids aloud. If they ask to remove or hide an entry, re-run
97
+ memory_list first (numbers from an older listing may have shifted),
98
+ read the candidate back in full, and get a confirmation before calling
99
+ memory_forget: deletion is permanent. If they hesitate, offer soft=true
100
+ (hide it instead — still one-way, but the file survives).
92
101
  - Memories default to this project's scope; use the personal scope for facts
93
102
  about the user that hold across all projects. When a saved fact becomes
94
103
  outdated, call memory_supersede (find the old memory's id with memory_search
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { PLUGIN_ID, bootstrapPlugin, captureFromText, injectOnce, } from "./plugin-core.js";
2
+ import { PLUGIN_ID, bootstrapPlugin, captureFromText, captureHandoff, injectOnce, } from "./plugin-core.js";
3
3
  import { makeTools } from "./tools/memory.js";
4
4
  /** Register the five memory tools on a v2 host. */
5
5
  async function registerTools(ctx, state) {
@@ -28,12 +28,17 @@ export const v2Plugin = {
28
28
  const registrations = [];
29
29
  await registerTools(ctx, state);
30
30
  registrations.push(await ctx.session.hook("prompt", (ev) => {
31
- captureFromText(ev.prompt?.text ?? "", state);
31
+ captureFromText(ev.prompt?.text ?? "", state, ev.sessionID ?? "");
32
32
  }));
33
33
  registrations.push(await ctx.session.hook("context", (ev) => {
34
- injectOnce(ev.sessionID ?? "", state, (block) => {
34
+ const sessionID = ev.sessionID ?? "";
35
+ injectOnce(sessionID, state, (block) => {
35
36
  ev.system.push({ type: "text", text: block });
36
37
  });
38
+ // D73: tell the agent what the keyword hook already stored this turn.
39
+ const handoff = captureHandoff(sessionID, state);
40
+ if (handoff)
41
+ ev.system.push({ type: "text", text: handoff });
37
42
  }));
38
43
  return () => {
39
44
  for (const r of registrations)
package/dist/paths.js CHANGED
@@ -84,6 +84,24 @@ export function inRepoMemoriesDir(root, memoryDir) {
84
84
  return dir;
85
85
  }
86
86
  /** Same as `inRepoMemoriesDir` but never creates the directory. */
87
+ /**
88
+ * True when a memory file lives inside the user's git working tree (the
89
+ * in-repo `.ai/open-memex/` copy) rather than in the local data root.
90
+ *
91
+ * D70: both destructive/corrective surfaces need this — the hard delete
92
+ * already said "commit the deletion so the team sees it" (D64), and the
93
+ * soft hide has to say the same, because a retraction that never gets
94
+ * committed leaves the memory standing on every teammate's clone.
95
+ */
96
+ export function isInRepoMemoryFile(filePath) {
97
+ if (!filePath)
98
+ return false;
99
+ const normalized = filePath.replace(/\\/g, "/");
100
+ return normalized.includes("/.ai/open-memex/") && !normalized.startsWith(root());
101
+ }
102
+ function root() {
103
+ return paths().root.replace(/\\/g, "/");
104
+ }
87
105
  export function inRepoMemoriesDirPath(root, memoryDir) {
88
106
  return path.join(root, memoryDir);
89
107
  }
@@ -6,6 +6,7 @@ import { scopeHasFiles } from "./store/migrate.js";
6
6
  import { writeMemoryFile, readMemoryFile, ulid, msToRfc3339, } from "./store/markdown.js";
7
7
  import { buildContextBlock } from "./retrieve/inject.js";
8
8
  import { detectKeywords } from "./capture/keywords.js";
9
+ import { formatHandoffBlock, freshCaptures, } from "./capture/handoff.js";
9
10
  import { findDuplicates } from "./store/lifecycle.js";
10
11
  import { redact } from "./redact.js";
11
12
  /**
@@ -44,14 +45,16 @@ export function bootstrapPlugin(root) {
44
45
  catch (err) {
45
46
  console.error("[open-memex] init failed:", err);
46
47
  }
47
- return { cfg, scope, injectedSessions: new Set() };
48
+ return { cfg, scope, injectedSessions: new Set(), captures: new Map() };
48
49
  }
49
50
  /**
50
51
  * Keyword capture (§ capture): scan one user message for "remember …"
51
52
  * triggers and save each hit. Shared by the v1 `chat.message` hook and
52
- * the v2 session `prompt` hook — both hand us the message text.
53
+ * the v2 session `prompt` hook — both hand us the message text and the
54
+ * session id. The session id is what makes the D73 hand-off possible: without
55
+ * it the agent never learns the sentence is already stored.
53
56
  */
54
- export function captureFromText(text, state) {
57
+ export function captureFromText(text, state, sessionID) {
55
58
  const { cfg, scope } = state;
56
59
  if (!cfg.keywordCaptureEnabled || !text)
57
60
  return;
@@ -106,12 +109,54 @@ export function captureFromText(text, state) {
106
109
  // offers no toast channel, so the plugin log is the feedback surface.
107
110
  const preview = content.length > 60 ? content.slice(0, 60) + "…" : content;
108
111
  console.log(`[open-memex] remembered → ${target.kind} scope: "${preview}"`);
112
+ // D73 hand-off: the agent gets told about this capture in the turn's
113
+ // system context, so it does not save the same statement again.
114
+ recordCapture(state, sessionID, { id: fm.id, scopeKey: target.key, content, at: now });
109
115
  }
110
116
  catch (err) {
111
117
  console.error("[open-memex] keyword capture failed:", err);
112
118
  }
113
119
  }
114
120
  }
121
+ /** Note one hook capture against its session (D73). No-op without a session. */
122
+ function recordCapture(state, sessionID, record) {
123
+ if (!sessionID)
124
+ return;
125
+ const list = state.captures.get(sessionID) ?? [];
126
+ list.push(record);
127
+ state.captures.set(sessionID, list);
128
+ }
129
+ /**
130
+ * D73 hand-off note (a): what the keyword hook already stored for this
131
+ * session, delivered once per capture into the turn's system context. The
132
+ * agent cannot avoid re-saving a statement it cannot see is stored, so the
133
+ * store tells it. Returns "" when there is nothing new to hand off; stale
134
+ * records are pruned (in-memory only, like `injectedSessions`).
135
+ *
136
+ * Both host adapters push this from their system/context hook — the one that
137
+ * runs before the model request, i.e. after `chat.message` / `prompt`.
138
+ */
139
+ export function captureHandoff(sessionID, state) {
140
+ if (!sessionID)
141
+ return "";
142
+ const list = state.captures.get(sessionID);
143
+ if (!list || list.length === 0)
144
+ return "";
145
+ const now = Date.now();
146
+ const fresh = freshCaptures(list, now);
147
+ if (fresh.length !== list.length) {
148
+ if (fresh.length === 0)
149
+ state.captures.delete(sessionID);
150
+ else
151
+ state.captures.set(sessionID, fresh);
152
+ }
153
+ const pending = fresh.filter((r) => !r.delivered);
154
+ if (pending.length === 0)
155
+ return "";
156
+ for (const r of pending)
157
+ r.delivered = true;
158
+ return formatHandoffBlock(pending);
159
+ }
115
160
  /**
116
161
  * First-turn context injection: exactly once per session. The host adapter
117
162
  * supplies `push` (v1: output.system.push; v2: the session context hook's
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Display helpers (D68): how memory provenance, age, and state are
3
+ * rendered on the user-facing surfaces — the `memory_list` inventory an
4
+ * agent shows its user, and the `open-memex inventory` reports.
5
+ *
6
+ * Two rules from the 3-C design (v2) live here:
7
+ * - The list format is STRUCTURED data (number + id + created= + source=
8
+ * + state tags). The plain-language renderings ("you said this",
9
+ * "3 days ago") live in the guidance surfaces (tool descriptions,
10
+ * SKILL.md, MCP handshake) so an agent rephrases them in the
11
+ * conversation's language — the raw enums never get localized or
12
+ * reworded inside the data itself.
13
+ * - Nothing truncates silently: callers pair these lines with the true
14
+ * totals so a cut list says so.
15
+ */
16
+ /** Human age for a saved memory: "just now", "3 days ago", else a date. */
17
+ export function relativeTime(ts, now = Date.now()) {
18
+ if (!ts || Number.isNaN(ts))
19
+ return "";
20
+ const diff = now - ts;
21
+ if (diff < 0)
22
+ return "just now";
23
+ const minute = 60_000;
24
+ const hour = 60 * minute;
25
+ const day = 24 * hour;
26
+ if (diff < minute)
27
+ return "just now";
28
+ if (diff < hour) {
29
+ const n = Math.floor(diff / minute);
30
+ return `${n} minute${n === 1 ? "" : "s"} ago`;
31
+ }
32
+ if (diff < day) {
33
+ const n = Math.floor(diff / hour);
34
+ return `${n} hour${n === 1 ? "" : "s"} ago`;
35
+ }
36
+ if (diff < 30 * day) {
37
+ const n = Math.floor(diff / day);
38
+ return `${n} day${n === 1 ? "" : "s"} ago`;
39
+ }
40
+ const d = new Date(ts);
41
+ const mm = String(d.getMonth() + 1).padStart(2, "0");
42
+ const dd = String(d.getDate()).padStart(2, "0");
43
+ return `on ${d.getFullYear()}-${mm}-${dd}`;
44
+ }
45
+ /** Compact age token for the structured list format: `3d`, `12h`, `now`. */
46
+ export function ageToken(ts, now = Date.now()) {
47
+ if (!ts || Number.isNaN(ts))
48
+ return "?";
49
+ const diff = now - ts;
50
+ if (diff < 60_000)
51
+ return "now";
52
+ if (diff < 3_600_000)
53
+ return `${Math.floor(diff / 60_000)}m`;
54
+ if (diff < 86_400_000)
55
+ return `${Math.floor(diff / 3_600_000)}h`;
56
+ if (diff < 60 * 86_400_000)
57
+ return `${Math.floor(diff / 86_400_000)}d`;
58
+ const d = new Date(ts);
59
+ const mm = String(d.getMonth() + 1).padStart(2, "0");
60
+ const dd = String(d.getDate()).padStart(2, "0");
61
+ return `${d.getFullYear()}-${mm}-${dd}`;
62
+ }
63
+ /**
64
+ * Provenance in the user's words (D68). Used by prose surfaces (HTML
65
+ * report); the structured list keeps the raw `source=` enum instead.
66
+ * The distinction that matters to the user is *whose words these were* —
67
+ * said outright, asked to be saved, auto-captured, or inferred by the
68
+ * agent and possibly wrong.
69
+ */
70
+ export function sourceLabel(source) {
71
+ switch (source) {
72
+ case "user":
73
+ return "you said this";
74
+ case "cli":
75
+ return "you saved this from the command line";
76
+ case "tool":
77
+ return "you asked me to save this";
78
+ case "keyword":
79
+ return "auto-captured from your own wording";
80
+ case "inference":
81
+ return "I inferred this — not in your words, check me";
82
+ case "import":
83
+ return "imported from another machine";
84
+ default:
85
+ return source ? `saved (${source})` : "saved";
86
+ }
87
+ }
88
+ /**
89
+ * Review state in plain words for project scopes (D68). Personal
90
+ * memories are always `draft` by design; callers must not show this
91
+ * for them — "not yet shared" would be alarming noise there.
92
+ */
93
+ export function reviewStateLabel(reviewState) {
94
+ switch (reviewState) {
95
+ case "draft":
96
+ return "still in your outbox — not in the repo yet";
97
+ case "proposed":
98
+ return "shared with the project, waiting for review";
99
+ case "approved":
100
+ return "approved, not yet published";
101
+ case "published":
102
+ return "published to the repo";
103
+ case "rejected":
104
+ return "reviewed and rejected";
105
+ default:
106
+ return reviewState ?? "draft";
107
+ }
108
+ }
109
+ /** Escape user content for HTML. Memory text is arbitrary user input. */
110
+ export function escapeHtml(s) {
111
+ return s
112
+ .replace(/&/g, "&amp;")
113
+ .replace(/</g, "&lt;")
114
+ .replace(/>/g, "&gt;")
115
+ .replace(/"/g, "&quot;")
116
+ .replace(/'/g, "&#39;");
117
+ }
118
+ /**
119
+ * One structured inventory line (D68):
120
+ * 3. [fact] id=01K6… created=3d source=user [draft] — body text
121
+ * Number and id always appear together: the number is for the user's
122
+ * mouth ("delete #3"), the id is the machine contract. `created=` is
123
+ * when the memory was learned; `updated=` appears only when it moved
124
+ * materially later (supersede/promote touch updated_at).
125
+ *
126
+ * D70: `index` must be a running counter across every section of one
127
+ * listing — a per-section counter produces two "#1"s in a single
128
+ * `scope: both` output, which makes "delete #3" a guess.
129
+ */
130
+ export function formatInventoryLine(index, hit, personalKey, now = Date.now()) {
131
+ const parts = [
132
+ `${index + 1}.`,
133
+ `[${hit.type}]`,
134
+ `id=${hit.id}`,
135
+ `created=${ageToken(hit.created_at ?? hit.updated_at, now)}`,
136
+ `source=${hit.source || "?"}`,
137
+ ];
138
+ const created = hit.created_at ?? hit.updated_at ?? 0;
139
+ if (hit.updated_at && hit.updated_at - created >= 86_400_000) {
140
+ parts.push(`updated=${ageToken(hit.updated_at, now)}`);
141
+ }
142
+ if (hit.scope_key !== personalKey) {
143
+ const state = hit.review_state ?? "draft";
144
+ if (state !== "published")
145
+ parts.push(`[${state}]`);
146
+ }
147
+ if (hit.status !== "active")
148
+ parts.push(`[${hit.status}]`);
149
+ const body = hit.snippet.replace(/\s+/g, " ").trim();
150
+ return `${parts.join(" ")} — ${body}`;
151
+ }
152
+ /**
153
+ * Truncation disclosure (D68): a cut list always says so.
154
+ * D70: the wording names the surface that can show everything — the CLI —
155
+ * so a hidden entry is always reachable.
156
+ */
157
+ export function truncationNote(shown, total, cli = "open-memex") {
158
+ if (total <= shown)
159
+ return null;
160
+ return `… and ${total - shown} more not shown (raise limit up to 100, run \`${cli} list --limit 100\`, or use memory_search to find something specific).`;
161
+ }