@joe-broadhead/opencode-mem 0.8.3 → 0.8.5

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.
@@ -53,6 +53,64 @@ export async function discoverKnowledge(backend, log, assetType, scope) {
53
53
 
54
54
  const DEFAULT_KNOWLEDGE_CHARS = 6000
55
55
  const DEFAULT_ASSET_CHARS = 3000
56
+ /** A hit's snippet, and how many linked pages a hit lists. */
57
+ const SNIPPET_CHARS = 160
58
+ const RELATED_PER_HIT = 5
59
+
60
+ /** A page path as read takes it: "wiki/entities/ama.md" -> "entities/ama". */
61
+ function pageRef(value) {
62
+ return String(value ?? "").replace(/^\/*wiki\//, "").replace(/\.md$/i, "")
63
+ }
64
+
65
+ /**
66
+ * A knowledge search answer as compact text. The hub's wiki search answers
67
+ * `{ results: [{ path, title, snippet, score, type, hop, related, via }],
68
+ * links, count }`, and printing that JSON spent tokens on scores, types and
69
+ * hop counts. Each hit is one line, its path (what read takes as ref), its
70
+ * title when it says more than the path, and a short snippet; the pages it
71
+ * links to follow on one line as refs. A code graph's `{ text }` is its text.
72
+ * Anything else is one line of JSON.
73
+ *
74
+ * @param {unknown} result
75
+ * @returns {string}
76
+ */
77
+ export function renderSearchHits(result) {
78
+ if (typeof result === "string") return result
79
+ if (result && typeof result === "object" && !Array.isArray(result) && typeof result.text === "string") return result.text
80
+ const hits = Array.isArray(result?.results) ? result.results : Array.isArray(result) ? result : null
81
+ if (!hits) return JSON.stringify(result ?? null)
82
+ if (hits.length === 0) return "no matching pages"
83
+ const lines = []
84
+ for (const hit of hits) {
85
+ if (!hit || typeof hit !== "object") {
86
+ lines.push(`- ${oneLine(String(hit), SNIPPET_CHARS)}`)
87
+ continue
88
+ }
89
+ const path = oneLine(hit.path ?? hit.id ?? hit.ref ?? "", 160)
90
+ const title = oneLine(hit.title ?? "", 100)
91
+ const named = title && title.toLowerCase() !== pageRef(path).split("/").at(-1)?.toLowerCase() ? ` | ${title}` : ""
92
+ const linked = Number(hit.hop) > 0 ? " (via a link)" : ""
93
+ const snippet = oneLine(String(hit.snippet ?? hit.content ?? "").replace(/\s+/g, " "), SNIPPET_CHARS)
94
+ lines.push(`- ${path}${named}${linked}${snippet ? `: ${snippet}` : ""}`)
95
+ const related = (Array.isArray(hit.related) ? hit.related : [])
96
+ .map((entry) => (typeof entry === "string" ? pageRef(entry) : pageRef(entry?.path ?? entry?.title ?? "")))
97
+ .filter(Boolean)
98
+ if (related.length > 0) {
99
+ const more = related.length > RELATED_PER_HIT ? `, +${related.length - RELATED_PER_HIT}` : ""
100
+ lines.push(` → ${related.slice(0, RELATED_PER_HIT).map((ref) => oneLine(ref, 80)).join(", ")}${more}`)
101
+ }
102
+ }
103
+ return lines.join("\n")
104
+ }
105
+
106
+ /** Cut text to `max` characters at a line end, and count the hits left out. */
107
+ function clipLines(value, max) {
108
+ if (value.length <= max) return value
109
+ const cut = value.lastIndexOf("\n", max - 40)
110
+ const kept = cut > 0 ? value.slice(0, cut) : value.slice(0, Math.max(0, max - 40))
111
+ const omitted = (value.slice(kept.length).match(/^- /gm) ?? []).length
112
+ return `${kept}\n(+${omitted || "more"} hit(s) not shown)`
113
+ }
56
114
 
57
115
  /**
58
116
  * Search knowledge assets and render the results as fenced data.
@@ -85,14 +143,14 @@ export async function searchKnowledge(backend, ids, query, scoped, options = {})
85
143
  params: { query, limit: 5 },
86
144
  scope: scoped,
87
145
  })
88
- const rendered = typeof result === "string" ? result : JSON.stringify(result, null, 2)
146
+ const rendered = renderSearchHits(result)
89
147
  // A planted command in a page is data: it is removed, marked, and noted
90
148
  // outside the fence, as recall does for atoms.
91
149
  const safe = quarantineText(rendered)
92
150
  const note = quarantineNote(safe.removed)
93
151
  // Truncate first, then neutralize: the closing tag is appended after,
94
152
  // so neither a long page nor a crafted one can escape the fence.
95
- const body = neutralizeFenceClosers(safe.text.slice(0, bodyRoom))
153
+ const body = neutralizeFenceClosers(clipLines(safe.text, bodyRoom).slice(0, bodyRoom))
96
154
  const block = `<knowledge source="${source}">\n${body}\n</knowledge>${note ? `\n${note}` : ""}`
97
155
  blocks.push(block)
98
156
  used += block.length + 2
@@ -30,6 +30,12 @@ const FORGET_PERMISSION = "mem_forget"
30
30
  const KINDS = Object.freeze(["fact", "decision", "constraint", "preference", "procedure"])
31
31
  /** A supersede replaces a few atoms, not a cleanup: more is a forget. */
32
32
  const MAX_SUPERSEDES = 10
33
+ /**
34
+ * Turn ids as the deployed core mints them (read from the image, 2026-11-08):
35
+ * `msg-<12 hex>` for conversation/add (mem_remember's turns) and
36
+ * `msg_<ms>_<hex>` for the L0 recorder. Atoms are `m_<ms>_<hex>`.
37
+ */
38
+ const TURN_ID = /^msg[-_]/
33
39
  /**
34
40
  * One atomic fact fits in a few sentences. The cap keeps a write well inside
35
41
  * the upstream per-message limit and points long synthesis at the wiki.
@@ -101,7 +107,7 @@ export function registerMemory(editor, toolkit) {
101
107
  editor.add({
102
108
  name: "remember",
103
109
  description:
104
- "Save one durable preference, constraint, decision, fact, or procedure, in the same turn it is stated and without asking; then say what was saved in one line. Capture already keeps the conversation, so this is curation: choose the kind and the wording that must come back exactly. When something known has changed, pass supersedes with the old atom's id: the new one is saved and the old one removed. Not for things to do (mem_commitments), where a project stands (its page's Status section, mem_wiki), file contents, tool output, or restatements of the code: a status-shaped write is refused. It is tagged with the session's task; pass task \"*\" for a fact that serves the whole space. Private (the default) always writes your personal space; team needs a shared space that is selected or bound to the session, editor access, and the person's approval. Extraction is asynchronous, so a new memory may not be recallable at once.",
110
+ "Save one durable preference, constraint, decision, fact, or procedure, in the same turn it is stated and without asking; then say what was saved in one line. Capture already keeps the conversation, so this is curation: choose the kind and the wording that must come back exactly. The answer gives the stored turn's id (msg-…); the memory's atom id (m_…) appears after extraction, through mem_recall. When something known has changed, pass supersedes with the old atom's id (m_…): the old atom is removed at once, and the new one is recallable after extraction. Not for things to do (mem_commitments), where a project stands (its page's Status section, mem_wiki), file contents, tool output, or restatements of the code: a status-shaped write ('Status: …', 'half done', 'is in progress', '40% done', 'next step: …') is refused. It is tagged with the session's task; pass task \"*\" for a fact that serves the whole space. Private (the default) always writes your personal space; team needs a shared space that is selected or bound to the session, editor access, and the person's approval. Extraction is asynchronous, so a new memory may not be recallable at once.",
105
111
  input: {
106
112
  type: "object",
107
113
  properties: {
@@ -121,7 +127,7 @@ export function registerMemory(editor, toolkit) {
121
127
  supersedes: {
122
128
  type: "array",
123
129
  items: { type: "string" },
124
- description: `Ids (rec_…) of atoms this one replaces, from mem_recall, at most ${MAX_SUPERSEDES}. They are removed once the new memory is accepted; captured turns that mention the old value stay as history. Example: {"content": "Staging listens on 8788", "kind": "fact", "supersedes": ["rec_..."]}`,
130
+ description: `Atom ids (m_…, as mem_recall shows them) this one replaces, at most ${MAX_SUPERSEDES}. They are removed as soon as the new memory is stored; the new one is recallable after extraction, so for a short while recall finds neither. A turn id (msg-…) is not an atom: delete turns with mem_forget. Captured turns that mention the old value stay as history. Example: {"content": "Staging listens on 8788", "kind": "fact", "supersedes": ["m_..."]}`,
125
131
  },
126
132
  space: { type: "string", description: "Space id to write to (control plane); defaults to your personal or session-bound shared space" },
127
133
  },
@@ -152,6 +158,15 @@ export function registerMemory(editor, toolkit) {
152
158
  if (supersedes.length > MAX_SUPERSEDES) {
153
159
  return text(`not stored: supersedes takes at most ${MAX_SUPERSEDES} ids; to remove more, use mem_forget.`)
154
160
  }
161
+ // A turn id (the core mints msg-… for a stored turn and msg_… for a
162
+ // captured one) is not an atom: atomic/delete would answer "not found"
163
+ // after the new memory was already written.
164
+ const turns = supersedes.filter((id) => TURN_ID.test(id))
165
+ if (turns.length > 0) {
166
+ return text(
167
+ `not stored: supersedes takes atom ids (m_…, as mem_recall shows them); ${turns.map((id) => oneLine(id, 80)).join(", ")} ${turns.length === 1 ? "is a turn" : "are turns"}. Pass the atom's id, or delete the turn with mem_forget.`,
168
+ )
169
+ }
155
170
  const task = taskFor(input, context)
156
171
  if (task.invalid) return text(`not stored: ${task.invalid}`)
157
172
  const visibility = normalizeVisibility(input?.visibility, "private")
@@ -211,9 +226,14 @@ export function registerMemory(editor, toolkit) {
211
226
  )
212
227
  const label = displayScope(spaceContext, scoped)
213
228
  log.info("remember", { kind, visibility, scope: label, count: data?.total_count, task: Boolean(task.key), supersedes: supersedes.length })
214
- const stored = `stored ${data?.total_count ?? messages.length} message(s) in ${label} ${
215
- task.key ? `for task ${task.key}` : "for the whole space"
216
- }; L1 extraction runs asynchronously.`
229
+ const head = `stored ${data?.total_count ?? messages.length} message(s) in ${label} ${task.key ? `for task ${task.key}` : "for the whole space"}`
230
+ // The turn's id is the handle the agent has now: the atom it extracts
231
+ // to has its own id, which only exists once extraction has run.
232
+ const turnIDs = accepted.filter((id) => typeof id === "string" && id).map((id) => oneLine(id, 80))
233
+ const stored =
234
+ turnIDs.length > 0
235
+ ? `${head}: the ${kind} is turn ${turnIDs[0]}${turnIDs.length > 1 ? ` (with its echo ${turnIDs.slice(1).join(", ")})` : ""}. Its atom id (m_…) appears once extraction runs (asynchronous): mem_recall finds it, and supersedes or mem_forget take that id. To remove it before then: mem_forget({ ids: ${JSON.stringify(turnIDs)} }).`
236
+ : `${head}; L1 extraction runs asynchronously.`
217
237
  if (supersedes.length === 0) return text(stored)
218
238
  // A delete never carries the task or the write's session: upstream
219
239
  // matches a row only under its own, and the atom being replaced was
@@ -279,7 +299,11 @@ export function registerMemory(editor, toolkit) {
279
299
  forgetLocations(spaceContext, removed)
280
300
  const list = (values) => values.map((id) => oneLine(id, 80)).join(", ")
281
301
  const lines = []
282
- if (removed.length > 0) lines.push(`Superseded and removed: ${list(removed)}.`)
302
+ if (removed.length > 0) {
303
+ lines.push(
304
+ `Superseded: ${list(removed)} ${removed.length === 1 ? "is" : "are"} removed now. The new memory is recallable after extraction (asynchronous), so for a short while mem_recall finds neither the old atom nor the new one.`,
305
+ )
306
+ }
283
307
  if (missing.length > 0) lines.push(`Not found, so not removed: ${list(missing)} (pass ids from mem_recall).`)
284
308
  if (failed.length > 0) lines.push(`Not removed, the delete failed: ${failed.join("; ")}.`)
285
309
  lines.push("Captured turns that mention the old value stay as history.")
@@ -761,14 +785,14 @@ export function registerMemory(editor, toolkit) {
761
785
  editor.add({
762
786
  name: "forget",
763
787
  description:
764
- "Delete memories. ids (from mem_recall or mem_remember) deletes L1 atoms and L0 turns; pass an atom and its turn together. Each id is deleted under the agent and session that wrote it; the result lists what the backend confirmed, did not find, and did not delete, deletes the mem_remember request rows that hold only the deleted text, and lists every other stored copy it found (id and excerpt; not deleted). match (a phrase) with layer l2, l3, or all previews the L3 persona and L2 scenario lines that contain it, which mem_recall cannot see; confirm=true removes them and reads the files back. Without confirm nothing changes. Private deletes use your personal space; team deletes need a selected or bound shared space, editor access, and approval. Irreversible: confirm with the user first.",
788
+ "Delete memories. ids (from mem_recall or mem_remember) deletes L1 atoms and L0 turns; pass an atom and its turn together. Each id is deleted under the agent and session that wrote it; the result lists what the backend confirmed, did not find, and did not delete, deletes the mem_remember request rows that hold only the deleted text, and lists every other stored copy it found (id and excerpt; not deleted). match (a phrase) with layer l2, l3, or all previews the L3 persona and L2 scenario lines that contain it, which mem_recall cannot see; confirm=true removes them and reads the files back. Without confirm nothing changes. Private deletes use your personal space; team deletes need a selected or bound shared space, editor access, and approval. Irreversible. When the person asked you to forget it, the request is their consent: call it without asking again in chat (the host may still show its own prompt). When you propose a deletion yourself (a duplicate, a tidy-up, a copy this tool listed), ask the person first.",
765
789
  input: {
766
790
  type: "object",
767
791
  properties: {
768
792
  ids: {
769
793
  type: "array",
770
794
  items: { type: "string" },
771
- description: 'L0/L1 ids from mem_recall or mem_remember. Pass ids or match (one is needed). Example: {"ids": ["rec_..."]}',
795
+ description: 'L0/L1 ids from mem_recall or mem_remember. Pass ids or match (one is needed). Example: {"ids": ["m_...", "msg-..."]}',
772
796
  },
773
797
  layer: {
774
798
  type: "string",
@@ -1032,11 +1056,15 @@ export function registerMemory(editor, toolkit) {
1032
1056
  if (requested) return { message: "control plane not configured; set MEMORY_CONTROL_URL to select a space" }
1033
1057
  return { spaceContext: null, scoped: scope({ sessionID: context?.sessionID, agent: context?.agent }) }
1034
1058
  }
1059
+ // An explicit space applies to this call only. A space and a session sent
1060
+ // together bind the session to that space (control's context route, and
1061
+ // the gateway for a data-plane call with both hints), so the next plain
1062
+ // recall searched the team space: neither is sent with the session here.
1035
1063
  let spaceContext
1036
1064
  try {
1037
1065
  spaceContext = await toolkit.resolveContext({
1038
1066
  space: requested || undefined,
1039
- sessionID: context?.sessionID,
1067
+ sessionID: requested ? undefined : context?.sessionID,
1040
1068
  agent: context?.agent,
1041
1069
  })
1042
1070
  } catch (error) {
@@ -1061,7 +1089,7 @@ export function registerMemory(editor, toolkit) {
1061
1089
  }
1062
1090
  }
1063
1091
  }
1064
- return { spaceContext, scoped: scopeFor(spaceContext, { sessionID: context?.sessionID, agent: context?.agent }) }
1092
+ return { spaceContext, scoped: scopeFor(spaceContext, { sessionID: requested ? undefined : context?.sessionID, agent: context?.agent }) }
1065
1093
  }
1066
1094
 
1067
1095
  /** Delete a share in local mode: the wiki itself, then read it back. */
@@ -1326,13 +1354,13 @@ export function registerMemory(editor, toolkit) {
1326
1354
  type: "array",
1327
1355
  items: { type: "string" },
1328
1356
  description:
1329
- 'To share: private L1 atom or L0 turn ids from mem_recall or mem_remember, with rationale. Example: {"ids": ["rec_..."], "rationale": "The team needs the logging rule", "space": "space-team"}',
1357
+ 'To share: private L1 atom or L0 turn ids from mem_recall or mem_remember, with rationale. Example: {"ids": ["m_..."], "rationale": "The team needs the logging rule", "space": "space-team"}',
1330
1358
  },
1331
1359
  name: { type: "string", description: "Short name for the share" },
1332
1360
  rationale: { type: "string", description: "Why the shared space should see this; required to share, recorded on the share" },
1333
1361
  space: {
1334
1362
  type: "string",
1335
- description: "Shared space id (control plane); defaults to the session's bound shared space",
1363
+ description: "Shared space id (control plane); defaults to the session's bound shared space. A space passed here applies to this call only: the session stays where it was",
1336
1364
  },
1337
1365
  revoke: {
1338
1366
  type: "string",