@joe-broadhead/opencode-mem 0.8.2 → 0.8.4

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.
@@ -34,9 +34,24 @@
34
34
  * decides who it speaks for, and the token is replaced 60 s before it expires.
35
35
  * A spooled entry records the account its token named and is not replayed
36
36
  * while its session's token names someone else. Work with no session
37
- * (the skill mirror, Memory's views, start-up) asks `token("memory")` as
38
- * before: the contract gives the agent owner's token while the agent is
39
- * private, and refuses it otherwise.
37
+ * (the skill mirror, start-up, and Memory's views on a host before contract
38
+ * v1.5) asks `token("memory")` as before: the contract gives the agent owner's
39
+ * token while the agent is private, and refuses it otherwise.
40
+ *
41
+ * **A view asks for the person who opened it (0.8.3, contract v1.5 §6.1).** A
42
+ * view's call carries no engine session, but a host of v1.5 or later (Jelly
43
+ * 0.3.3) fills the call's `jellySpeaker` input with a speaker id, `view_…`,
44
+ * naming the person whose device made that one call. The view's handler runs
45
+ * the call in `asView(id, fn)`: every credential `fn` asks for is asked
46
+ * `token("memory", { session: id })`, held in that call's scope only and
47
+ * dropped with it. A speaker id is never put in the session cache or its
48
+ * refusal hold, never logged, and never reused by a later call, the skill
49
+ * mirror or background work: each call has a fresh id, and the host keeps
50
+ * the token per person, so asking again costs one round trip, not a mint.
51
+ * The refusals are a session's: `not_signed_in` gives that call no
52
+ * credential (never the pasted key, never another session's or the owner's
53
+ * token); the others fall back as for a session. Without an id (a host
54
+ * before v1.5, stock OpenCode) a view asks as before, with no session.
40
55
  *
41
56
  * A host older than members (Jelly 0.3.2) refuses `{ session }` as options it
