@joe-broadhead/opencode-mem 0.7.1 → 0.8.1

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.
@@ -16,9 +16,20 @@ import {
16
16
  rememberParts,
17
17
  } from "../copies.js"
18
18
  import { errorMessage, neutralizeFenceClosers, oneLine, redactSecrets, shortHash } from "../util.js"
19
+ import { isCoded, withNote } from "../errors.js"
19
20
  import { TASK_INPUT, canWriteShared } from "./shared.js"
20
21
 
22
+ /**
23
+ * The permission mem_forget asserts before it deletes: the tool's own engine
24
+ * id, declared `effect: "ask"` in `jelly.tools`. Not an approval action
25
+ * (`jelly.asks`), so it is a name here, not a literal the scan in
26
+ * scripts/approval-actions.mjs would read as one.
27
+ */
28
+ const FORGET_PERMISSION = "mem_forget"
29
+
21
30
  const KINDS = Object.freeze(["fact", "decision", "constraint", "preference", "procedure"])
31
+ /** A supersede replaces a few atoms, not a cleanup: more is a forget. */
32
+ const MAX_SUPERSEDES = 10
22
33
  /**
23
34
  * One atomic fact fits in a few sentences. The cap keeps a write well inside
24
35
  * the upstream per-message limit and points long synthesis at the wiki.
@@ -90,19 +101,28 @@ export function registerMemory(editor, toolkit) {
90
101
  editor.add({
91
102
  name: "remember",
92
103
  description:
93
- "Persist a durable fact, decision, constraint, or preference that should survive this session. Call it when the user states a standing rule (\"never do X\"), a decision with rationale, or a stable preference. Do not store file contents, tool output, or restatements of the code. It is tagged with the session's task (declared with task here or in mem_recall); pass task \"*\" for a fact that serves the whole space. Default to visibility=private, which always writes your personal space. Team visibility requires a shared space that is explicitly selected or bound to the session and editor-or-higher access, and it asks for approval. Extraction is asynchronous and batched, so a new memory may not be recallable immediately.",
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.",
94
105
  input: {
95
106
  type: "object",
96
107
  properties: {
97
- content: { type: "string", description: "The thing to remember, stated plainly" },
108
+ content: {
109
+ type: "string",
110
+ description:
111
+ 'Required: the thing to remember, stated plainly. Example: {"content": "Log timestamps are UTC", "kind": "decision", "reason": "One clock across every log"}',
112
+ },
98
113
  task: TASK_INPUT,
99
114
  kind: {
100
115
  type: "string",
101
116
  enum: ["fact", "decision", "constraint", "preference", "procedure"],
102
- description: "constraint for standing rules, decision for choices with rationale, preference for user habits, fact for stable truths, procedure for repeatable steps",
117
+ description: "preference for how the person likes things done, constraint for a standing rule (a lesson from a mistake is a constraint or a procedure with the incident in reason), decision for a choice and its reason, fact for a verified non-obvious truth, procedure for steps that worked (five at most). Default fact",
103
118
  },
104
119
  visibility: { type: "string", enum: ["private", "team"], description: "private (default) always writes your personal space; team shares with a selected or session-bound shared space" },
105
- reason: { type: "string", description: "Why it is worth keeping; stored as background and improves extraction" },
120
+ reason: { type: "string", description: "Why it is worth keeping, with the source and date when known (\"agreed in the launch review, 2026-11-05\"); for a lesson, the incident" },
121
+ supersedes: {
122
+ type: "array",
123
+ 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_..."]}`,
125
+ },
106
126
  space: { type: "string", description: "Space id to write to (control plane); defaults to your personal or session-bound shared space" },
107
127
  },
108
128
  required: ["content"],
@@ -124,6 +144,14 @@ export function registerMemory(editor, toolkit) {
124
144
  const reason = String(input?.reason ?? "").trim()
125
145
  const reasonRefusal = reason ? writeRefusal(reason) : ""
126
146
  if (reasonRefusal) return text(`not stored (reason): ${reasonRefusal.replace(/^not stored: /, "")}`)
147
+ const supersedes = Array.isArray(input?.supersedes)
148
+ ? [...new Set(input.supersedes.map((id) => String(id ?? "").trim()).filter(Boolean))]
149
+ : typeof input?.supersedes === "string" && input.supersedes.trim()
150
+ ? [input.supersedes.trim()]
151
+ : []
152
+ if (supersedes.length > MAX_SUPERSEDES) {
153
+ return text(`not stored: supersedes takes at most ${MAX_SUPERSEDES} ids; to remove more, use mem_forget.`)
154
+ }
127
155
  const task = taskFor(input, context)
128
156
  if (task.invalid) return text(`not stored: ${task.invalid}`)
129
157
  const visibility = normalizeVisibility(input?.visibility, "private")
@@ -139,9 +167,11 @@ export function registerMemory(editor, toolkit) {
139
167
 
140
168
  if (visibility === "team") {
141
169
  try {
142
- await assertTeamWrite(context, "memory.remember", [spaceContext?.space_id ?? "team"], {
170
+ await assertTeamWrite(context, "memory.remember", [spaceContext?.space_id ?? "team", ...supersedes], {
143
171
  kind,
144
172
  visibility,
173
+ excerpt: redactSecrets(oneLine(content, 400)),
174
+ ...(supersedes.length > 0 ? { supersedes } : {}),
145
175
  })
146
176
  } catch (error) {
147
177
  return text(`remembering to the team denied: ${errorMessage(error)}`)
@@ -180,32 +210,82 @@ export function registerMemory(editor, toolkit) {
180
210
  { agent_id: scoped.agent_id, session_id: sessionID },
181
211
  )
182
212
  const label = displayScope(spaceContext, scoped)
183
- log.info("remember", { kind, visibility, scope: label, count: data?.total_count, task: Boolean(task.key) })
184
- return text(
185
- `stored ${data?.total_count ?? messages.length} message(s) in ${label} ${
186
- task.key ? `for task ${task.key}` : "for the whole space"
187
- }; L1 extraction runs asynchronously.`,
188
- )
213
+ 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.`
217
+ if (supersedes.length === 0) return text(stored)
218
+ // A delete never carries the task or the write's session: upstream
219
+ // matches a row only under its own, and the atom being replaced was
220
+ // usually written in another task (as mem_forget does).
221
+ const unscoped = spaceContext
222
+ ? scopeFor(spaceContext, { sessionID: context?.sessionID, agent: context?.agent })
223
+ : scope({ sessionID: context?.sessionID, agent: context?.agent })
224
+ const { session_id: _session, task_id: _task, ...base } = unscoped
225
+ return text(`${stored}\n${await supersede(supersedes, spaceContext, base)}`)
189
226
  } catch (error) {
190
227
  if (!isTransientFailure(error)) {
191
228
  log.warn("remember rejected by the backend", error)
192
- return text(`not stored: the backend rejected the write (${errorMessage(error)}). Nothing was queued.`)
229
+ const message = errorMessage(error)
230
+ return text(
231
+ isCoded(message)
232
+ ? withNote(message, "not stored, and nothing was queued")
233
+ : `not stored: the backend rejected the write (${message}). Nothing was queued.`,
234
+ )
193
235
  }
194
236
  const spooled = toolkit.runtime.enqueueSpool("conversation", { sessionID, messages, scope: scoped })
195
237
  if (spooled) {
196
238
  log.warn("remember failed, spooled", error)
239
+ // A queued write is not accepted yet, so nothing it supersedes is removed.
240
+ const kept = supersedes.length > 0 ? ` Superseded ids were kept, because the new memory is not stored yet: ${supersedes.map((id) => oneLine(id, 80)).join(", ")}.` : ""
197
241
  return text(
198
- `backend unreachable; queued locally (${errorMessage(error)}). It will be retried on the next flush.`,
242
+ `backend unreachable; queued locally (${errorMessage(error)}). It will be retried on the next flush.${kept}`,
199
243
  )
200
244
  }
201
245
  log.warn("remember failed and could not be spooled", error)
202
- return fail(
203
- `${errorMessage(error)}; local spooling is disabled or unavailable, so the memory was not stored.`,
204
- )
246
+ return fail(withNote(errorMessage(error), "local spooling is disabled or unavailable, so the memory was not stored"))
205
247
  }
206
248
  },
207
249
  })
208
250
 
251
+ /**
252
+ * Remove the private L1 atoms a new memory replaces, after it was accepted.
253
+ * Each id is deleted under the agent that wrote it, as mem_recall showed it;
254
+ * an id this process has not seen is tried under this session's agent. Only
255
+ * the backend's count is reported. Captured turns are history and stay.
256
+ */
257
+ async function supersede(ids, spaceContext, base) {
258
+ const groups = new Map()
259
+ for (const id of ids) {
260
+ const hit = locate(spaceContext, id)
261
+ const agent = hit?.layer === "l1" && hit.agent_id ? hit.agent_id : base.agent_id
262
+ if (!groups.has(agent)) groups.set(agent, [])
263
+ groups.get(agent).push(id)
264
+ }
265
+ const removed = []
266
+ const missing = []
267
+ const failed = []
268
+ for (const [agent, group] of groups) {
269
+ try {
270
+ const data = await backend.deleteAtoms({ ids: group, scope: { ...base, ...(agent ? { agent_id: agent } : {}) } })
271
+ const count = Math.max(0, Math.min(group.length, Number(data?.deleted_count) || 0))
272
+ const confirmed = Array.isArray(data?.deleted_ids) ? group.filter((id) => data.deleted_ids.includes(id)) : group.slice(0, count)
273
+ removed.push(...confirmed)
274
+ missing.push(...group.filter((id) => !confirmed.includes(id)))
275
+ } catch (error) {
276
+ failed.push(`${group.map((id) => oneLine(id, 80)).join(", ")} (${errorMessage(error)})`)
277
+ }
278
+ }
279
+ forgetLocations(spaceContext, removed)
280
+ const list = (values) => values.map((id) => oneLine(id, 80)).join(", ")
281
+ const lines = []
282
+ if (removed.length > 0) lines.push(`Superseded and removed: ${list(removed)}.`)
283
+ if (missing.length > 0) lines.push(`Not found, so not removed: ${list(missing)} (pass ids from mem_recall).`)
284
+ if (failed.length > 0) lines.push(`Not removed, the delete failed: ${failed.join("; ")}.`)
285
+ lines.push("Captured turns that mention the old value stay as history.")
286
+ return lines.join(" ")
287
+ }
288
+
209
289
  /**
210
290
  * Rows a forget reported as copies, keyed by space and id, with the features
211
291
  * (anchors and stems, no text) of the forgotten text they matched. When a
@@ -685,7 +765,11 @@ export function registerMemory(editor, toolkit) {
685
765
  input: {
686
766
  type: "object",
687
767
  properties: {
688
- ids: { type: "array", items: { type: "string" }, description: "L0/L1 ids" },
768
+ ids: {
769
+ type: "array",
770
+ items: { type: "string" },
771
+ description: 'L0/L1 ids from mem_recall or mem_remember. Pass ids or match (one is needed). Example: {"ids": ["rec_..."]}',
772
+ },
689
773
  layer: {
690
774
  type: "string",
691
775
  enum: ["all", "l0", "l1", "l2", "l3"],
@@ -693,7 +777,7 @@ export function registerMemory(editor, toolkit) {
693
777
  },
694
778
  match: {
695
779
  type: "string",
696
- description: `Phrase (${MIN_ERASE_CHARS}+ characters); every L2/L3 line containing it is removed`,
780
+ description: `Phrase (${MIN_ERASE_CHARS}+ characters); every L2/L3 line containing it is removed. Without confirm it only previews. Example: {"match": "old log format", "layer": "all"}`,
697
781
  },
698
782
  confirm: { type: "boolean", description: "Apply the match erase (default: preview only, nothing deleted)" },
699
783
  agent: { type: "string", description: "The agent that wrote the ids, if not this session's agent" },
@@ -734,6 +818,25 @@ export function registerMemory(editor, toolkit) {
734
818
  const label = displayScope(spaceContext, scoped)
735
819
 
736
820
  const preview = Boolean(match) && input?.confirm !== true
821
+ // Forget asks (D17): a delete cannot be undone, so the call asserts the
822
+ // tool's own permission before anything is deleted, and the plugin's
823
+ // default rule (src/permissions.js) or Jelly's declared `ask` makes the
824
+ // host ask. A preview deletes nothing and does not ask.
825
+ if (!preview) {
826
+ try {
827
+ await toolkit.assert({
828
+ sessionID: context?.sessionID,
829
+ agent: context?.agent,
830
+ source: { type: "tool", messageID: context?.messageID, id: context?.id },
831
+ action: FORGET_PERMISSION,
832
+ resources: [visibility],
833
+ save: [visibility],
834
+ metadata: { visibility, layer, space: label, ...(ids.length > 0 ? { ids: ids.length } : {}), ...(match ? { erase: true } : {}) },
835
+ })
836
+ } catch (error) {
837
+ return text(`forgetting denied: ${errorMessage(error)}. Nothing was deleted.`)
838
+ }
839
+ }
737
840
  const approvalMetadata = { layer, space: spaceContext?.space_id ?? "team", ...(match ? { erase: true } : {}) }
738
841
  // An id delete asks once it knows every row it will delete: the named ids
739
842
  // and the mem_remember rows that hold only their text. Nothing is
@@ -1219,14 +1322,22 @@ export function registerMemory(editor, toolkit) {
1219
1322
  input: {
1220
1323
  type: "object",
1221
1324
  properties: {
1222
- ids: { type: "array", items: { type: "string" }, description: "Private L1 atom or L0 turn ids from mem_recall or mem_remember" },
1325
+ ids: {
1326
+ type: "array",
1327
+ items: { type: "string" },
1328
+ 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"}',
1330
+ },
1223
1331
  name: { type: "string", description: "Short name for the share" },
1224
1332
  rationale: { type: "string", description: "Why the shared space should see this; required to share, recorded on the share" },
1225
1333
  space: {
1226
1334
  type: "string",
1227
1335
  description: "Shared space id (control plane); defaults to the session's bound shared space",
1228
1336
  },
1229
- revoke: { type: "string", description: "Share id from an earlier mem_promote; deletes that copy instead of sharing" },
1337
+ revoke: {
1338
+ type: "string",
1339
+ description: 'To revoke instead: the share id an earlier mem_promote returned; deletes that copy. Example: {"revoke": "res_...", "space": "space-team"}',
1340
+ },
1230
1341
  },
1231
1342
  additionalProperties: false,
1232
1343
  },
@@ -51,7 +51,11 @@ export function registerRecall(editor, toolkit) {
51
51
  input: {
52
52
  type: "object",
53
53
  properties: {
54
- query: { type: "string", description: "Natural-language description of what to look for, e.g. \"auth refactor constraints\"" },
54
+ query: {
55
+ type: "string",
56
+ description:
57
+ 'Required: what to look for, in plain words. task never replaces it. Example: {"query": "auth refactor constraints", "task": "finish the auth refactor"}',
58
+ },
55
59
  task: TASK_INPUT,
56
60
  visibility: {
57
61
  type: "string",
@@ -1,5 +1,6 @@
1
1
  import { contextScopeLabel, scopeLabel, taskKey } from "../scope.js"
2
2
  import { errorMessage, oneLine } from "../util.js"
3
+ import { isCoded } from "../errors.js"
3
4
 
4
5
  /**
5
6
  * Roles that may write to a shared space. The plugin reads this from the
@@ -14,7 +15,7 @@ export const WHOLE_SPACE = "*"
14
15
  export const TASK_INPUT = Object.freeze({
15
16
  type: "string",
16
17
  description:
17
- 'One line naming the work, not the topic ("fix the migration ordering"). Kept for the session: later calls and captured turns use it. "*" means the whole space for this call',
18
+ 'Optional context, never a substitute for the required arguments: one line naming the work, not the topic ("fix the migration ordering"). Kept for the session: later calls and captured turns use it. "*" means the whole space for this call',
18
19
  })
19
20
 
20
21
  /** True when a control-plane role may write to a shared space. */