42
57
  * does not know (`invalid_target`, detail `invalid_cnf_jwk`; the plugin sends
@@ -114,7 +129,12 @@ const SESSION_PATTERN = /^[A-Za-z0-9_-]{1,128}$/
114
129
  export const UNLINKED_SENTENCE =
115
130
  "Memory isn't available in this chat because the person speaking hasn't linked their Jelly account on this host."
116
131
 
117
- /** The session the current work is done for, and the turn when the work belongs to one: `{ session, turn }`. */
132
+ /**
133
+ * The session the current work is done for, and the turn when the work
134
+ * belongs to one: `{ session, turn }`; for one view call, `view` instead
135
+ * (`asView`): `{ id }`, the call's speaker id, an object that lives as long as
136
+ * the call.
137
+ */
118
138
  const sessionScope = new AsyncLocalStorage()
119
139
 
120
140
  /** A session id the accessor accepts, or "" (work with no session). */
@@ -142,6 +162,34 @@ export function asSession(sessionID, fn, turn) {
142
162
  return sessionScope.run({ session: sessionKey(sessionID), turn: typeof turn === "string" ? turn : "" }, fn)
143
163
  }
144
164
 
165
+ /**
166
+ * Run `fn` as one view call made by the person the speaker id `speaker` names
167
+ * (contract v1.5 §6.1, `jellySpeaker`): every credential it and what it awaits
168
+ * ask for is that person's, asked for this call and kept for it only. A value
169
+ * that is not a string the accessor accepts runs `fn` as work with no session,
170
+ * exactly as a view did before the id existed.
171
+ *
172
+ * @template T
173
+ * @param {unknown} speaker
174
+ * @param {() => T} fn
175
+ * @returns {T}
176
+ */
177
+ export function asView(speaker, fn) {
178
+ const id = sessionKey(speaker)
179
+ if (!id) return asSession("", fn)
180
+ return sessionScope.run({ session: "", turn: "", view: { id } }, fn)
181
+ }
182
+
183
+ /** True inside a view call that carries a speaker id (`asView`). */
184
+ export function inView() {
185
+ return Boolean(sessionScope.getStore()?.view)
186
+ }
187
+
188
+ /** The current view call, `{ id }`, or null. */
189
+ function currentView() {
190
+ return sessionScope.getStore()?.view ?? null
191
+ }
192
+
145
193
  /** The session the current work is done for, or "" for none. */
146
194
  export function currentSession() {
147
195
  return sessionScope.getStore()?.session ?? ""
@@ -319,6 +367,22 @@ export function createCredentials(input = {}) {
319
367
  * (a host older than members): from then on every session asks as `engine`.
320
368
  */
321
369
  let sessionAsks = true
370
+ /**
371
+ * One view call -> its state, for as long as the call's scope object lives:
372
+ * a speaker id is never a key of `sessions`, so it never reaches the LRU,
373
+ * a session's refusal hold, or any later call.
374
+ */
375
+ const views = new WeakMap()
376
+
377
+ /** The state of one view call, created on its first ask. */
378
+ function viewState(view) {
379
+ let state = views.get(view)
380
+ if (!state) {
381
+ state = newState()
382
+ views.set(view, state)
383
+ }
384
+ return state
385
+ }
322
386
 
323
387
  function newEntry() {
324
388
  return { turn: "", state: newState(), pending: null, previous: null }
@@ -351,15 +415,24 @@ export function createCredentials(input = {}) {
351
415
  return entry.state
352
416
  }
353
417
 
354
- /** The state the current work uses, and the session it asks for ("" for none). */
418
+ /**
419
+ * The state the current work uses, the session it asks for ("" for none),
420
+ * and whether that is a view call's speaker id (`view`). On a host that
421
+ * refused `session` (older than members) a view asks as the engine, as it
422
+ * did before.
423
+ */
355
424
  function current() {
425
+ const view = sessionAsks ? currentView() : null
426
+ if (view) return { state: viewState(view), session: view.id, view: true }
356
427
  const session = sessionAsks ? currentSession() : ""
357
- if (!session) return { state: engine, session: "" }
358
- return { state: stateIn(entryOf(session), currentTurn(), true), session }
428
+ if (!session) return { state: engine, session: "", view: false }
429
+ return { state: stateIn(entryOf(session), currentTurn(), true), session, view: false }
359
430
  }
360
431
 
361
432
  /** The current work's state without creating, reordering or rotating one: for reads such as `source()`. */
362
433
  function peek() {
434
+ const view = sessionAsks ? currentView() : null
435
+ if (view) return viewState(view)
363
436
  const session = sessionAsks ? currentSession() : ""
364
437
  if (!session) return engine
365
438
  const entry = sessions.get(session)
@@ -536,18 +609,24 @@ export function createCredentials(input = {}) {
536
609
  * Hold a refusal for `REFUSAL_HOLD_MS` and log it: the code and detail only,
537
610
  * never a token or the accessor's words. Returns the error for this request.
538
611
  *
612
+ * A view call's refusal is logged as `view: true`, never with its speaker
613
+ * id, which is a credential handle; it is held for that call only.
614
+ *
539
615
  * @param {{ refusal: any }} state
540
- * @param {string} session "" for work with no session
616
+ * @param {{ session: string, view: boolean }} asker `session` "" for work with no session
541
617
  * @param {string} code
542
618
  * @param {string} [detail]
543
619
  * @param {string} [reason] why, in the plugin's words; the code's own by default
544
620
  */
545
- function hold(state, session, code, detail = "", reason = TOKEN_ERRORS[code]) {
621
+ function hold(state, asker, code, detail = "", reason = TOKEN_ERRORS[code]) {
546
622
  state.refusal = { code, detail, reason, until: now() + REFUSAL_HOLD_MS }
547
- const fields = { code, ...(detail ? { detail } : {}), ...(session ? { sessionID: session } : {}), holdMs: REFUSAL_HOLD_MS }
623
+ const who = asker.view ? { view: true } : asker.session ? { sessionID: asker.session } : {}
624
+ const fields = { code, ...(detail ? { detail } : {}), ...who, holdMs: REFUSAL_HOLD_MS }
548
625
  if (unlinkedRefusal(state.refusal)) {
549
626
  log?.warn?.(
550
- "Jelly has no memory token for the person speaking: they have not linked a Jelly account on this host; memory is off for this session, and the saved memory key is not used in its place",
627
+ asker.view
628
+ ? "Jelly has no memory token for the person who opened this view: they have not linked a Jelly account on this host; this call gets no credential, and the saved memory key is not used in its place"
629
+ : "Jelly has no memory token for the person speaking: they have not linked a Jelly account on this host; memory is off for this session, and the saved memory key is not used in its place",
551
630
  fields,
552
631
  )
553
632
  } else if (FALLBACK_CODES.includes(code)) {
@@ -584,10 +663,15 @@ export function createCredentials(input = {}) {
584
663
  }
585
664
 
586
665
  /**
587
- * Ask Jelly for a token for `state`: with `session` when there is one, else
588
- * as before. One call per state in flight.
666
+ * Ask Jelly for a token for `state`: with `session` when there is one (an
667
+ * engine session or a view call's speaker id), else as before. One call per
668
+ * state in flight.
669
+ *
670
+ * @param {any} state
671
+ * @param {string} session
672
+ * @param {boolean} [view] `session` is a view call's speaker id
589
673
  */
590
- function mint(state, session) {
674
+ function mint(state, session, view = false) {
591
675
  if (state.minting) return state.minting
592
676
  const flight = (async () => {
593
677
  const accessor = identity()
@@ -609,12 +693,12 @@ export function createCredentials(input = {}) {
609
693
  }
610
694
  const code = typeof member(error, "code") === "string" && TOKEN_ERRORS[error.code] ? error.code : "unavailable"
611
695
  const detail = typeof member(error, "detail") === "string" ? error.detail : ""
612
- throw hold(state, session, code, detail)
696
+ throw hold(state, { session, view }, code, detail)
613
697
  }
614
698
  const accessToken = usableToken(member(answer, "accessToken"))
615
699
  const expiresAt = Number(member(answer, "expiresAt"))
616
700
  if (!accessToken || !Number.isFinite(expiresAt)) {
617
- throw hold(state, session, "unavailable", "", "Jelly returned a malformed memory token")
701
+ throw hold(state, { session, view }, "unavailable", "", "Jelly returned a malformed memory token")
618
702
  }
619
703
  const entry = { accessToken, expiresAt }
620
704
  state.refusal = null
@@ -660,7 +744,7 @@ export function createCredentials(input = {}) {
660
744
  if (!refused) {
661
745
  if (fresh(asked.state.cached)) return asked.state.cached.accessToken
662
746
  try {
663
- return (await mint(asked.state, asked.session)).accessToken
747
+ return (await mint(asked.state, asked.session, asked.view)).accessToken
664
748
  } catch (error) {
665
749
  // The ask may have moved to the engine's state (a host older than members).
666
750
  refused = held(current().state)
@@ -687,13 +771,13 @@ export function createCredentials(input = {}) {
687
771
  async function refresh(rejected) {
688
772
  if (optionToken || !memoryResource()) return ""
689
773
  if (!rejected || rejected === secretToken()) return ""
690
- const { state, session } = current()
774
+ const { state, session, view } = current()
691
775
  if (held(state)) return ""
692
776
  if (state.cached?.accessToken === rejected) state.cached = null
693
777
  if (fresh(state.cached)) return state.cached.accessToken
694
778
  let next
695
779
  try {
696
- next = (await mint(state, session)).accessToken
780
+ next = (await mint(state, session, view)).accessToken
697
781
  } catch {
698
782
  return ""
699
783
  }
package/src/curation.js CHANGED
@@ -35,6 +35,18 @@ const STATUS = [
35
35
  /\bon (?:the|my|our|a) to-?do list\b/i,
36
36
  /\btbd\b/i,
37
37
  /\bpending (?:confirmation|review|approval)\b/i,
38
+ // A status label opening a line: "Status: half done", "Progress - 3 of 5".
39
+ // Not "status 403", "Status codes:", or "Status-shaped writes".
40
+ /^\s*(?:status|progress)\s*(?::|[-–—]\s)/im,
41
+ // A line that opens as a work-in-progress marker: "WIP: auth", "In progress: x".
42
+ /^\s*(?:wip|in progress)\b\s*[:\-–—]?/im,
43
+ // Partly finished, said of something: "the walkthrough is half done". Not a
44
+ // rule about such things ("never ship half done migrations").
45
+ /\b(?:is|are|was|were|now|currently|still)\s+(?:about |roughly |around |only |just )?(?:half|mostly|nearly|almost|partly|partially)[- ](?:done|finished|complete|completed|through)\b/i,
46
+ // Progress as a share: "40% done", "70 % complete". Not "an error budget of 0.1%".
47
+ /\b\d{1,3}(?:\.\d+)?\s?%\s+(?:done|complete|completed|finished|through)\b/i,
48
+ // Under way, said of something: "the migration is under way".
49
+ /\b(?:is|are|was|were|now|currently|still)\s+(?:well\s+)?under\s?way\b/i,
38
50
  ]
39
51
 
40
52
  // The reply payload is a fixed all-caps token or a short quoted string that
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * The plugin's own default permission rules: `mem_forget` asks before it runs
3
- * (D17, "Forget asks"). Forgetting deletes, and a delete cannot be undone, so it
4
- * asks in every space; the other tools run as the agent's rules let them.
3
+ * (D17, "Forget asks"), and so does a wiki delete (`wiki.delete`, 0.8.4).
4
+ * Forgetting and deleting cannot be undone, so they ask in every space; the
5
+ * other tools run as the agent's rules let them.
5
6
  *
6
7
  * The engine consults a rule on a plugin tool's id only when the tool asserts
7
8
  * it, so `mem_forget` asserts `mem_forget` before it deletes
@@ -23,7 +24,12 @@
23
24
  /** @typedef {{ action: string, resource: string, effect: "allow" | "ask" | "deny" }} Rule */
24
25
 
25
26
  /** @type {readonly Rule[]} */
26
- export const DEFAULT_RULES = Object.freeze([Object.freeze({ action: "mem_forget", resource: "*", effect: "ask" })])
27
+ export const DEFAULT_RULES = Object.freeze([
28
+ Object.freeze({ action: "mem_forget", resource: "*", effect: "ask" }),
29
+ // A wiki delete always asks, private or team (mem_wiki delete with confirm),
30
+ // for the same reason: it cannot be undone. Jelly asks it through `asks`.
31
+ Object.freeze({ action: "wiki.delete", resource: "*", effect: "ask" }),
32
+ ])
27
33
 
28
34
  const BASE_ALLOW = { action: "*", resource: "*", effect: "allow" }
29
35
  const same = (a, b) => a?.action === b.action && a?.resource === b.resource && a?.effect === b.effect
@@ -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",