@@ -31,7 +32,8 @@ export function createToolkit(ctx, runtime) {
31
32
  const control = runtime.control
32
33
 
33
34
  const text = (content) => ({ content })
34
- const fail = (message) => text(`memory unavailable: ${message}`)
35
+ // A coded failure (src/errors.js) already says what happened and what to do.
36
+ const fail = (message) => text(isCoded(message) ? message : `memory unavailable: ${message}`)
35
37
 
36
38
  /** Shared-asset scope (skills, wiki). Agent is intentionally absent. */
37
39
  function sharedScope(context) {
@@ -21,7 +21,7 @@ export function registerSpaces(editor, toolkit) {
21
21
  action: {
22
22
  type: "string",
23
23
  enum: ["list", "current"],
24
- description: "list personal and shared spaces, or show the active context",
24
+ description: 'Required: "current" shows the active space, "list" every space you can use. Example: {"action": "current"}',
25
25
  },
26
26
  },
27
27
  required: ["action"],
@@ -96,7 +96,7 @@ export function registerSpaces(editor, toolkit) {
96
96
  input: {
97
97
  type: "object",
98
98
  properties: {
99
- action: { type: "string", enum: ["list"], description: "list grants visible to you" },
99
+ action: { type: "string", enum: ["list"], description: 'Required; the only value is "list". Example: {"action": "list"}' },
100
100
  space: { type: "string", description: "Space id to inspect (control plane); defaults to the active space" },
101
101
  },
102
102
  required: ["action"],
@@ -141,7 +141,7 @@ export function registerSpaces(editor, toolkit) {
141
141
  input: {
142
142
  type: "object",
143
143
  properties: {
144
- action: { type: "string", enum: ["list"], description: "list space members" },
144
+ action: { type: "string", enum: ["list"], description: 'Required; the only value is "list". Example: {"action": "list"}' },
145
145
  space: { type: "string", description: "Space id to inspect (control plane); defaults to the active space" },
146
146
  },
147
147
  required: ["action"],
@@ -16,7 +16,7 @@ export function registerStatus(editor, toolkit) {
16
16
  input: {
17
17
  type: "object",
18
18
  properties: {
19
- space: { type: "string", description: "Space id to report on (control plane); defaults to the active space" },
19
+ space: { type: "string", description: "Optional; no argument is needed. Space id to report on (control plane); defaults to the active space" },
20
20
  },
21
21
  additionalProperties: false,
22
22
  },