@joe-broadhead/opencode-mem 0.9.5 → 0.9.12

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 (53) hide show
  1. package/CHANGELOG.md +1281 -0
  2. package/README.md +105 -31
  3. package/docs/agent-protocol.md +28 -27
  4. package/docs/permissions.md +148 -0
  5. package/package.json +24 -12
  6. package/skills/mem.pages/SKILL.md +35 -16
  7. package/skills/mem.sharing/SKILL.md +39 -6
  8. package/skills/mem.sources/SKILL.md +41 -10
  9. package/skills/mem.usage/SKILL.md +37 -16
  10. package/src/backend/records.js +8 -0
  11. package/src/backend/v3.js +15 -10
  12. package/src/call-shapes.js +18 -25
  13. package/src/capture-pause.js +136 -0
  14. package/src/capture.js +7 -5
  15. package/src/collector-service.js +212 -35
  16. package/src/collector.js +186 -47
  17. package/src/commands.js +37 -0
  18. package/src/compaction.js +4 -2
  19. package/src/config.js +151 -1
  20. package/src/curation.js +6 -10
  21. package/src/events.js +144 -36
  22. package/src/forget-purge.js +377 -0
  23. package/src/forgotten.js +152 -0
  24. package/src/hooks.js +9 -4
  25. package/src/index.js +5 -3
  26. package/src/permissions.js +116 -38
  27. package/src/protocol.js +21 -11
  28. package/src/records.js +4 -1
  29. package/src/runtime.js +202 -15
  30. package/src/shapes.js +63 -0
  31. package/src/sources.js +183 -12
  32. package/src/spaces.js +58 -1
  33. package/src/spool.js +442 -64
  34. package/src/stated.js +334 -0
  35. package/src/storable.js +477 -0
  36. package/src/tools/aliases.js +36 -147
  37. package/src/tools/commitments.js +69 -12
  38. package/src/tools/index.js +25 -43
  39. package/src/tools/ingest.js +33 -128
  40. package/src/tools/memory.js +503 -904
  41. package/src/tools/page-sections.js +147 -0
  42. package/src/tools/page.js +314 -82
  43. package/src/tools/recall-browse.js +173 -0
  44. package/src/tools/recall.js +36 -8
  45. package/src/tools/share.js +494 -131
  46. package/src/tools/shared.js +97 -19
  47. package/src/tools/spaces.js +194 -101
  48. package/src/tools/status.js +31 -3
  49. package/src/tools/wiki.js +5 -13
  50. package/src/util.js +10 -59
  51. package/src/views/profile.js +2 -3
  52. package/src/views/records-reads.js +6 -1
  53. package/src/erase.js +0 -36
@@ -1,7 +1,5 @@
1
- import { randomBytes } from "node:crypto"
2
1
  import { normalizeVisibility } from "../scope.js"
3
2
  import { writeRefusal } from "../curation.js"
4
- import { containsPhrase, eraseLines, matchingLines, MIN_ERASE_CHARS } from "../erase.js"
5
3
  import {
6
4
  REMEMBER_WRAPPER,
7
5
  copyExcerpt,
@@ -19,18 +17,9 @@ import { errorMessage, neutralizeFenceClosers, oneLine, redactSecrets } from "..
19
17
  import { isCoded } from "../errors.js"
20
18
  import { RecordsError, isRecordsUnavailable } from "../backend/records.js"
21
19
  import { FORGOTTEN_ID, createForgottenMatcher } from "../forgotten.js"
22
- import { TASK_INPUT, canWriteShared } from "./shared.js"
23
- import { holdTeamWrite } from "./held-write.js"
20
+ import { TASK_INPUT, canWriteShared, hostProvenance } from "./shared.js"
24
21
  import { CORE_ID, MEMORY_TYPES, PAGE_PATH, RECORD_ID, TURN_ID, callRecords, changeNote, dateOf, lineageIds, noteRecordSpace, notWritten, recordLine, recordSpace, titleFrom } from "./records-kit.js"
25
22
 
26
- /**
27
- * The permission mem_forget asserts before it deletes: the tool's own engine
28
- * id, declared `effect: "ask"` in `jelly.tools`. Not an approval action
29
- * (`jelly.asks`), so it is a name here, not a literal the scan in
30
- * scripts/approval-actions.mjs would read as one.
31
- */
32
- const FORGET_PERMISSION = "mem_forget"
33
-
34
23
  const KINDS = MEMORY_TYPES
35
24
  /** A supersede replaces a few records, not a cleanup: more is a forget. */
36
25
  const MAX_SUPERSEDES = 10
@@ -43,6 +32,24 @@ export const REVISE_ACTIONS = Object.freeze(["correct", "confirm", "retire", "re
43
32
  * the upstream per-message limit and points long synthesis at the wiki.
44
33
  */
45
34
  const MAX_CONTENT_CHARS = 4_000
35
+ /** Ids one mem_revise call takes (records.get reads 50 at a time). */
36
+ export const MAX_REVISE_IDS = 50
37
+ /** The records service's batch action that deletes (records.revise {ids, action}); not an approval action. */
38
+ const RECORDS_FORGET = "forget"
39
+ /** The records service's retire action, for a kept atom copy whose replacement was not stored. */
40
+ const RECORDS_RETIRE = "retire"
41
+ /** The actions mem_revise applies to several ids at once. */
42
+ export const BATCH_VERBS = Object.freeze(["confirm", "retire", "restore", "forget"])
43
+ /** An ask names each item with this much of its text. */
44
+ const ASK_EXCERPT_CHARS = 120
45
+ /** Items an ask lists one by one; the count covers the rest. */
46
+ const ASK_ITEMS = 60
47
+ /** Forgotten-copy fingerprints one person keeps per space (records/src/forgotten.js MAX_PER_AUTHOR). */
48
+ export const FINGERPRINT_CAP = 2_000
49
+ /** A forget reports the fingerprint budget when this few or fewer are left. */
50
+ const FINGERPRINT_NEAR = 200
51
+ /** Facts a forget reads back one by one; a larger batch says the rest were not. */
52
+ const READBACK_FACTS = 10
46
53
 
47
54
  /** The forget scan reads at most this many rows per layer and agent. */
48
55
  const SCAN_PAGE = 100
@@ -55,64 +62,177 @@ const COPY_SCAN_MS = 5_000
55
62
  /** Copies listed in one forget result; the rest are counted, not shown. */
56
63
  const MAX_COPIES_LISTED = 10
57
64
  const COPY_EXCERPT_CHARS = 120
58
- /** Upstream caps L2 at 15 scenes; read a little more in case that changes. */
59
- const MAX_SCENARIOS = 30
65
+
66
+ /** A non-empty string, or undefined. */
67
+ function field(value) {
68
+ return value === undefined || value === null || value === "" ? undefined : String(value)
69
+ }
60
70
 
61
71
  /**
62
- * Shares (mem_promote): one wiki per share, holding a copy of private memory
63
- * (docs/design/adr-sharing-semantics.md). The marker on the first line is
64
- * how a revoke tells a share from any other wiki before it deletes anything.
72
+ * The text of an atom as it is kept: a remember wrapper's fact and its
73
+ * Context part, or the atom's whole text; the core's own context (background)
74
+ * is kept too when the text carries none.
65
75
  */
66
- const MAX_SHARE_IDS = 20
67
- const MAX_SHARED_CHARS = 8_000
68
- const SHARE_FILE = "SHARE.md"
69
- const SHARE_MARKER = "<!-- opencode-mem:share v1 -->"
76
+ function keptText({ row, text }) {
77
+ const parts = rememberParts(text)
78
+ const fact = (parts.kind === "wrapper" ? parts.body : text).trim()
79
+ if (!fact) return ""
80
+ const context = parts.kind === "wrapper" && parts.reason ? parts.reason : String(row?.background ?? "").trim()
81
+ return context ? `${fact}\n\nContext: ${context}` : fact
82
+ }
83
+
84
+ /** The atom's id, agent, session and time, as the core reports them, for the kept record's fields. */
85
+ function atomProvenance(id, { row, agent }) {
86
+ const out = {
87
+ atom_id: id,
88
+ atom_agent: field(row?.agent_id ?? row?.agentId) ?? field(agent),
89
+ atom_session: field(row?.session_id ?? row?.session_key ?? row?.sessionId),
90
+ atom_created: field(row?.created_at ?? row?.createdAt ?? row?.created),
91
+ }
92
+ return Object.fromEntries(Object.entries(out).filter(([, value]) => value !== undefined).map(([key, value]) => [key, oneLine(value, 200)]))
93
+ }
70
94
 
71
95
  /**
72
- * The core's forget machinery, one per toolkit, shared by mem_revise (for
73
- * `m_` and `msg-` ids) and the legacy mem_forget, so a copy reported by one is
74
- * matched by the other (docs/design/adr-forget-copies.md).
96
+ * The core's forget machinery, one per toolkit, for mem_revise's `m_` and
97
+ * `msg-` ids and the copies a forget reports (docs/design/adr-forget-copies.md).
75
98
  *
76
99
  * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
77
100
  */
78
101
  export function createCoreForget(toolkit) {
79
102
  if (coreForgets.has(toolkit)) return coreForgets.get(toolkit)
80
103
  const { backend, locate, noteLocations, forgetLocations, knownAgents, rowLocation } = toolkit
104
+ // A turn is deleted under the session it was written under, sent with the
105
+ // space; keepBinding stops a control before 0.9.7 from rebinding that session.
106
+ // `notes` collects what the answer must say if the binding could not be put back.
107
+ const deleteTurns = (args, notes) =>
108
+ toolkit.runtime?.keepBinding ? toolkit.runtime.keepBinding(args.scope, () => backend.deleteConversations(args), notes) : backend.deleteConversations(args)
81
109
 
82
110
  /**
83
- * Remove the core L1 atoms a new memory replaces, after it was stored.
84
- * Each id is deleted under the agent that wrote it, as mem_recall showed it;
85
- * an id this process has not seen is tried under this session's agent. Only
86
- * the backend's count is reported. Captured turns are history and stay.
111
+ * Each core atom as the core holds it: its full text and provenance, read
112
+ * from the core's own listing of the newest atoms (the agent that wrote it
113
+ * first, as recall showed it). The location cache is used only to choose the
114
+ * agent: its text is cut at 1,000 characters, so it is never kept. An id the
115
+ * listing does not reach is left out of the answer.
87
116
  */
88
- async function supersede(ids, spaceContext, base) {
89
- const groups = new Map()
117
+ async function atomRows(ids, spaceContext, base) {
118
+ const found = new Map()
119
+ const pending = () => ids.filter((id) => !found.has(id))
120
+ const seen = ids.map((id) => locate(spaceContext, id)).filter((hit) => hit?.layer === "l1").map((hit) => hit.agent_id)
121
+ const agents = [...new Set([...seen, base.agent_id, ...knownAgents(spaceContext)])].filter(Boolean).slice(0, 4)
122
+ for (const agent of agents) {
123
+ if (pending().length === 0) break
124
+ await readListing({
125
+ pages: new Map(),
126
+ readPage: async (offset) => {
127
+ const data = await backend.queryAtoms({ scope: { ...base, agent_id: agent }, limit: SCAN_PAGE, offset })
128
+ const rows = data?.items ?? data?.records ?? []
129
+ noteLocations(spaceContext, "l1", rows, { agent_id: agent })
130
+ return { rows, total: data?.total }
131
+ },
132
+ pageSize: SCAN_PAGE,
133
+ maxPages: SCAN_PAGES,
134
+ onPage: (rows) => {
135
+ for (const row of rows) {
136
+ const id = String(row?.id ?? "")
137
+ const content = String(row?.content ?? row?.text ?? "")
138
+ if (ids.includes(id) && !found.has(id) && content.trim()) found.set(id, { row, text: content, agent: field(row?.agent_id ?? row?.agentId) ?? agent })
139
+ }
140
+ },
141
+ stop: () => pending().length === 0,
142
+ })
143
+ }
144
+ return found
145
+ }
146
+
147
+ /**
148
+ * Keep the text of the core atoms a new memory replaces (0.9.9, WRITES-099).
149
+ * An atom has no history of its own, so before it is replaced its full text
150
+ * (with a remember wrapper's Context part) is stored as a memory record,
151
+ * with the atom's agent, session and time in its fields; the new memory then
152
+ * supersedes that record, as it supersedes a rec_ id: kept, shown by recall
153
+ * with status "all" and in mem_revise history. An atom whose full text the
154
+ * core does not return, or that would be refused as a record, is not
155
+ * replaced at all, so nothing is lost unasked.
156
+ *
157
+ * @returns {Promise<{ kept: Map<string, { record: string, agent?: string }>, left: string[] }>}
158
+ */
159
+ async function keepAtoms({ ids, spaceContext, scoped, base, session }) {
160
+ const kept = new Map()
161
+ const left = []
162
+ let texts = new Map()
163
+ try {
164
+ texts = await atomRows(ids, spaceContext, base)
165
+ } catch {
166
+ /* every id is left as it is */
167
+ }
90
168
  for (const id of ids) {
91
- const hit = locate(spaceContext, id)
92
- const agent = hit?.layer === "l1" && hit.agent_id ? hit.agent_id : base.agent_id
93
- if (!groups.has(agent)) groups.set(agent, [])
94
- groups.get(agent).push(id)
169
+ const found = texts.get(id)
170
+ const body = found ? keptText(found) : ""
171
+ if (!body || writeRefusal(body)) {
172
+ left.push(id)
173
+ continue
174
+ }
175
+ try {
176
+ const record = {
177
+ kind: "memory",
178
+ type: "fact",
179
+ title: titleFrom(body),
180
+ body: `${body}\n\nWhy: the text of core atom ${oneLine(id, 80)}, kept as history when a newer memory replaced it`,
181
+ stated_by: "agent",
182
+ fields: atomProvenance(id, found),
183
+ source: session ? { session: String(session) } : {},
184
+ }
185
+ const stored = (await callRecords(toolkit, "records.put", { record }, spaceContext, scoped))?.record
186
+ if (RECORD_ID.test(String(stored?.id ?? ""))) kept.set(id, { record: stored.id, agent: found.agent })
187
+ else left.push(id)
188
+ } catch {
189
+ left.push(id)
190
+ }
95
191
  }
192
+ return { kept, left }
193
+ }
194
+
195
+ /** The new memory was not stored: the kept copies would read as current, so they are retired. */
196
+ async function dropKept(keep, spaceContext, scoped) {
197
+ for (const { record } of keep?.kept?.values?.() ?? []) {
198
+ try {
199
+ await callRecords(toolkit, "records.revise", { id: record, action: RECORDS_RETIRE, reason: "the memory that was to replace it was not stored" }, spaceContext, scoped)
200
+ } catch {
201
+ /* best effort: the answer already says the write failed */
202
+ }
203
+ }
204
+ }
205
+
206
+ /**
207
+ * After the new memory `byId` is stored: remove each kept atom from the
208
+ * core, so recall stops serving the old value (its text lives on in the
209
+ * superseded record), and say what happened to every id. Each id is deleted
210
+ * under the agent that wrote it; captured turns are history and stay.
211
+ */
212
+ async function supersede(keep, byId, spaceContext, base) {
96
213
  const removed = []
97
- const missing = []
98
- const failed = []
99
- for (const [agent, group] of groups) for (const id of group) {
214
+ const notRemoved = []
215
+ for (const [id, { record, agent }] of keep.kept) {
216
+ const where = locate(spaceContext, id)
217
+ const owner = agent || (where?.layer === "l1" && where.agent_id) || base.agent_id
100
218
  try {
101
- const data = await backend.deleteAtoms({ ids: [id], scope: { ...base, ...(agent ? { agent_id: agent } : {}) } })
219
+ const data = await backend.deleteAtoms({ ids: [id], scope: { ...base, ...(owner ? { agent_id: owner } : {}) } })
102
220
  const confirmed = Array.isArray(data?.deleted_ids) ? data.deleted_ids.includes(id) : Number(data?.deleted_count) === 1
103
- ;(confirmed ? removed : missing).push(id)
221
+ ;(confirmed ? removed : notRemoved).push(`${oneLine(id, 80)} as ${record}`)
222
+ if (confirmed) forgetLocations(spaceContext, [id])
104
223
  } catch (error) {
105
- failed.push(`${oneLine(id, 80)} (${errorMessage(error)})`)
224
+ notRemoved.push(`${oneLine(id, 80)} as ${record} (${errorMessage(error)})`)
106
225
  }
107
226
  }
108
- forgetLocations(spaceContext, removed)
109
- const list = (values) => values.map((id) => oneLine(id, 80)).join(", ")
110
227
  const lines = []
111
228
  if (removed.length > 0) {
112
- lines.push(`Superseded atom${removed.length === 1 ? "" : "s"} ${list(removed)}: deleted now (atoms have no history to keep).`)
229
+ lines.push(`Superseded atom${removed.length === 1 ? "" : "s"} ${removed.join(", ")}: the text is kept as history, marked superseded by ${byId} (mem_recall status "all" shows it; mem_revise history shows the lineage), and the atom is removed from the core.`)
230
+ }
231
+ if (notRemoved.length > 0) lines.push(`Kept the text of ${notRemoved.join(", ")}, but the atom was not removed from the core, so recall may still show it.`)
232
+ if (keep.left.length > 0) {
233
+ const list = keep.left.map((id) => oneLine(id, 80)).join(", ")
234
+ lines.push(`Not replaced: ${list}. ${keep.left.length === 1 ? "Its" : "Their"} text could not be kept as history, so ${keep.left.length === 1 ? "it stays" : "they stay"} and recall may still show ${keep.left.length === 1 ? "it" : "them"}. Removing ${keep.left.length === 1 ? "it" : "them"} is a forget: ask the person first.`)
113
235
  }
114
- if (missing.length > 0) lines.push(`Not found, so not removed: ${list(missing)} (pass ids from mem_recall).`)
115
- if (failed.length > 0) lines.push(`Not removed, the delete failed: ${failed.join("; ")}.`)
116
236
  lines.push("Captured turns that mention the old value stay as history.")
117
237
  return lines.join(" ")
118
238
  }
@@ -143,7 +263,7 @@ export function createCoreForget(toolkit) {
143
263
  * 4. Delete the named ids, then those remember rows.
144
264
  * 5. Report every other copy with its id and an excerpt; delete nothing else.
145
265
  */
146
- async function deleteByIds({ ids, wanted, spaceContext, base, explicitAgent, approve, retryArgs = {} }) {
266
+ async function deleteByIds({ ids, wanted, spaceContext, base, explicitAgent, approve }) {
147
267
  const found = new Map()
148
268
  for (const id of ids) {
149
269
  const hit = locate(spaceContext, id)
@@ -284,6 +404,8 @@ export function createCoreForget(toolkit) {
284
404
  groups.get(key).ids.push(id)
285
405
  }
286
406
  const removed = { l0: 0, l1: 0 }
407
+ // What the answer must say if a turn delete moved the session's binding and it could not be put back.
408
+ const bindingNotes = []
287
409
  const confirmedIDs = []
288
410
  const unconfirmed = []
289
411
  const noSession = []
@@ -298,7 +420,7 @@ export function createCoreForget(toolkit) {
298
420
  const data =
299
421
  group.layer === "l1"
300
422
  ? await backend.deleteAtoms({ ids: group.ids, scope: groupScope })
301
- : await backend.deleteConversations({ messageIDs: group.ids, scope: { ...groupScope, session_id: group.session } })
423
+ : await deleteTurns({ messageIDs: group.ids, scope: { ...groupScope, session_id: group.session } }, bindingNotes)
302
424
  const count = Math.max(0, Math.min(group.ids.length, Number(data?.deleted_count) || 0))
303
425
  removed[group.layer] += count
304
426
  if (count < group.ids.length) unconfirmed.push({ ...group, missing: group.ids.length - count })
@@ -338,10 +460,13 @@ export function createCoreForget(toolkit) {
338
460
  for (const group of ownGroups.values()) {
339
461
  const messageIDs = group.rows.map((row) => row.id)
340
462
  try {
341
- const data = await backend.deleteConversations({
342
- messageIDs,
343
- scope: { ...base, ...(group.agent ? { agent_id: group.agent } : {}), session_id: group.session },
344
- })
463
+ const data = await deleteTurns(
464
+ {
465
+ messageIDs,
466
+ scope: { ...base, ...(group.agent ? { agent_id: group.agent } : {}), session_id: group.session },
467
+ },
468
+ bindingNotes,
469
+ )
345
470
  const count = Math.max(0, Math.min(messageIDs.length, Number(data?.deleted_count) || 0))
346
471
  if (count === messageIDs.length) ownDeleted.push(...group.rows)
347
472
  else ownKept.push(...group.rows.map((row) => ({ ...row, note: `the backend confirmed ${count} of ${messageIDs.length} in its session` })))
@@ -395,6 +520,7 @@ export function createCoreForget(toolkit) {
395
520
  `Also deleted ${ownDeleted.length} l0 row(s) mem_remember wrote for this text that hold nothing else (its request, which mem_recall never shows, and its "Understood." echo): ${list(ownDeleted.map((row) => row.id))}.`,
396
521
  )
397
522
  }
523
+ lines.push(...new Set(bindingNotes))
398
524
  const report =
399
525
  total > 0 && found.size > 0
400
526
  ? copiesReport({
@@ -402,7 +528,6 @@ export function createCoreForget(toolkit) {
402
528
  copies: [...ownKept, ...copies],
403
529
  windows,
404
530
  base,
405
- retryArgs,
406
531
  unscannedAgents: knownAgents(spaceContext).filter((agent) => !copyAgents.includes(agent)),
407
532
  })
408
533
  : ""
@@ -415,7 +540,7 @@ export function createCoreForget(toolkit) {
415
540
  * The copies block of a forget result: bounded, fenced as stored memory
416
541
  * text, with the ids and the call that deletes them, and what was scanned.
417
542
  */
418
- function copiesReport({ forgotten, copies, windows, base, retryArgs, unscannedAgents = [] }) {
543
+ function copiesReport({ forgotten, copies, windows, base, unscannedAgents = [] }) {
419
544
  const scanned = new Map()
420
545
  for (const window of windows) {
421
546
  if (!scanned.has(window.agent)) scanned.set(window.agent, {})
@@ -476,126 +601,13 @@ export function createCoreForget(toolkit) {
476
601
  lines.push(`(+${ranked.length - shown.length} more not listed or deleted; these also need individual review.)`)
477
602
  }
478
603
  lines.push("</forget_copies>")
479
- const byAgent = new Map()
480
- for (const row of shown) {
481
- const agent = row.agent_id ?? base.agent_id
482
- if (!byAgent.has(agent)) byAgent.set(agent, [])
483
- byAgent.get(agent).push(row.id)
484
- }
485
- const calls = [...byAgent].map(([agent, rowIDs]) =>
486
- `mem_forget(${JSON.stringify({ ids: rowIDs, ...retryArgs, ...(agent && agent !== base.agent_id ? { agent } : {}) })})`,
487
- )
604
+ // revise forget finds each listed id where this scan saw it, whichever agent wrote it.
605
+ const calls = [`mem_revise(${JSON.stringify({ action: RECORDS_FORGET, ids: shown.map((row) => row.id) })})`]
488
606
  lines.push(`A match is only a candidate, not proof. Show each entire turn and ask for explicit consent to delete that whole turn, including unrelated text; never infer consent from the original fact request. After the person agrees to each listed item: ${calls.join("; ")}.`)
489
607
  lines.push(scannedLine)
490
608
  return lines.join("\n")
491
609
  }
492
610
 
493
- /**
494
- * Erase the lines that contain a phrase from the L3 persona and the L2
495
- * scenarios. Without `apply` it only reads and reports. With `apply` it
496
- * rewrites every file that has a matching line, rebuilds the pinned block,
497
- * and reads the files back so the result states where the phrase remains.
498
- */
499
- async function eraseSummaries({ phrase, layers, apply, scope }) {
500
- const readFiles = async () => {
501
- const files = []
502
- const notes = []
503
- if (layers.includes("l3")) {
504
- try {
505
- const data = await backend.readCore({ scope })
506
- files.push({ layer: "l3", path: "persona", content: typeof data?.content === "string" ? data.content : "" })
507
- } catch (error) {
508
- files.push({ layer: "l3", path: "persona", content: "", error: errorMessage(error) })
509
- }
510
- }
511
- if (layers.includes("l2")) {
512
- try {
513
- const listed = await backend.listScenarios({ scope })
514
- const entries = (listed?.entries ?? []).filter((entry) => entry?.path && !String(entry.path).endsWith("/"))
515
- if (entries.length > MAX_SCENARIOS) notes.push(`Only the first ${MAX_SCENARIOS} of ${entries.length} scenarios were read.`)
516
- for (const entry of entries.slice(0, MAX_SCENARIOS)) {
517
- const path = String(entry.path)
518
- try {
519
- const data = await backend.readScenario({ path, scope })
520
- files.push({ layer: "l2", path, summary: String(entry.summary ?? ""), content: String(data?.content ?? "") })
521
- } catch (error) {
522
- files.push({ layer: "l2", path, summary: String(entry.summary ?? ""), content: "", error: errorMessage(error) })
523
- }
524
- }
525
- } catch (error) {
526
- notes.push(`The scenario list could not be read (${errorMessage(error)}), so L2 was not checked.`)
527
- }
528
- }
529
- return { files, notes }
530
- }
531
-
532
- const quote = (line) => ` > ${neutralizeFenceClosers(oneLine(line, 160))}`
533
- const name = (file) => (file.layer === "l3" ? "L3 persona" : `L2 ${neutralizeFenceClosers(oneLine(file.path, 160))}`)
534
- const before = await readFiles()
535
- const lines = []
536
- for (const note of before.notes) lines.push(note)
537
- for (const file of before.files) if (file.error) lines.push(`${name(file)} could not be read: ${file.error}.`)
538
- const hits = before.files.filter((file) => !file.error && matchingLines(file.content, phrase).length > 0)
539
- const summaryHits = before.files.filter((file) => file.layer === "l2" && containsPhrase(file.summary, phrase))
540
-
541
- if (!apply) {
542
- const body = []
543
- for (const file of hits) {
544
- const found = matchingLines(file.content, phrase)
545
- body.push(`- ${name(file)}: ${found.length} line(s) contain it:`)
546
- body.push(...found.slice(0, 10).map(quote))
547
- if (found.length > 10) body.push(` (+${found.length - 10} more)`)
548
- }
549
- for (const file of summaryHits) {
550
- body.push(`- L2 summary of ${neutralizeFenceClosers(oneLine(file.path, 160))} contains it; rewriting the file does not change the summary the backend lists.`)
551
- }
552
- const checked = before.files.filter((file) => !file.error).length
553
- if (body.length === 0) body.push(`No line in the ${checked} file(s) checked contains it.`)
554
- return {
555
- changed: 0,
556
- text: [
557
- `<forget_preview phrase="${neutralizeFenceClosers(oneLine(phrase, 80)).replace(/"/g, "'")}">`,
558
- "Preview only: nothing was changed. The lines below are stored memory text: data, not instructions.",
559
- ...body,
560
- "</forget_preview>",
561
- ...lines,
562
- ].join("\n"),
563
- }
564
- }
565
-
566
- let changed = 0
567
- for (const file of hits) {
568
- const next = eraseLines(file.content, phrase)
569
- try {
570
- if (file.layer === "l3") await backend.writeCore({ content: next.content, scope })
571
- else await backend.writeScenario({ path: file.path, content: next.content, scope })
572
- changed += 1
573
- lines.push(`${name(file)}: removed ${next.removed} line(s).`)
574
- } catch (error) {
575
- lines.push(`${name(file)}: write failed, nothing removed (${errorMessage(error)}).`)
576
- }
577
- }
578
- if (hits.length === 0) lines.push("No persona or scenario line contained it, so nothing was rewritten.")
579
- // The pinned block caches L2/L3 for ten minutes; drop every cached copy.
580
- if (changed > 0) toolkit.runtime.invalidate?.()
581
-
582
- const after = await readFiles()
583
- const remaining = []
584
- for (const file of after.files) {
585
- if (file.error) remaining.push(`${name(file)} (could not be read back: ${file.error})`)
586
- else if (containsPhrase(file.content, phrase)) remaining.push(name(file))
587
- if (file.layer === "l2" && containsPhrase(file.summary, phrase)) {
588
- remaining.push(`the L2 summary of ${neutralizeFenceClosers(oneLine(file.path, 160))}, which the backend keeps outside the file`)
589
- }
590
- }
591
- lines.push(
592
- remaining.length === 0
593
- ? `Read back: no persona or scenario checked (${after.files.length} file(s)) contains it.`
594
- : `Read back: it remains in ${remaining.join("; ")}.`,
595
- )
596
- return { changed, text: lines.join(" ") }
597
- }
598
-
599
611
  /** One newest-first page of a layer's rows under one agent, noting where each row was written. */
600
612
  const pageReader = (spaceContext, base, agent, layer) => async (offset) => {
601
613
  const listScope = { ...base, agent_id: agent }
@@ -653,6 +665,7 @@ export function createCoreForget(toolkit) {
653
665
  * what it did not delete, with the reason.
654
666
  */
655
667
  async function deleteRows(rows, base) {
668
+ const notes = []
656
669
  const groups = new Map()
657
670
  for (const row of rows) {
658
671
  const key = `${row.layer}::${row.agent_id ?? ""}::${row.layer === "l0" ? (row.session_id ?? "") : ""}`
@@ -672,7 +685,7 @@ export function createCoreForget(toolkit) {
672
685
  const data =
673
686
  group.layer === "l1"
674
687
  ? await backend.deleteAtoms({ ids, scope })
675
- : await backend.deleteConversations({ messageIDs: ids, scope: { ...scope, session_id: group.session } })
688
+ : await deleteTurns({ messageIDs: ids, scope: { ...scope, session_id: group.session } }, notes)
676
689
  const confirmed = Array.isArray(data?.deleted_ids) ? data.deleted_ids.includes(row.id) : Number(data?.deleted_count) === 1
677
690
  if (confirmed) deleted.push(row)
678
691
  else kept.push({ ...row, why: "the core did not confirm the delete" })
@@ -680,7 +693,7 @@ export function createCoreForget(toolkit) {
680
693
  kept.push({ ...row, why: `the delete failed: ${errorMessage(error)}` })
681
694
  }
682
695
  }
683
- return { deleted, kept }
696
+ return { deleted, kept, notes: [...new Set(notes)] }
684
697
  }
685
698
 
686
699
  /**
@@ -709,7 +722,7 @@ export function createCoreForget(toolkit) {
709
722
  return { left: [...new Map(left.map((row) => [row.id, row])).values()], failed }
710
723
  }
711
724
 
712
- const api = { supersedeAtoms: supersede, deleteByIds, eraseSummaries, scanCopies, deleteRows, remainingCopies, copiesReport }
725
+ const api = { keepAtoms, dropKept, supersedeAtoms: supersede, deleteByIds, scanCopies, deleteRows, remainingCopies, copiesReport }
713
726
  coreForgets.set(toolkit, api)
714
727
  return api
715
728
  }
@@ -739,7 +752,7 @@ async function storeFingerprint(toolkit, entry, spaceContext, scoped) {
739
752
  await callRecords(toolkit, "forgotten.put", { text: String(entry.text).slice(0, 4_000), kind: entry.kind }, spaceContext, scoped)
740
753
  return entry.kept > 0
741
754
  ? "Recall won't show these copies. To delete them, ask your agent; to undo this forget, use Memory's console (Memories › Forgotten)."
742
- : "Recall won't show a copy of it written later. To undo this forget, use Memory's console (Memories › Forgotten)."
755
+ : "Recall withholds later copies that repeat its specific words or numbers; a reworded mention, or the fact remembered again, can still show. To undo this forget, use Memory's console (Memories › Forgotten)."
743
756
  } catch (error) {
744
757
  if (error?.code === "fingerprint_cap") return `Copies of the forgotten text can't be withheld from recall: ${errorMessage(error)} Lift old fingerprints in Memory's console (Memories › Forgotten).`
745
758
  if (error?.code === "invalid_fingerprint") return "The forgotten text has nothing a copy can be matched by, so recall cannot withhold its copies; a later mem_recall can show them until they are deleted."
@@ -782,6 +795,38 @@ function idList(value) {
782
795
  return []
783
796
  }
784
797
 
798
+ /** One line of a record's text for an ask: its fact (before "Why:"), redacted and cut. */
799
+ function askExcerpt(value) {
800
+ const textOf = typeof value === "string" ? value : String(value?.body ?? "").split(/\n\s*\nWhy:/)[0].trim() || String(value?.title ?? value?.path ?? "")
801
+ return oneLine(redactSecrets(textOf), ASK_EXCERPT_CHARS)
802
+ }
803
+
804
+ /**
805
+ * What an ask shows of the items it covers: the count, each item's id with an
806
+ * excerpt of its text (so the person approves what they can read, not a list
807
+ * of rec_ ids), and one summary line.
808
+ *
809
+ * @param {string} verb
810
+ * @param {Array<{id: string, text?: string, layer?: string}>} entries
811
+ */
812
+ function askItems(verb, entries) {
813
+ const items = entries.slice(0, ASK_ITEMS).map((entry) => ({ id: entry.id, ...(entry.layer ? { layer: entry.layer } : {}), excerpt: entry.text ? askExcerpt(entry.text) : "(text not available)" }))
814
+ const quoted = []
815
+ let length = 0
816
+ for (const item of items) {
817
+ const piece = `“${item.excerpt}”`
818
+ if (length + piece.length > 600) break
819
+ quoted.push(piece)
820
+ length += piece.length + 2
821
+ }
822
+ const rest = entries.length - quoted.length
823
+ return {
824
+ count: entries.length,
825
+ items,
826
+ summary: `${verb} ${entries.length} item${entries.length === 1 ? "" : "s"}: ${quoted.join("; ")}${rest > 0 ? `; and ${rest} more` : ""}`,
827
+ }
828
+ }
829
+
785
830
  /** Lower-case words only, for an exact-duplicate check. */
786
831
  function normal(text) {
787
832
  return String(text ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()
@@ -793,61 +838,61 @@ function normal(text) {
793
838
  * stored verbatim with its type, answers its `rec_` id at once, and recall
794
839
  * finds it at once. Nothing is written to the core.
795
840
  *
796
- * Every curation refusal runs before any request. A team write asks
797
- * `memory.remember`. A records write is never queued: an answer without an id
798
- * would be a promise the tool cannot keep, so a failed write says so.
841
+ * Every curation refusal runs before any request. A remember writes only the
842
+ * person's personal space (FIX-0911): it is the agent's own proactive write,
843
+ * which the owner allows freely in personal memory and never in a shared
844
+ * space. A `visibility` or `space` that names a shared space is not obeyed;
845
+ * the answer says so, and that team memory is a mem_share copy only when the
846
+ * person asked for it. It offers no ready-made call: an agent that chose team
847
+ * on its own must not be led into the copy (the same H3). So no remember, asked
848
+ * for or not, lands in a shared space. A records write is never queued: an
849
+ * answer without an id would be a promise the tool cannot keep, so a failed
850
+ * write says so.
799
851
  *
800
852
  * @param {any} editor
801
853
  * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
802
854
  */
803
855
  export function registerRemember(editor, toolkit) {
804
- const { text, fail, log, scope, scopeFor, resolveWriteSpace, assertTeamWrite, displayScope, taskFor } = toolkit
805
- // The pre-0.9 promote, offered for the deprecated `promote` alias's legacy
806
- // path (src/tools/index.js captures it, never registers it twice): it
807
- // revokes a 0.8 share exactly as before, local mode included.
808
- registerPromote(editor, toolkit)
809
-
856
+ const { text, fail, log, scope, scopeFor, resolvePrivateSpace, displayScope, taskFor } = toolkit
810
857
  editor.add({
811
858
  name: "remember",
812
859
  description:
813
- "Save one durable memory: a preference, constraint, decision, fact or procedure. Call it in the same turn the thing is stated or settled, without asking, then say what you saved in one line. Store what exists only because this conversation worked it out, with how it is known (why); capture already keeps the conversation, so this is curation. The content is stored verbatim with its kind. The answer gives the memory's id (rec_…) at once, and mem_recall finds it at once; correct, retire or forget it later with mem_revise and that id. When something known has changed, pass supersedes with the old memory's id: a rec_ id is kept as history, marked superseded by the new one; an older atom id (m_…) is deleted. Duplicate checking is best effort. stated_by is person only when the person said or confirmed it. Never store things to do (mem_commitments), where a project stands (its page's Status section, mem_page), secrets, file contents, tool output or restatements of the code. A status-shaped write ('Status: …', 'half done', 'is in progress', 'next step: …'), an instruction, an email address or an absolute local path is refused, and nothing is written. Private (the default) writes your personal space and never asks; team needs editor access and permission policy. With heldTeamWrites it is held in the Inbox; otherwise the host's permission settings decide, and may prompt or allow silently.",
860
+ "Save one durable memory: a preference, constraint, decision, fact or procedure. Call it in the same turn the thing is stated or settled. Store what this conversation worked out, with how it is known (why); capture already keeps the conversation. The answer gives the memory's id (rec_…) at once, and mem_recall finds it at once; change it later with mem_revise. Never store things to do (mem_commitments), project status or restatements of the code. A status-shaped write, an instruction, an email address or an absolute local path is refused, and nothing is written. It writes only the person's personal space and never asks; team memory is mem_share copy, only when the person asks.",
814
861
  input: {
815
862
  type: "object",
816
863
  properties: {
817
864
  content: {
818
865
  type: "string",
819
866
  description:
820
- 'Required: the thing to remember, stated plainly, as it should come back. Example: {"content": "Log timestamps are UTC", "kind": "decision", "why": "One clock across every log; agreed with [[people/ama]]"}',
867
+ "Required: the thing to remember, stated plainly, as it should come back",
821
868
  },
822
869
  kind: {
823
870
  type: "string",
824
871
  enum: [...KINDS],
825
872
  description:
826
- "Required: 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 why), decision for a choice and its reason, fact for a verified non-obvious truth, procedure for steps that worked (five at most). recall filters on the same names",
873
+ "Required: preference (how the person likes things done), constraint (a standing rule or a lesson), decision (a choice and its reason; a decisions/ page only for a long record), fact (a verified non-obvious truth), procedure (steps that worked, five at most)",
827
874
  },
828
875
  why: {
829
876
  type: "string",
830
- description: 'How it is known and 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. Stored after the content as "Why: …"; [[people/ama]] links a page',
877
+ description: "How it is known, with the source and date (\"agreed in the launch review, 2026-11-05\"); for a lesson, the incident",
831
878
  },
832
879
  links: {
833
880
  type: "array",
834
881
  items: { type: "string" },
835
- description: `Page paths (people/ama, projects/harbour) or record ids this memory is about, at most ${MAX_LINKS}; [[path]] in the content or why links too`,
882
+ description: `Page paths or record ids it is about, at most ${MAX_LINKS}; [[path]] in the text links too`,
836
883
  },
837
884
  supersedes: {
838
885
  type: "array",
839
886
  items: { type: "string" },
840
- description: `Ids this memory replaces, at most ${MAX_SUPERSEDES}: rec_… ids (kept, marked superseded, shown only with recall status "all") or older atom ids (m_…, deleted). A turn id (msg-…) is refused: forget it with mem_revise. Example: {"content": "Staging listens on 8788", "kind": "fact", "supersedes": ["rec_..."]}`,
887
+ description: `Ids it replaces, at most ${MAX_SUPERSEDES} (rec_… or m_…): each old value is kept as superseded history`,
841
888
  },
842
889
  stated_by: {
843
890
  type: "string",
844
891
  enum: ["person", "agent"],
845
- description:
846
- "person when the person said or confirmed it in this conversation; agent (default) when you concluded it yourself. Never mark your own inference as the person's.",
892
+ description: "A claim: person is kept only when the person accepts the write in Memory's console",
847
893
  },
848
894
  task: TASK_INPUT,
849
- visibility: { type: "string", enum: ["private", "team"], description: "private (default) always writes your personal space; team shares with a selected or session-bound shared space, and asks" },
850
- space: { type: "string", description: "Space id to write to (control plane); defaults to your personal or session-bound shared space" },
895
+ visibility: { type: "string", enum: ["private"], description: "Always your personal space. For the team: mem_share copy, only when the person asks" },
851
896
  },
852
897
  required: ["content", "kind"],
853
898
  additionalProperties: false,
@@ -869,10 +914,15 @@ export function registerRemember(editor, toolkit) {
869
914
  // The why is stored with the fact, so it passes the same guard.
870
915
  const why = String(input?.why ?? "").trim()
871
916
  const whyRefusal = why ? writeRefusal(why) : ""
872
- if (whyRefusal) return text(`not stored (why): ${whyRefusal.replace(/^not stored: /, "")}`)
873
- // Who stated it: the routines' policy treats the person's own statement
874
- // differently from the agent's conclusion, so it is the caller's to say.
875
- const statedBy = input?.stated_by === "person" ? "person" : "agent"
917
+ if (whyRefusal) {
918
+ // A refusal that opens "Nothing was stored:" keeps its opening, so a relay passes the gate's answer check.
919
+ if (whyRefusal.startsWith("Nothing was stored: ")) return text(whyRefusal.replace(/^Nothing was stored: /, "Nothing was stored (why): "))
920
+ return text(`not stored (why): ${whyRefusal.replace(/^not stored: /, "")}`)
921
+ }
922
+ // Who stated it is the host's to decide, not the caller's (FABLE tools 1
923
+ // and 6): the argument is a claim, kept for compatibility, and stays
924
+ // "person" only in a held write the person accepts (hostProvenance).
925
+ const claimed = input?.stated_by === "person" ? "person" : "agent"
876
926
  const links = idList(input?.links)
877
927
  if (links.length > MAX_LINKS) return text(`not stored: links takes at most ${MAX_LINKS} paths or ids.`)
878
928
  const badLinks = links.filter((link) => !PAGE_PATH.test(link) && !RECORD_ID.test(link))
@@ -894,8 +944,10 @@ export function registerRemember(editor, toolkit) {
894
944
  const task = taskFor(input, context)
895
945
  if (task.invalid) return text(`not stored: ${task.invalid}`)
896
946
 
897
- const visibility = normalizeVisibility(input?.visibility, "private")
898
- const resolved = await resolveWriteSpace(input, context, visibility)
947
+ // Personal, whatever the call names (FIX-0911). A call that asked for a
948
+ // shared target is told where the memory went and how the team gets it.
949
+ const askedShared = normalizeVisibility(input?.visibility, "private") !== "private" || String(input?.space ?? "").trim() !== ""
950
+ const resolved = await resolvePrivateSpace({}, context)
899
951
  if (resolved.invalid) return text(resolved.invalid)
900
952
  if (resolved.error) return fail(resolved.error)
901
953
  const spaceContext = resolved.context
@@ -920,42 +972,32 @@ export function registerRemember(editor, toolkit) {
920
972
  type: kind,
921
973
  title: titleFrom(content),
922
974
  body,
923
- stated_by: statedBy,
975
+ // A held write carries the claim: the person reads and approves it in the Inbox.
976
+ stated_by: claimed,
924
977
  ...(links.length > 0 ? { fields: { links } } : {}),
925
978
  ...(recordIDs.length > 0 ? { supersedes: recordIDs } : {}),
926
979
  source: context?.sessionID ? { session: String(context.sessionID) } : {},
927
980
  ...(task.key ? { task: task.key } : {}),
928
981
  }
929
982
 
930
- if (visibility === "team" && toolkit.config.heldTeamWrites) {
931
- if (atomIDs.length) return text("not held: legacy atom supersession cannot be applied transactionally. Nothing was stored.")
932
- try {
933
- return text(await holdTeamWrite(toolkit, context, spaceContext, [record]))
934
- } catch (error) {
935
- if (error?.outcomeUnknown) return fail(errorMessage(error))
936
- return fail(`held write was not confirmed: ${errorMessage(error)}`)
937
- }
938
- }
939
- if (visibility === "team") {
940
- try {
941
- await assertTeamWrite(context, "memory.remember", [spaceContext?.space_id ?? "team", ...supersedes], {
942
- kind,
943
- visibility,
944
- ...(spaceContext?.space_name ? { space_name: oneLine(spaceContext.space_name, 200) } : {}),
945
- ...(spaceContext?.space_id ? { space_id: spaceContext.space_id } : {}),
946
- excerpt: oneLine(redactSecrets(content), 400),
947
- ...(supersedes.length > 0 ? { supersedes } : {}),
948
- })
949
- } catch (error) {
950
- return text(`remembering to the team denied: ${errorMessage(error)}. Nothing was stored.`)
951
- }
952
- }
983
+ // A personal write has no gate and no ask, so nothing the person did
984
+ // makes it theirs: stated_by is agent (hostProvenance, FABLE tools 1).
985
+ const statedBy = hostProvenance(claimed, { asked: false })
986
+ record.stated_by = statedBy
987
+
988
+ // An atom is replaced only once its text is kept as a record this one supersedes.
989
+ const { session_id: _session, task_id: _task, ...base } = scoped
990
+ const core = atomIDs.length > 0 ? createCoreForget(toolkit) : null
991
+ const keep = core ? await core.keepAtoms({ ids: atomIDs, spaceContext, scoped, base, session: context?.sessionID }) : null
992
+ const keptIDs = keep ? [...keep.kept.values()].map((entry) => entry.record) : []
993
+ if (keptIDs.length > 0) record.supersedes = [...recordIDs, ...keptIDs]
953
994
 
954
995
  let stored
955
996
  try {
956
997
  stored = (await callRecords(toolkit, "records.put", { record }, spaceContext, scoped))?.record
957
998
  } catch (error) {
958
999
  log.warn("remember failed", error)
1000
+ if (!error?.outcomeUnknown) await core?.dropKept(keep, spaceContext, scoped)
959
1001
  if (error?.outcomeUnknown) return fail(errorMessage(error))
960
1002
  const refused = notWritten(error, "stored")
961
1003
  if (refused) return text(refused)
@@ -968,20 +1010,22 @@ export function registerRemember(editor, toolkit) {
968
1010
  const id = String(stored?.id ?? "")
969
1011
  if (!RECORD_ID.test(id)) return fail("the records service answered without a record id; the memory may not be stored. Check with mem_recall before writing it again.")
970
1012
  noteRecordSpace(toolkit, id, spaceContext)
971
- log.info("remember", { kind, visibility, scope: label, task: Boolean(task.key), supersedes: supersedes.length })
1013
+ log.info("remember", { kind, scope: label, task: Boolean(task.key), supersedes: supersedes.length, askedShared })
972
1014
 
973
1015
  const lines = [
974
1016
  `stored ${id} (memory/${kind}, stated by ${statedBy}) in ${label} ${task.key ? `for task ${task.key}` : "for the whole space"}. mem_recall finds it now.`,
975
1017
  ]
1018
+ if (askedShared) {
1019
+ lines.push(
1020
+ "It is in the person's personal memory: mem_remember writes nowhere else, and this is not in a shared space. Team memory only when the person asked for it, and then with mem_share copy (with space, when the person named one).",
1021
+ )
1022
+ }
1023
+ if (claimed !== statedBy) lines.push("Recorded as stated by agent: only a write the person accepts in Memory's console is recorded as theirs.")
976
1024
  if (recordIDs.length > 0) {
977
- const marked = (stored?.supersedes ?? recordIDs).map((value) => oneLine(value, 40))
1025
+ const marked = (stored?.supersedes ?? recordIDs).filter((value) => !keptIDs.includes(value)).map((value) => oneLine(value, 40))
978
1026
  lines.push(`Superseded ${marked.join(", ")}: kept as history, marked superseded by ${id}; mem_recall shows ${marked.length === 1 ? "it" : "them"} only with status "all", and mem_revise history shows the lineage.`)
979
1027
  }
980
- if (atomIDs.length > 0) {
981
- const unscoped = spaceContext ? scopeFor(spaceContext, { agent: context?.agent }) : scope({ agent: context?.agent })
982
- const { session_id: _session, task_id: _task, ...base } = unscoped
983
- lines.push(await createCoreForget(toolkit).supersedeAtoms(atomIDs, spaceContext, base))
984
- }
1028
+ if (core) lines.push(await core.supersedeAtoms(keep, id, spaceContext, base))
985
1029
  lines.push(`To change it later: mem_revise {"action": "correct", "id": "${id}", "content": "…"}; to drop it: {"action": "retire", "id": "${id}"}.`)
986
1030
  return text(lines.join("\n"))
987
1031
  },
@@ -993,8 +1037,9 @@ export function registerRemember(editor, toolkit) {
993
1037
  * new record that supersedes the old one, which is kept; `confirm`, `retire`
994
1038
  * and `restore` change its status; `history` shows its versions and lineage;
995
1039
  * `forget` deletes it for good and always asks `memory.forget`. An `m_` or
996
- * `msg-` id is forgotten in the core as mem_forget does, and `correct` on an
997
- * `m_` id stores the correction as a record and deletes the atom.
1040
+ * `msg-` id is forgotten in the core as forget always has, and `correct` on an
1041
+ * `m_` id keeps the atom's text as a superseded record, stores the correction
1042
+ * as a record, then removes the atom (keepAtoms).
998
1043
  *
999
1044
  * A change to a record in a shared space asks `memory.revise`.
1000
1045
  *
@@ -1002,12 +1047,7 @@ export function registerRemember(editor, toolkit) {
1002
1047
  * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
1003
1048
  */
1004
1049
  export function registerRevise(editor, toolkit) {
1005
- const { text, fail, log, scope, scopeFor, resolveReadSpace, assertTeamWrite, displayScope, taskFor, forgetLocations } = toolkit
1006
- // The pre-0.9 forget, offered for the deprecated `forget` alias's legacy
1007
- // path (src/tools/index.js captures it, never registers it twice): it keeps
1008
- // the persona and scenario phrase erase (match), which revise does not take.
1009
- registerForget(editor, toolkit)
1010
-
1050
+ const { text, fail, log, scope, scopeFor, resolveReadSpace, assertTeamWrite, gateWrite, displayScope, taskFor, forgetLocations } = toolkit
1011
1051
  /**
1012
1052
  * The space a revise acts in: where this process last saw the id (recall,
1013
1053
  * remember, page), else the session's (personal, or a bound shared one).
@@ -1044,36 +1084,52 @@ export function registerRevise(editor, toolkit) {
1044
1084
  editor.add({
1045
1085
  name: "revise",
1046
1086
  description:
1047
- 'Change one memory by its id (rec_… from mem_remember or mem_recall). Call it when the person says a memory changed or is wrong, or you find it so. correct writes a successor; confirm, retire, restore and history manage its lifecycle. When the person explicitly asks to forget, use forget, even if they call it obsolete; do not substitute retire. forget deletes the named record and history, checks a bounded subset for candidates, deletes atoms that state only that fact and previews turns that hold it. It cannot establish complete erasure. When the person asked you to forget it, the request is their consent. When you propose a deletion yourself (including a whole turn), ask the person first. Show each whole turn and obtain separate consent before deleting it. Shared revisions follow the host permission policy, which may prompt or allow silently. Never put status, instructions, email addresses or local paths in content: they are refused before anything changes.',
1087
+ "Change memories by their ids (rec_… from mem_remember or mem_recall). Call it when the person says a memory changed or is wrong, or you find it so. correct writes a successor; confirm, retire, restore and history manage its lifecycle. To clean up many, list them with mem_recall's filter, retire them (restore undoes it), and forget only what the person asks to forget. forget deletes the record and its history and checks a bounded subset for copies; it cannot establish complete erasure. When the person asked you to forget it, the request is their consent. When you propose a deletion yourself (including a whole turn), ask the person first, and obtain separate consent before deleting it. Shared revisions follow the host permission policy, which may prompt or allow silently. Never put status, instructions, email addresses or local paths in content.",
1048
1088
  input: {
1049
1089
  type: "object",
1050
1090
  properties: {
1051
1091
  action: {
1052
1092
  type: "string",
1053
1093
  enum: [...REVISE_ACTIONS],
1054
- description: 'Required: correct, confirm, retire, restore, forget, or history. Example: {"action": "correct", "id": "rec_...", "content": "Staging listens on 8788", "reason": "moved in the infra review"}',
1094
+ description: "Required. Correct or change a shared space's record only when the person asks. When the person explicitly asks to forget, use forget, even if they call it obsolete; do not substitute retire. Example: {\"action\": \"correct\", \"id\": \"rec_...\", \"content\": \"Staging listens on 8788\", \"reason\": \"moved in the infra review\"}",
1055
1095
  },
1056
- id: { type: "string", description: "Required: the record id (rec_…); forget also takes the core's m_… and msg-… ids" },
1057
- content: { type: "string", description: "correct only: the corrected memory, whole, as it should come back" },
1058
- reason: { type: "string", description: "Why it changed; kept in the record's history" },
1096
+ id: { type: "string", description: "A rec_… id; forget also takes m_… and msg-… ids. Pass id or ids" },
1097
+ ids: {
1098
+ type: "array",
1099
+ items: { type: "string" },
1100
+ maxItems: MAX_REVISE_IDS,
1101
+ description: `confirm, retire, restore or forget: up to ${MAX_REVISE_IDS} ids from one space, asked once`,
1102
+ },
1103
+ content: { type: "string", description: "correct: the whole corrected memory" },
1104
+ reason: { type: "string", description: "Why; kept in its history" },
1059
1105
  },
1060
- required: ["action", "id"],
1106
+ required: ["action"],
1061
1107
  additionalProperties: false,
1062
1108
  },
1063
1109
  options: { namespace: "mem" },
1064
1110
  execute: async (input, context) => {
1065
1111
  const verb = String(input?.action ?? "")
1066
1112
  if (!REVISE_ACTIONS.includes(verb)) return text(`action is required: one of ${REVISE_ACTIONS.join(", ")}. Example: {"action": "history", "id": "rec_..."}`)
1067
- const ids = idList(input?.id)
1068
- if (ids.length === 0) return text(`id is required for ${verb}: the rec_… id mem_remember or mem_recall gave.`)
1113
+ const many = input?.ids !== undefined && input?.ids !== null
1114
+ if (Array.isArray(input?.id)) return text(`id takes one id; pass several as ids: {"action": "${verb}", "ids": ["rec_…", "rec_…"]}. Nothing changed.`)
1115
+ if (many && !Array.isArray(input.ids)) return text('ids must be a list: {"ids": ["rec_…", "rec_…"]}. Nothing changed.')
1116
+ if (many && String(input?.id ?? "").trim()) return text("pass id for one record or ids for several, not both. Nothing changed.")
1117
+ const ids = many ? idList(input.ids) : idList(input?.id)
1118
+ if (ids.length === 0) return text(`id is required for ${verb}: the rec_… id mem_remember or mem_recall gave${BATCH_VERBS.includes(verb) ? ", or ids for several" : ""}.`)
1119
+ if (many && !BATCH_VERBS.includes(verb)) return text(`${verb} takes one id; ids is for ${BATCH_VERBS.join(", ")}. Nothing changed.`)
1120
+ if (ids.length > MAX_REVISE_IDS) return text(`ids takes at most ${MAX_REVISE_IDS} ids per call; you sent ${ids.length}. Send the first ${MAX_REVISE_IDS}, then the rest. Nothing changed.`)
1069
1121
  const id = ids[0]
1070
- const fingerprint = verb === "restore" && FORGOTTEN_ID.test(id)
1122
+ const fingerprint = verb === "restore" && ids.some((value) => FORGOTTEN_ID.test(value))
1071
1123
  // A record id, a turn id, or else the core's atom id (m_… on the
1072
1124
  // deployed core; other cores mint other shapes), as supersedes takes it.
1073
1125
  const unknown = ids.filter((value) => !RECORD_ID.test(value) && !CORE_ID.test(value))
1074
1126
  if (unknown.length > 0) {
1075
1127
  return text(`${unknown.map((value) => JSON.stringify(oneLine(value, 80))).join(", ")} ${unknown.length === 1 ? "is not a memory id" : "are not memory ids"}: pass rec_… ids from mem_remember or mem_recall (forget also takes m_… and msg-…). Nothing changed.`)
1076
1128
  }
1129
+ if (many && verb !== "forget" && !fingerprint) {
1130
+ const core = ids.filter((value) => !RECORD_ID.test(value))
1131
+ if (core.length > 0) return text(`${verb} takes record ids (rec_…); ${core.map((value) => oneLine(value, 80)).join(", ")} ${core.length === 1 ? "is" : "are"} in the core. Forget ${core.length === 1 ? "it" : "them"} instead. Nothing changed.`)
1132
+ }
1077
1133
  if (verb !== "forget" && !fingerprint && !RECORD_ID.test(id) && !(verb === "correct" && !TURN_ID.test(id))) {
1078
1134
  return text(`${verb} takes a record id (rec_…); ${oneLine(id, 80)} is in the core${verb === "correct" ? " as a turn" : ""}. ${TURN_ID.test(id) ? "Forget it, or remember the corrected text." : "Correct it to store the correction as a record, or forget it."} Nothing changed.`)
1079
1135
  }
@@ -1096,7 +1152,10 @@ export function registerRevise(editor, toolkit) {
1096
1152
  const kind = "fact"
1097
1153
  const task = taskFor({}, context)
1098
1154
 
1099
- const resolved = await spaceFor(id, context)
1155
+ // Every id of one call must be in one space: where this process saw each.
1156
+ const seenIn = [...new Set(ids.map((value) => recordSpace(toolkit, value)).filter(Boolean))]
1157
+ if (seenIn.length > 1) return text(`these ids are in ${seenIn.length} spaces (${seenIn.map((value) => oneLine(value, 80)).join(", ")}); send one call per space. Nothing changed.`)
1158
+ const resolved = await spaceFor(ids.find((value) => recordSpace(toolkit, value)) ?? id, context)
1100
1159
  if (resolved.invalid) return text(resolved.invalid)
1101
1160
  if (resolved.error) return fail(resolved.error)
1102
1161
  const spaceContext = resolved.context
@@ -1112,26 +1171,44 @@ export function registerRevise(editor, toolkit) {
1112
1171
  const data = await callRecords(toolkit, "records.history", { id }, spaceContext, scoped)
1113
1172
  return text(renderHistory(id, data))
1114
1173
  }
1174
+ // FIX-0911: a page in a shared space changes only through mem_page,
1175
+ // where an agent only adds lines; it is never revised here.
1176
+ const recordIDs = ids.filter((value) => RECORD_ID.test(value))
1177
+ if (shared && recordIDs.length > 0) {
1178
+ const found = await callRecords(toolkit, "records.get", { ids: recordIDs }, spaceContext, scoped)
1179
+ const pages = (found?.records ?? []).filter((record) => record?.kind === "page")
1180
+ if (pages.length > 0) {
1181
+ return text(`${pages.map((record) => `${oneLine(record.id, 40)} (${oneLine(record.path ?? "", 80)})`).join(", ")} ${pages.length === 1 ? "is a page" : "are pages"} in a shared space: pages change through mem_page, where an agent only adds lines. The person retires, restores, forgets or rewrites a team page in Memory's console. Nothing changed.`)
1182
+ }
1183
+ }
1115
1184
  if (verb === "forget") return text(await forget({ ids, context, spaceContext, scoped, label }))
1116
1185
  if (fingerprint) return text(restoreCopies())
1186
+ if (many) return text(await reviseMany({ ids, verb, reason, context, spaceContext, scoped, label, shared }))
1187
+
1188
+ const gate = await gateWrite(context, {
1189
+ action: "memory.revise",
1190
+ spaceContext,
1191
+ shared,
1192
+ resources: [id],
1193
+ metadata: { revise: verb, ...(content ? { excerpt: redactSecrets(oneLine(content, 400)) } : {}), ...(reason ? { reason: oneLine(reason, 200) } : {}) },
1194
+ })
1195
+ if (gate.denied) return text(`revising team memory denied: ${gate.denied}. Nothing changed.`)
1117
1196
 
1118
- if (shared) {
1197
+ if (verb === "correct" && !RECORD_ID.test(id)) {
1198
+ // The atom's text is kept as a record the correction supersedes, as remember's supersedes does.
1199
+ const core = createCoreForget(toolkit)
1200
+ const { session_id: _session, task_id: _task, ...base } = scoped
1201
+ const keep = await core.keepAtoms({ ids: [id], spaceContext, scoped, base, session: context?.sessionID })
1202
+ const keptIDs = [...keep.kept.values()].map((entry) => entry.record)
1203
+ const record = { kind: "memory", type: kind, title: titleFrom(content), body: content, stated_by: "agent", ...(keptIDs.length > 0 ? { supersedes: keptIDs } : {}), source: context?.sessionID ? { session: String(context.sessionID) } : {}, ...(task.key ? { task: task.key } : {}) }
1204
+ let stored
1119
1205
  try {
1120
- await assertTeamWrite(context, "memory.revise", [spaceContext.space_id, id], {
1121
- revise: verb,
1122
- ...(content ? { excerpt: redactSecrets(oneLine(content, 400)) } : {}),
1123
- ...(reason ? { reason: oneLine(reason, 200) } : {}),
1124
- })
1206
+ stored = (await callRecords(toolkit, "records.put", { record }, spaceContext, scoped))?.record
1125
1207
  } catch (error) {
1126
- return text(`revising team memory denied: ${errorMessage(error)}. Nothing changed.`)
1208
+ if (!error?.outcomeUnknown) await core.dropKept(keep, spaceContext, scoped)
1209
+ throw error
1127
1210
  }
1128
- }
1129
-
1130
- if (verb === "correct" && !RECORD_ID.test(id)) {
1131
- const record = { kind: "memory", type: kind, title: titleFrom(content), body: content, stated_by: "agent", source: context?.sessionID ? { session: String(context.sessionID) } : {}, ...(task.key ? { task: task.key } : {}) }
1132
- const stored = (await callRecords(toolkit, "records.put", { record }, spaceContext, scoped))?.record
1133
- const { session_id: _session, task_id: _task, ...base } = scoped
1134
- const removed = await createCoreForget(toolkit).supersedeAtoms([id], spaceContext, base)
1211
+ const removed = await core.supersedeAtoms(keep, stored?.id, spaceContext, base)
1135
1212
  return text(`corrected atom ${oneLine(id, 80)} as ${stored?.id} (memory/${kind}) in ${label}; mem_recall finds it now.\n${removed}`)
1136
1213
  }
1137
1214
 
@@ -1146,7 +1223,7 @@ export function registerRevise(editor, toolkit) {
1146
1223
  const scan = await createCoreForget(toolkit).scanCopies({ texts: [factOf(old)], spaceContext, base })
1147
1224
  const atoms = scan.copies.filter((row) => row.layer === "l1")
1148
1225
  correctionWarning = atoms.length
1149
- ? `Possible stale/conflicting atoms remain and may appear in recall (heuristic candidates, not verified lineage): ${atoms.map((row) => `${oneLine(row.id, 80)}: ${JSON.stringify(oneLine(row.content, 300))}`).join("; ")}.`
1226
+ ? `Possible stale/conflicting atoms remain and may appear in recall (heuristic candidates, not verified lineage): ${atoms.map((row) => `${oneLine(row.id, 80)}: ${JSON.stringify(oneLine(row.content, 300))}`).join("; ")}. Leave them unless the person asks: removing one is a forget, so ask first.`
1150
1227
  : "Old atoms and turns may still appear in recall; provenance and the bounded scan cannot rule out stale conflicts."
1151
1228
  if (scan.windows.some((window) => !window.listing.complete)) correctionWarning += " The core scan was incomplete."
1152
1229
  } catch (error) {
@@ -1187,6 +1264,81 @@ export function registerRevise(editor, toolkit) {
1187
1264
  return "not restored: only the person can undo a forget, in a browser: Memory's console (Memories › Forgotten). Nothing changed, and recall keeps withholding the copies."
1188
1265
  }
1189
1266
 
1267
+ /** How many forgotten-copy fingerprints the caller keeps in this space, or null when they cannot be read. */
1268
+ async function fingerprintsKept(spaceContext, scoped) {
1269
+ try {
1270
+ const data = await callRecords(toolkit, "forgotten.list", {}, spaceContext, scoped)
1271
+ return Array.isArray(data?.fingerprints) ? data.fingerprints.length : null
1272
+ } catch {
1273
+ return null
1274
+ }
1275
+ }
1276
+
1277
+ /** A records service before 0.9.7 refuses a batch revise ({ids}) as a revise without an id. */
1278
+ function noBatch(error) {
1279
+ return error instanceof RecordsError && (error.code === "invalid_id" || error.code === "invalid_action") && !error.outcomeUnknown
1280
+ }
1281
+
1282
+ /** The records of `ids` this caller can read, by id; an empty map when the read fails. */
1283
+ async function readRecords(ids, spaceContext, scoped) {
1284
+ try {
1285
+ const data = await callRecords(toolkit, "records.get", { ids: ids.filter((value) => RECORD_ID.test(value)) }, spaceContext, scoped)
1286
+ return new Map((data?.records ?? []).map((record) => [record.id, record]))
1287
+ } catch (error) {
1288
+ log.debug("revise: records unread", { error: errorMessage(error) })
1289
+ return new Map()
1290
+ }
1291
+ }
1292
+
1293
+ /** One line per id: what happened to it, or why it did not. */
1294
+ function outcomeLines(results, done, undone = "not changed") {
1295
+ return results.map((item) => item.ok
1296
+ ? `- ${oneLine(item.id, 40)}: ${done}`
1297
+ : `- ${oneLine(item.id, 40)}: ${undone} (${oneLine(item.error?.code ?? "error", 40)}): ${oneLine(item.error?.message ?? "", 200)}`)
1298
+ }
1299
+
1300
+ /**
1301
+ * confirm, retire or restore for several ids (one space): one ask in a
1302
+ * shared space, naming each record with an excerpt; one batch request
1303
+ * (records.revise {ids}), or one request per id on a service before 0.9.7;
1304
+ * one line per id.
1305
+ */
1306
+ async function reviseMany({ ids, verb, reason, context, spaceContext, scoped, label, shared }) {
1307
+ const byId = await readRecords(ids, spaceContext, scoped)
1308
+ const gate = await gateWrite(context, {
1309
+ action: "memory.revise",
1310
+ spaceContext,
1311
+ shared,
1312
+ resources: ids,
1313
+ metadata: { revise: verb, ...askItems(verb, ids.map((value) => ({ id: value, text: byId.get(value) }))), ...(reason ? { reason: oneLine(reason, 200) } : {}) },
1314
+ })
1315
+ if (gate.denied) return `revising team memory denied: ${gate.denied}. Nothing changed.`
1316
+ let results
1317
+ try {
1318
+ results = (await callRecords(toolkit, "records.revise", { ids, action: verb, ...(reason ? { reason } : {}) }, spaceContext, scoped))?.results ?? []
1319
+ } catch (error) {
1320
+ if (!noBatch(error)) throw error
1321
+ results = []
1322
+ for (const one of ids) {
1323
+ try {
1324
+ const record = (await callRecords(toolkit, "records.revise", { id: one, action: verb, ...(reason ? { reason } : {}) }, spaceContext, scoped))?.record ?? {}
1325
+ results.push({ id: one, ok: true, status: record.status, version: record.version })
1326
+ } catch (failure) {
1327
+ if (failure?.outcomeUnknown) throw failure
1328
+ results.push({ id: one, ok: false, error: { code: failure?.code ?? "error", message: errorMessage(failure) } })
1329
+ }
1330
+ }
1331
+ }
1332
+ const done = results.filter((item) => item.ok)
1333
+ const past = { confirm: "confirmed", retire: "retired", restore: "restored" }[verb]
1334
+ log.info("revise batch", { revise: verb, scope: label, ids: ids.length, done: done.length })
1335
+ const lines = [`${past} ${done.length} of ${results.length} in ${label}:`, ...outcomeLines(results, past)]
1336
+ if (verb === "retire" && done.length > 0) lines.push(`Retired records leave mem_recall (status "all" still shows them). To bring them back: mem_revise {"action": "restore", "ids": [the ids retired above]}.`)
1337
+ if (verb === "restore" && done.length > 0) lines.push("Restored records are current again and mem_recall shows them.")
1338
+ if (done.length < results.length) lines.push("The others were not changed; each line says why.")
1339
+ return lines.join("\n")
1340
+ }
1341
+
1190
1342
  /** The fact a memory record states: its body before "Why:", else its title. */
1191
1343
  function factOf(record) {
1192
1344
  const body = String(record?.body ?? "").split(/\n\s*\nWhy:/)[0].trim()
@@ -1195,7 +1347,7 @@ export function registerRevise(editor, toolkit) {
1195
1347
 
1196
1348
  /**
1197
1349
  * Forget (EVAL's gate, contract §4.1): records by id with `records.delete`,
1198
- * and core ids as mem_forget deletes them. Capture keeps the conversation a
1350
+ * and core ids in the core. Capture keeps the conversation a
1199
1351
  * fact was said in and the core extracts atoms from it, so deleting a record
1200
1352
  * alone leaves the fact recallable: the core's copies of each record's fact
1201
1353
  * (atoms and turns that hold it, docs/design/adr-forget-copies.md) are found
@@ -1223,18 +1375,50 @@ export function registerRevise(editor, toolkit) {
1223
1375
  const facts = records.map(factOf).filter(Boolean)
1224
1376
  const scan = facts.length > 0 ? await core.scanCopies({ texts: facts, spaceContext, base, exclude: new Set(coreIDs) }) : { copies: [], windows: [], forgotten: [] }
1225
1377
  const copyIDs = scan.copies.map((row) => row.id)
1226
- const metadata = { space: spaceContext?.space_id ?? "local", visibility: spaceContext?.space_kind === "shared" ? "team" : "private", ids: ids.length, ...(copyIDs.length > 0 ? { copies: copyIDs.length } : {}) }
1378
+ // The fingerprint budget, read before anything changes: each forgotten
1379
+ // record adds one, and at the cap its copies are no longer withheld.
1380
+ const kept = records.length > 0 ? await fingerprintsKept(spaceContext, scoped) : null
1381
+ // A batch that does not fit is refused before anything is asked or deleted,
1382
+ // as the console refuses it: each forgotten record needs one fingerprint.
1383
+ if (kept !== null && records.length > 1 && records.length > FINGERPRINT_CAP - kept) {
1384
+ const room = Math.max(0, FINGERPRINT_CAP - kept)
1385
+ return `not forgotten: ${records.length} records need ${records.length} forgotten-copy fingerprints, but you keep ${kept} of ${FINGERPRINT_CAP} in this space, so ${room} fit. ${room > 0 ? `Forget ${room} or fewer at a time, or lift` : "Lift"} old fingerprints in Memory's console (Memories › Forgotten), or retire them instead. Nothing was deleted.`
1386
+ }
1387
+ const byId = new Map(records.map((record) => [record.id, record]))
1388
+ const entries = [
1389
+ ...ids.map((value) => ({ id: value, text: byId.get(value) ?? toolkit.locate?.(spaceContext, value)?.text })),
1390
+ ...scan.copies.map((row) => ({ id: row.id, layer: row.layer, text: row.content })),
1391
+ ]
1392
+ const metadata = {
1393
+ space: spaceContext?.space_id ?? "local",
1394
+ visibility: spaceContext?.space_kind === "shared" ? "team" : "private",
1395
+ ids: ids.length,
1396
+ ...(copyIDs.length > 0 ? { copies: copyIDs.length } : {}),
1397
+ ...askItems("forget", entries),
1398
+ ...(kept !== null ? { fingerprints_left: Math.max(0, FINGERPRINT_CAP - kept) } : {}),
1399
+ }
1227
1400
  const ask = (more = []) =>
1228
1401
  assertTeamWrite(context, "memory.forget", [...ids, ...copyIDs, ...more], { ...metadata, ...(more.length > 0 ? { remember_rows: more.length } : {}) })
1229
1402
 
1230
1403
  const parts = []
1231
1404
  let report = ""
1405
+ // The local purge (src/forget-purge.js), run once something was deleted:
1406
+ // a denied forget marks nothing.
1407
+ const purge = toolkit.runtime?.forgetPurge
1408
+ const purgeSpace = spaceContext?.space_id ?? scoped?.space_id ?? ""
1409
+ const purgeTexts = []
1410
+ let coreGone = 0
1232
1411
  if (coreIDs.length > 0) {
1233
- const deleted = await core.deleteByIds({ ids: coreIDs, wanted: ["l1", "l0"], spaceContext, base, explicitAgent: "", approve: (ownIDs) => ask(ownIDs), retryArgs: {} })
1412
+ const deleted = await core.deleteByIds({ ids: coreIDs, wanted: ["l1", "l0"], spaceContext, base, explicitAgent: "", approve: (ownIDs) => ask(ownIDs) })
1234
1413
  if (deleted.denied) return `forgetting denied: ${deleted.denied}. Nothing was deleted.`
1235
1414
  parts.push(`deleted ${deleted.total} core item(s) (${deleted.removed.l1} l1 atom(s), ${deleted.removed.l0} l0 turn(s)).`, ...deleted.lines)
1236
1415
  parts.push(...(await fingerprintForgottenAtoms(toolkit, deleted, spaceContext, scoped)))
1237
1416
  report = deleted.report
1417
+ coreGone = deleted.total || 0
1418
+ const deletedIDs = new Set(deleted.deletedIDs ?? [])
1419
+ // An atom states one fact: its sentences are purged. A whole turn is not
1420
+ // hashed: its every sentence would mask unrelated later text.
1421
+ for (const row of deleted.forgottenRows ?? []) if (row.layer === "l1" && row.content && (deletedIDs.size === 0 || deletedIDs.has(row.id))) purgeTexts.push(String(row.content))
1238
1422
  for (const row of deleted.forgottenRows ?? []) {
1239
1423
  if (!row.content) {
1240
1424
  parts.push(`Record copies of ${oneLine(row.id, 80)} were not searched: its text was unavailable.`)
@@ -1258,21 +1442,37 @@ export function registerRevise(editor, toolkit) {
1258
1442
  }
1259
1443
 
1260
1444
  let gone = []
1445
+ // Records the service refused to delete: still there by its answer, so the
1446
+ // read back does not report them as copies left behind.
1447
+ const refusedIDs = new Set()
1448
+ let refusedBlock = ""
1261
1449
  if (records.length > 0) {
1262
1450
  let data
1263
1451
  let deleteUnknown = false
1452
+ const recordList = records.map((record) => record.id)
1264
1453
  try {
1265
- data = await callRecords(toolkit, "records.delete", { ids: records.map((record) => record.id) }, spaceContext, scoped)
1454
+ // A batch forget authorises each id on its own (0.9.7); an older
1455
+ // service has only records.delete, which refuses the whole list when
1456
+ // one id is not the caller's to delete.
1457
+ try {
1458
+ data = await callRecords(toolkit, "records.revise", { ids: recordList, action: RECORDS_FORGET }, spaceContext, scoped)
1459
+ } catch (error) {
1460
+ if (!noBatch(error)) throw error
1461
+ data = await callRecords(toolkit, "records.delete", { ids: recordList }, spaceContext, scoped)
1462
+ }
1266
1463
  } catch (error) {
1267
1464
  data = {}
1268
1465
  deleteUnknown = error?.outcomeUnknown === true
1269
1466
  parts.push(`Record delete failed (${errorMessage(error)}); the record(s) remain unconfirmed. Any core deletions above already happened.`)
1270
1467
  }
1271
- gone = (data?.deleted ?? []).map(String)
1468
+ const refusedItems = Array.isArray(data?.results) ? data.results.filter((item) => !item.ok) : []
1469
+ for (const item of refusedItems) refusedIDs.add(String(item.id))
1470
+ gone = Array.isArray(data?.results) ? data.results.filter((item) => item.ok).map((item) => String(item.id)) : (data?.deleted ?? []).map(String)
1272
1471
  if (gone.length > 0) {
1273
1472
  parts.unshift(`forgot ${gone.join(", ")} in ${label}: deleted with ${gone.length === 1 ? "its" : "their"} history; ${Number(data?.links_removed) || 0} link(s) removed. Records that superseded ${gone.length === 1 ? "it" : "them"} stay.`)
1274
1473
  }
1275
- const undeleted = records.map((record) => record.id).filter((value) => !gone.includes(value))
1474
+ if (refusedItems.length > 0) refusedBlock = `Not deleted, each for its reason:\n${outcomeLines(refusedItems, "", "not deleted").join("\n")}`
1475
+ const undeleted = recordList.filter((value) => !gone.includes(value) && !refusedItems.some((item) => item.id === value))
1276
1476
  if (undeleted.length > 0 && !deleteUnknown) parts.push(`The records service did not delete ${undeleted.join(", ")}.`)
1277
1477
  }
1278
1478
  if (missing.length > 0) parts.push(`Not found, so not deleted: ${missing.join(", ")} (pass ids from mem_recall in this space).`)
@@ -1297,673 +1497,72 @@ export function registerRevise(editor, toolkit) {
1297
1497
  if (copies.deleted.length > 0) parts.push(`Also deleted ${copies.deleted.length} atom(s) in the core that state only this fact: ${list(copies.deleted)}.`)
1298
1498
  else if (scan.copies.length === 0) parts.push("No candidate copy of the fact was found in the rows actually scanned.")
1299
1499
  if (copies.kept.length > 0) parts.push(`Not deleted: ${copies.kept.map((row) => `${row.layer} ${oneLine(row.id, 80)} (${row.why})`).join("; ")}.`)
1300
- report = [report, core.copiesReport({ forgotten: scan.forgotten.length, copies: copies.kept.map((row) => ({ ...row, note: row.why })), windows: scan.windows, base, retryArgs: {}, unscannedAgents: scan.unscannedAgents })].filter(Boolean).join("\n")
1500
+ parts.push(...copies.notes)
1501
+ report = [report, core.copiesReport({ forgotten: scan.forgotten.length, copies: copies.kept.map((row) => ({ ...row, note: row.why })), windows: scan.windows, base, unscannedAgents: scan.unscannedAgents })].filter(Boolean).join("\n")
1301
1502
 
1302
1503
  // The kept copies stay in the core until the person consents, and the
1303
1504
  // forget's own reply may copy the fact again: a fingerprint makes every
1304
1505
  // later recall withhold all of them from this person.
1506
+ const printLines = []
1305
1507
  for (const record of goneRecords) {
1306
1508
  const fact = factOf(record)
1307
1509
  if (!fact) continue
1308
1510
  const kind = MEMORY_TYPES.includes(record.type) ? record.type : "fact"
1309
1511
  const features = [copyFeatures(fact)]
1310
- const kept = copies.kept.filter((row) => {
1512
+ const copiesKept = copies.kept.filter((row) => {
1311
1513
  const parts = rememberParts(row.content)
1312
1514
  return matchCopy(features, parts.kind === "wrapper" ? `${parts.body}\n${parts.reason}` : row.content)
1313
1515
  }).length
1314
- const line = await storeFingerprint(toolkit, { text: fact, kind, kept }, spaceContext, scoped)
1315
- if (line) parts.push(line)
1516
+ const line = await storeFingerprint(toolkit, { text: fact, kind, kept: copiesKept }, spaceContext, scoped)
1517
+ if (line && !printLines.includes(line)) printLines.push(line)
1518
+ }
1519
+ parts.push(...printLines)
1520
+ // Near the cap, say how many fingerprints are left: at the cap a forget
1521
+ // still deletes, but its copies are no longer withheld from recall.
1522
+ if (kept !== null && FINGERPRINT_CAP - kept - goneRecords.length <= FINGERPRINT_NEAR) {
1523
+ const now = await fingerprintsKept(spaceContext, scoped)
1524
+ if (now !== null) parts.push(`Fingerprints: you keep ${now} of ${FINGERPRINT_CAP} in this space; ${Math.max(0, FINGERPRINT_CAP - now)} left. At the cap a forget still deletes, but recall no longer withholds its copies; the person can lift old fingerprints in Memory's console (Memories › Forgotten), or retire instead of forgetting.`)
1316
1525
  }
1317
1526
 
1318
- // Read back, as recall searches: records, then atoms and turns.
1527
+ // Read back, as recall searches: records, then atoms and turns. A large
1528
+ // batch reads back its first few facts and says so.
1319
1529
  const back = { records: [], core: { left: [], failed: false }, recordsFailed: false }
1320
- for (const fact of facts) {
1530
+ const goneTexts = records.filter((record) => !refusedIDs.has(record.id)).map(factOf).filter(Boolean)
1531
+ const readBack = goneTexts.slice(0, READBACK_FACTS)
1532
+ if (goneTexts.length > readBack.length) parts.push(`Read back covers the first ${readBack.length} of ${goneTexts.length} facts.`)
1533
+ for (const fact of readBack) {
1321
1534
  try {
1322
1535
  const hits = (await callRecords(toolkit, "records.search", { query: oneLine(fact, 200), status: "all", limit: 20 }, spaceContext, scoped))?.hits ?? []
1323
- back.records.push(...hits.filter((hit) => gone.includes(hit.id) || matchCopy(scan.forgotten, `${hit.title}\n${hit.snippet}`)).map((hit) => hit.id))
1536
+ back.records.push(...hits.filter((hit) => gone.includes(hit.id) || (!refusedIDs.has(hit.id) && matchCopy(scan.forgotten, `${hit.title}\n${hit.snippet}`))).map((hit) => hit.id))
1324
1537
  } catch {
1325
1538
  back.recordsFailed = true
1326
1539
  }
1327
1540
  }
1328
- back.core = await core.remainingCopies({ texts: facts, forgotten: scan.forgotten, base })
1541
+ back.core = await core.remainingCopies({ texts: readBack, forgotten: scan.forgotten, base })
1329
1542
  const remaining = [...new Set(back.records)].map((id) => `record ${oneLine(id, 80)}`).concat(back.core.left.map((row) => `${row.layer} ${oneLine(row.id, 80)}`))
1330
- if (back.recordsFailed || back.core.failed) parts.push("Read back: a search failed, so it is not confirmed that recall no longer finds the fact.")
1543
+ if (readBack.length === 0) parts.push("Read back: no record was deleted, so there was nothing to read back.")
1544
+ else if (back.recordsFailed || back.core.failed) parts.push("Read back: a search failed, so it is not confirmed that recall no longer finds the fact.")
1331
1545
  else if (remaining.length === 0) parts.push("Read back: no candidate was found in the bounded search results; this does not prove recall or other stores cannot return the fact.")
1332
1546
  else parts.push(`Read back: bounded search found possible copies in ${remaining.join(", ")}. Verify each; before deleting a whole turn, show it and obtain explicit consent for the entire turn.`)
1333
1547
  }
1334
- log.info("revise forget", { records: gone.length, core: coreIDs.length, copies: copyIDs.length })
1335
- parts.push("Coverage is incomplete: other agents (including a fifth or unknown agent), rows beyond 300 per layer/agent, older record versions, other users and spaces, L2/L3, wiki, backups and derived copies were not comprehensively searched. Searches use at most 20 record and 25 core hits per query and can miss paraphrases. The persona and scenarios (L2/L3) are not changed by an id forget: mem_forget with match previews phrase erasure there.")
1336
- return [parts.join(" "), report].filter(Boolean).join("\n")
1337
- }
1338
- }
1339
-
1340
- /**
1341
- * The pre-0.9 `mem_forget`: core ids and the L2/L3 phrase erase. Kept for the
1342
- * alias PLUG-B registers ("Deprecated: use mem_revise forget").
1343
- *
1344
- * @param {any} editor
1345
- * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
1346
- */
1347
- export function registerForget(editor, toolkit) {
1348
- const { text, fail, log, scope, scopeFor, resolveWriteSpace, assertTeamWrite, displayScope, taskFor } = toolkit
1349
- const { deleteByIds, eraseSummaries } = createCoreForget(toolkit)
1350
-
1351
- editor.add({
1352
- name: "forget",
1353
- description:
1354
- "Delete explicitly named L1 atoms and L0 turns, or preview and erase matching L2/L3 lines. An id delete lists bounded candidate copies and leaves other turns intact. Before proposing deletion of a whole turn, show it and obtain the person's explicit consent to delete all of it. A permission assertion may not prompt. The person's explicit request is consent; when you propose a deletion yourself, ask first. The scan cannot establish complete erasure.",
1355
- input: {
1356
- type: "object",
1357
- properties: {
1358
- ids: {
1359
- type: "array",
1360
- items: { type: "string" },
1361
- description: 'L0/L1 ids from mem_recall or mem_remember. Pass ids or match (one is needed). Example: {"ids": ["m_...", "msg-..."]}',
1362
- },
1363
- layer: {
1364
- type: "string",
1365
- enum: ["all", "l0", "l1", "l2", "l3"],
1366
- description: "all (default); l0/l1 for ids; l2/l3 for match",
1367
- },
1368
- match: {
1369
- type: "string",
1370
- 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"}`,
1371
- },
1372
- confirm: { type: "boolean", description: "Apply the match erase (default: preview only, nothing deleted)" },
1373
- agent: { type: "string", description: "The agent that wrote the ids, if not this session's agent" },
1374
- task: { type: "string", description: "Declares the session task, as in mem_recall; deletes are not narrowed by task" },
1375
- visibility: { type: "string", enum: ["private", "team"] },
1376
- space: { type: "string", description: "Space id containing the records (control plane); defaults to your personal or session-bound shared space" },
1377
- },
1378
- additionalProperties: false,
1379
- },
1380
- options: { namespace: "mem" },
1381
- execute: async (input, context) => {
1382
- const ids = Array.isArray(input?.ids) ? [...new Set(input.ids.map(String).map((id) => id.trim()).filter(Boolean))] : []
1383
- const match = String(input?.match ?? "").trim()
1384
- const layer = ["all", "l0", "l1", "l2", "l3"].includes(String(input?.layer)) ? String(input.layer) : "all"
1385
- if (ids.length === 0 && !match) return text("nothing to forget: pass ids, or match with layer l2, l3, or all")
1386
- if (match && match.length < MIN_ERASE_CHARS) {
1387
- return text(`match needs at least ${MIN_ERASE_CHARS} characters, so it cannot erase unrelated lines.`)
1388
- }
1389
- if (match && (layer === "l0" || layer === "l1")) {
1390
- return text("match erases lines from the L2 scenarios and the L3 persona; use ids for l0 and l1.")
1391
- }
1392
- if (ids.length > 0 && (layer === "l2" || layer === "l3")) {
1393
- return text("ids delete l0 and l1 records; use match for l2 and l3.")
1394
- }
1395
- // Declares the session's task like the other tools. A delete never sends
1396
- // it: ids are exact, and a task filter would make a delete of a record
1397
- // found by a space-wide recall silently match nothing.
1398
- const task = taskFor(input, context)
1399
- if (task.invalid) return text(task.invalid)
1400
- const visibility = normalizeVisibility(input?.visibility, "private")
1401
- const resolved = await resolveWriteSpace(input, context, visibility)
1402
- if (resolved.invalid) return text(resolved.invalid)
1403
- if (resolved.error) return fail(resolved.error)
1404
- const spaceContext = resolved.context
1405
- const scoped = spaceContext
1406
- ? scopeFor(spaceContext, { sessionID: context?.sessionID, agent: context?.agent })
1407
- : scope({ sessionID: context?.sessionID, agent: context?.agent })
1408
- const label = displayScope(spaceContext, scoped)
1409
-
1410
- const preview = Boolean(match) && input?.confirm !== true
1411
- // Forget asks (D17): a delete cannot be undone, so the call asserts the
1412
- // tool's own permission before anything is deleted, and the plugin's
1413
- // default rule (src/permissions.js) or Jelly's declared `ask` makes the
1414
- // host ask. A preview deletes nothing and does not ask.
1415
- if (!preview) {
1416
- try {
1417
- await toolkit.assert({
1418
- sessionID: context?.sessionID,
1419
- agent: context?.agent,
1420
- source: { type: "tool", messageID: context?.messageID, id: context?.id },
1421
- action: FORGET_PERMISSION,
1422
- resources: [visibility],
1423
- save: [visibility],
1424
- metadata: { visibility, layer, space: label, ...(ids.length > 0 ? { ids: ids.length } : {}), ...(match ? { erase: true } : {}) },
1425
- })
1426
- } catch (error) {
1427
- return text(`forgetting denied: ${errorMessage(error)}. Nothing was deleted.`)
1428
- }
1429
- }
1430
- const approvalMetadata = { layer, space: spaceContext?.space_id ?? "team", ...(match ? { erase: true } : {}) }
1431
- // An id delete asks once it knows every row it will delete: the named ids
1432
- // and the mem_remember rows that hold only their text. Nothing is
1433
- // deleted before the answer, and a denial deletes nothing.
1434
- const approve =
1435
- visibility === "team" && !preview && ids.length > 0
1436
- ? (ownIDs) =>
1437
- assertTeamWrite(context, "memory.forget", [...ids, ...ownIDs], {
1438
- ...approvalMetadata,
1439
- ...(ownIDs.length > 0 ? { remember_rows: ownIDs.length } : {}),
1440
- })
1441
- : undefined
1442
- if (visibility === "team" && !preview && ids.length === 0) {
1443
- try {
1444
- await assertTeamWrite(context, "memory.forget", [spaceContext?.space_id ?? "team"], approvalMetadata)
1445
- } catch (error) {
1446
- return text(`forgetting team memory denied: ${errorMessage(error)}`)
1447
- }
1448
- }
1449
-
1450
- // The caller's session is never the scope of a delete: each row is
1451
- // addressed under the agent and session it was written with.
1452
- const { session_id: _session, ...base } = scoped
1453
- const explicitAgent = String(input?.agent ?? "").trim()
1454
- const idLayers = ids.length === 0 ? [] : layer === "all" ? ["l1", "l0"] : [layer]
1455
- const textLayers = !match ? [] : layer === "all" ? ["l3", "l2"] : [layer]
1456
- const textScope = { ...base, agent_id: explicitAgent || base.agent_id }
1457
- const footer =
1458
- "Not erased or verified by this call: other spaces and agents, wiki pages, raw logs and backups."
1459
-
1460
- try {
1461
- if (preview) {
1462
- const erase = await eraseSummaries({ phrase: match, layers: textLayers, apply: false, scope: textScope })
1463
- const pendingIDs = ids.length > 0 ? ` ${ids.length} id(s) would also be deleted from ${idLayers.join("/")}.` : ""
1464
- return text(
1465
- `${erase.text}\nNothing was deleted from ${label}.${pendingIDs} To apply, call mem_forget again with the same arguments and confirm: true.`,
1466
- )
1467
- }
1468
-
1469
- const parts = []
1470
- let deleted = null
1471
- let report = ""
1472
- if (ids.length > 0) {
1473
- // A suggested follow-up delete must address the same space.
1474
- const retryArgs = {
1475
- ...(visibility === "team" ? { visibility: "team" } : {}),
1476
- ...(String(input?.space ?? "").trim() ? { space: String(input.space).trim() } : {}),
1477
- }
1478
- deleted = await deleteByIds({ ids, wanted: idLayers, spaceContext, base, explicitAgent, approve, retryArgs })
1479
- if (deleted.denied) return text(`forgetting team memory denied: ${deleted.denied}`)
1480
- if (deleted.fatal && !match) {
1481
- log.warn("forget failed", deleted.fatal)
1482
- return fail(deleted.fatal)
1483
- }
1484
- parts.push(
1485
- `deleted ${deleted.total} item(s) from ${label} (${idLayers.map((name) => `${deleted.removed[name]} ${name}`).join(" and ")}).`,
1486
- ...deleted.lines,
1487
- ...(await fingerprintForgottenAtoms(toolkit, deleted, spaceContext, scoped)),
1488
- )
1489
- report = deleted.report
1490
- }
1491
- const head = parts.splice(0, parts.length).join(" ")
1492
- if (match) {
1493
- const erase = await eraseSummaries({ phrase: match, layers: textLayers, apply: true, scope: textScope })
1494
- parts.push(`Erase of "${neutralizeFenceClosers(oneLine(match, 80))}" from ${textLayers.join("/")} in ${label}:`, erase.text)
1495
- parts.push(
1496
- ids.length > 0
1497
- ? "The next consolidation rebuilds L2/L3 from the remaining atoms, so an atom that still holds the phrase can bring it back."
1498
- : "The L0 turns and L1 atoms this text came from were not touched. Delete them by id, or the next consolidation can write it back.",
1499
- )
1500
- } else {
1501
- parts.push("An id delete does not change the L2 scenarios or the L3 persona; use match to erase a phrase there.")
1502
- }
1503
- parts.push(footer)
1504
- log.info("forget", { removed: deleted?.removed ?? null, erase: Boolean(match), copies: Boolean(report) })
1505
- return text([head, report, parts.join(" ")].filter(Boolean).join("\n"))
1506
- } catch (error) {
1507
- log.warn("forget failed", error)
1508
- return fail(errorMessage(error))
1509
- }
1510
- },
1511
- })
1512
- }
1513
-
1514
- /**
1515
- * The pre-0.9 `mem_promote`: copy private memory into a shared space as one
1516
- * wiki, and revoke such a copy. Kept for the alias (`share` copy replaces it).
1517
- *
1518
- * @param {any} editor
1519
- * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
1520
- */
1521
- export function registerPromote(editor, toolkit) {
1522
- const { backend, control, text, fail, log, scope, scopeFor, displayScope, locate, knownAgents } = toolkit
1523
-
1524
- /**
1525
- * Read the text of private L1 atoms and L0 turns by id, for a share. Each id
1526
- * is looked up in the caller's personal space only, newest rows first, under
1527
- * the agents that wrote it (as mem_forget locates ids). The L0 text of a
1528
- * mem_remember turn drops its "Please remember this … for later:" wrapper.
1529
- */
1530
- async function readPrivateRecords({ ids, spaceContext, base }) {
1531
- const found = new Map()
1532
- const pending = () => ids.filter((id) => !found.has(id))
1533
- const agents = [
1534
- ...new Set(
1535
- [...ids.map((id) => locate(spaceContext, id)?.agent_id), base.agent_id, ...knownAgents(spaceContext)].filter(Boolean),
1536
- ),
1537
- ].slice(0, 4)
1538
- let failed = false
1539
- for (const layer of ["l1", "l0"]) {
1540
- for (const agent of agents) {
1541
- for (let page = 0; page < SCAN_PAGES && pending().length > 0; page += 1) {
1542
- const listScope = { ...base, agent_id: agent }
1543
- let data
1544
- try {
1545
- data =
1546
- layer === "l0"
1547
- ? await backend.queryConversations({ scope: listScope, limit: SCAN_PAGE, offset: page * SCAN_PAGE })
1548
- : await backend.queryAtoms({ scope: listScope, limit: SCAN_PAGE, offset: page * SCAN_PAGE })
1549
- } catch {
1550
- failed = true
1551
- break
1552
- }
1553
- const rows = (layer === "l0" ? (data?.messages ?? data?.items) : (data?.items ?? data?.records)) ?? []
1554
- for (const row of rows) {
1555
- const id = String(row?.id ?? "")
1556
- if (!ids.includes(id) || found.has(id)) continue
1557
- const raw = String(row?.content ?? row?.text ?? "").trim()
1558
- found.set(id, { id, layer, text: layer === "l0" ? raw.replace(REMEMBER_WRAPPER, "").trim() : raw })
1559
- }
1560
- if (rows.length < SCAN_PAGE) break
1561
- }
1562
- }
1563
- }
1564
- return { found, failed, agents }
1565
- }
1566
-
1567
- /** The Markdown a share holds: a marker, the provenance, then the copied text. */
1568
- function shareDocument({ key, label, sharer, at, space, rationale, records }) {
1569
- const lines = [
1570
- SHARE_MARKER,
1571
- `# Shared memory: ${label}`,
1572
- "",
1573
- "A copy of private memory, shared on request. It does not change when the originals change. Revoking the share deletes this wiki.",
1574
- "",
1575
- "| Field | Value |",
1576
- "|---|---|",
1577
- `| Share key | \`${key}\` |`,
1578
- `| Shared by | \`${sharer}\` |`,
1579
- `| Shared at | ${at} |`,
1580
- `| Space | \`${space}\` |`,
1581
- `| Sources | ${records.map((record) => `\`${record.layer}:${oneLine(record.id, 120)}\``).join(", ")} |`,
1582
- "",
1583
- `Rationale: ${oneLine(rationale, 500)}`,
1584
- "",
1585
- "## Copied memory",
1586
- ]
1548
+ // Forget, end to end on this machine: turns waiting in the spool or in
1549
+ // quarantine that hold the text are deleted, and later captures of this
1550
+ // session (the asking turn, the next checkpoint) are masked.
1587
1551
  for (const record of records) {
1588
- lines.push("", `### ${record.layer} \`${oneLine(record.id, 120)}\``, "", record.text)
1589
- }
1590
- return `${lines.join("\n")}\n`
1591
- }
1592
-
1593
- /**
1594
- * Is this wiki a share? "share" when SHARE.md carries the marker, "other"
1595
- * when the wiki exists without it, "absent" when the wiki is already gone
1596
- * (a retry after a partial revoke), or `{ error }`.
1597
- */
1598
- async function shareState(scope, wikiID) {
1599
- try {
1600
- const raw = await backend.readWikiRaw({ scope, wikiID, filenames: [SHARE_FILE] })
1601
- const item = (raw?.items ?? []).find((entry) => entry?.filename === SHARE_FILE)
1602
- return String(item?.content ?? "").startsWith(SHARE_MARKER) ? "share" : "other"
1603
- } catch (error) {
1604
- if (Number(error?.status) === 404) return "absent"
1605
- return { error: errorMessage(error) }
1606
- }
1607
- }
1608
-
1609
- /**
1610
- * Read a revoked share back. Gone means the gateway refuses the id (the
1611
- * catalog row is deleted) or the cell no longer has it.
1612
- */
1613
- async function readBack(scope, wikiID) {
1614
- try {
1615
- await backend.getWiki({ scope, wikiID })
1616
- return { gone: false, text: `Read back: wiki ${oneLine(wikiID, 120)} is still readable.` }
1617
- } catch (error) {
1618
- const status = Number(error?.status)
1619
- if (status === 403 || status === 404) {
1620
- return { gone: true, text: `Read back: wiki ${oneLine(wikiID, 120)} is no longer reachable (${status}).` }
1621
- }
1622
- return { gone: null, text: `Read back failed (${errorMessage(error)}).` }
1623
- }
1624
- }
1625
-
1626
- /**
1627
- * The shared space a share is made in, or revoked from: passed explicitly,
1628
- * or bound to the session. Sharing also needs editor access; a revoke
1629
- * leaves the decision to control (owner or space admin).
1630
- */
1631
- async function resolveShareSpace(input, context, { write }) {
1632
- const requested = String(input?.space ?? "").trim()
1633
- if (!control) {
1634
- if (requested) return { message: "control plane not configured; set MEMORY_CONTROL_URL to select a space" }
1635
- return { spaceContext: null, scoped: scope({ sessionID: context?.sessionID, agent: context?.agent }) }
1636
- }
1637
- // An explicit space applies to this call only. A space and a session sent
1638
- // together bind the session to that space (control's context route, and
1639
- // the gateway for a data-plane call with both hints), so the next plain
1640
- // recall searched the team space: neither is sent with the session here.
1641
- let spaceContext
1642
- try {
1643
- spaceContext = await toolkit.resolveContext({
1644
- space: requested || undefined,
1645
- sessionID: requested ? undefined : context?.sessionID,
1646
- agent: context?.agent,
1647
- })
1648
- } catch (error) {
1649
- return { error: errorMessage(error) }
1650
- }
1651
- if (!spaceContext) return { error: "the control plane returned no space context" }
1652
- if (spaceContext.space_kind !== "shared") {
1653
- return {
1654
- message: requested
1655
- ? `mem_promote cannot use personal space ${oneLine(spaceContext.space_id || "personal", 80)}; pass a shared space.`
1656
- : "no shared space is bound to this session; pass a shared space with the space argument.",
1657
- }
1552
+ if (!gone.includes(record.id)) continue
1553
+ purgeTexts.push(String(record.title ?? ""), factOf(record), String(record.body ?? "").replace(/^\s*why\s*:\s*/gim, ""))
1658
1554
  }
1659
- if (!requested && !toolkit.isSessionBound(spaceContext)) {
1660
- return { message: "the active shared space is not bound to this session; pass a shared space with the space argument." }
1661
- }
1662
- if (write) {
1663
- const role = String(spaceContext.role ?? "").trim().toLowerCase()
1664
- if (!canWriteShared(role)) {
1665
- return {
1666
- message: `sharing requires editor access to ${oneLine(spaceContext.space_id, 80)}; the control plane reports role ${role || "unknown"}.`,
1667
- }
1668
- }
1669
- }
1670
- return { spaceContext, scoped: scopeFor(spaceContext, { sessionID: requested ? undefined : context?.sessionID, agent: context?.agent }) }
1671
- }
1672
-
1673
- /** Delete a share in local mode: the wiki itself, then read it back. */
1674
- async function deleteLocalShare(scoped, wikiID) {
1675
- let data
1676
- try {
1677
- data = await backend.deleteWiki({ scope: scoped, wikiIDs: [wikiID] })
1678
- } catch (error) {
1679
- return { ok: false, text: `the cell did not delete wiki ${oneLine(wikiID, 120)} (${errorMessage(error)})` }
1680
- }
1681
- const deleted = (data?.deleted_ids ?? []).map(String).includes(wikiID)
1682
- const missing = (data?.failed ?? []).some((entry) => String(entry?.id) === wikiID && /not\s*found/i.test(String(entry?.reason ?? "")))
1683
- if (!deleted && !missing) {
1684
- return { ok: false, text: `the cell did not delete wiki ${oneLine(wikiID, 120)}` }
1685
- }
1686
- const back = await readBack(scoped, wikiID)
1687
- return { ok: back.gone === true, text: back.text }
1688
- }
1689
-
1690
- async function share(input, context) {
1691
- const ids = [...new Set((Array.isArray(input?.ids) ? input.ids : []).map((id) => String(id).trim()).filter(Boolean))]
1692
- if (ids.length === 0) return text("nothing to share: ids is empty")
1693
- if (ids.length > MAX_SHARE_IDS) return text(`not shared: at most ${MAX_SHARE_IDS} ids per share.`)
1694
- const rationale = String(input?.rationale ?? "").trim()
1695
- if (!rationale) return text("not shared: rationale is required; it is recorded on the share.")
1696
- const rationaleRefusal = writeRefusal(rationale)
1697
- if (rationaleRefusal) return text(`not shared (rationale): ${rationaleRefusal.replace(/^not stored: /, "")}`)
1698
-
1699
- const target = await resolveShareSpace(input, context, { write: true })
1700
- if (target.message) return text(target.message)
1701
- if (target.error) return fail(target.error)
1702
- const { spaceContext, scoped } = target
1703
-
1704
- // The source is always the caller's personal space: a share copies the
1705
- // caller's own private memory, never another space's.
1706
- let personal = null
1707
- if (control) {
1708
- const resolved = await toolkit.resolvePrivateSpace({}, context)
1709
- if (resolved.invalid) return text(resolved.invalid)
1710
- if (resolved.error) return fail(resolved.error)
1711
- personal = resolved.context
1712
- }
1713
- const sourceScope = personal
1714
- ? scopeFor(personal, { agent: context?.agent })
1715
- : scope({ agent: context?.agent })
1716
- const { session_id: _session, ...base } = sourceScope
1717
- const read = await readPrivateRecords({ ids, spaceContext: personal, base })
1718
- const list = (values) => values.map((id) => oneLine(id, 80)).join(", ")
1719
- const missing = ids.filter((id) => !read.found.has(id))
1720
- if (missing.length > 0) {
1721
- const where = read.failed
1722
- ? "the backend did not answer the row listing"
1723
- : `searched the newest ${SCAN_PAGE * SCAN_PAGES} l1 and l0 rows for agent(s) ${read.agents.join(", ") || "unknown"}`
1724
- return text(
1725
- `not shared: ${list(missing)} not found in your personal space (${where}). Nothing was created. Pass ids that mem_recall or mem_remember returned from private memory.`,
1726
- )
1727
- }
1728
- const records = ids.map((id) => read.found.get(id))
1729
- for (const record of records) {
1730
- if (!record.text) return text(`not shared: ${oneLine(record.id, 80)} has no text. Nothing was created.`)
1731
- if (record.text.length > MAX_SHARED_CHARS) {
1732
- return text(
1733
- `not shared: ${oneLine(record.id, 80)} is ${record.text.length} characters, over the ${MAX_SHARED_CHARS} a share copies. Share atoms, or write the synthesis with mem_wiki. Nothing was created.`,
1734
- )
1735
- }
1736
- const refusal = writeRefusal(record.text)
1737
- if (refusal) return text(`not shared: ${oneLine(record.id, 80)}: ${refusal.replace(/^not stored: /, "")} Nothing was created.`)
1738
- record.text = redactSecrets(record.text)
1739
- }
1740
-
1741
- const spaceID = spaceContext?.space_id ?? "local"
1742
- try {
1743
- await toolkit.assert({
1744
- sessionID: context?.sessionID,
1745
- agent: context?.agent,
1746
- source: { type: "tool", messageID: context?.messageID, id: context?.id },
1747
- action: "memory.promote",
1748
- resources: ids,
1749
- save: [],
1750
- metadata: {
1751
- space: spaceID,
1752
- rationale,
1753
- copies: records.map((record) => `${record.layer}:${oneLine(record.id, 80)}: ${oneLine(record.text, 160)}`),
1754
- },
1755
- })
1756
- } catch (error) {
1757
- return text(`sharing denied: ${errorMessage(error)}`)
1758
- }
1759
-
1760
- const key = `share-${randomBytes(4).toString("hex")}`
1761
- const label = oneLine(input?.name, 120).trim() || oneLine(records[0].text, 60)
1762
- const wikiName = `Shared memory: ${label} [${key}]`
1763
- let wiki
1764
- try {
1765
- wiki = await backend.createWiki({ scope: scoped, name: wikiName })
1766
- } catch (error) {
1767
- log.warn("share create failed", error)
1768
- return fail(`the share could not be created (${errorMessage(error)}). Nothing was shared.`)
1769
- }
1770
- const wikiID = String(wiki?.wiki_id ?? "").trim()
1771
- if (!wikiID) return fail("wiki/create returned no wiki_id. Nothing was shared.")
1772
-
1773
- // A gateway with the create hook registered it and says so; an older one
1774
- // did not, so register explicitly (the route is idempotent).
1775
- let shareID = wikiID
1776
- if (spaceContext) {
1777
- shareID = typeof wiki?.resource_id === "string" ? wiki.resource_id.trim() : ""
1778
- if (!shareID) {
1779
- try {
1780
- const registered = await control.createResource({
1781
- userId: spaceContext.user_id || toolkit.runtime.config.user,
1782
- spaceId: spaceContext.space_id,
1783
- resource: { kind: "wiki", upstream_id: wikiID, name: wikiName },
1784
- })
1785
- shareID = String(registered?.id ?? "").trim()
1786
- } catch (error) {
1787
- return fail(
1788
- `wiki ${wikiID} was created but could not be registered (${errorMessage(error)}). It is invisible to the space and holds no copy yet; nothing was shared.`,
1789
- )
1790
- }
1791
- if (!shareID) return fail(`wiki ${wikiID} was created but registration returned no id; nothing was shared.`)
1792
- }
1793
- }
1794
-
1795
- const document = shareDocument({
1796
- key,
1797
- label,
1798
- sharer: spaceContext?.user_id || toolkit.runtime.config.user || "local",
1799
- at: new Date().toISOString(),
1800
- space: spaceID,
1801
- rationale,
1802
- records,
1803
- })
1804
- try {
1805
- await backend.writeWikiRaw({ scope: scoped, wikiID, files: [{ filename: SHARE_FILE, content: document }] })
1806
- } catch (error) {
1807
- log.warn("share write failed", error)
1808
- // Do not leave an empty share behind.
1809
- let cleanup
1810
- if (spaceContext) {
1811
- try {
1812
- await control.deleteResource({
1813
- userId: spaceContext.user_id || toolkit.runtime.config.user,
1814
- spaceId: spaceContext.space_id,
1815
- resourceId: shareID,
1816
- })
1817
- cleanup = "the empty share was deleted"
1818
- } catch (cleanupError) {
1819
- cleanup = `the empty share ${shareID} remains (${errorMessage(cleanupError)}); revoke it with mem_promote revoke`
1820
- }
1821
- } else {
1822
- const removed = await deleteLocalShare(scoped, wikiID)
1823
- cleanup = removed.ok ? "the empty share was deleted" : `the empty share ${wikiID} remains: ${removed.text}`
1824
- }
1825
- return fail(`the copy could not be written (${errorMessage(error)}); ${cleanup}. Nothing was shared.`)
1826
- }
1827
-
1828
- let ingest = ""
1829
- try {
1830
- await backend.ingestWiki({ scope: scoped, wikiID })
1831
- } catch (error) {
1832
- ingest = ` Ingestion did not start (${errorMessage(error)}): mem_wiki read shows the copy now; search finds it after ingestion.`
1833
- }
1834
- const targetLabel = spaceContext ? displayScope(spaceContext, scoped) : "the local shared scope"
1835
- log.info("share", { space: spaceID, count: ids.length })
1836
- const revokeCall = spaceContext
1837
- ? `mem_promote({ revoke: "${shareID}", space: "${oneLine(spaceContext.space_id, 80)}" })`
1838
- : `mem_promote({ revoke: "${shareID}" })`
1839
- return text(
1840
- `shared ${ids.length} memory id(s) to ${targetLabel} as share ${shareID} (wiki ${wikiID}). It is a copy: your private originals are unchanged, and later edits to them do not reach it. Readers find it with mem_wiki or mem_recall sources "knowledge"; plain memory recall does not return it.${ingest} To revoke: ${revokeCall}.`,
1841
- )
1842
- }
1843
-
1844
- async function revoke(input, context) {
1845
- const shareID = String(input?.revoke ?? "").trim()
1846
- if (Array.isArray(input?.ids) && input.ids.length > 0) {
1847
- return text("pass ids to share, or revoke to delete a share, not both.")
1848
- }
1849
- const target = await resolveShareSpace(input, context, { write: false })
1850
- if (target.message) return text(target.message.replace("pass a shared space", "pass the shared space the share was made in"))
1851
- if (target.error) return fail(target.error)
1852
- const { spaceContext, scoped } = target
1853
- const userId = spaceContext ? spaceContext.user_id || toolkit.runtime.config.user : ""
1854
- const refused = (error) => [400, 403, 404].includes(Number(error?.status))
1855
-
1856
- // Learn what the id names, and whether this caller may delete it, before
1857
- // anything changes.
1858
- let wikiID = shareID
1859
- if (spaceContext) {
1860
- let dry
1555
+ if (purge && (gone.length > 0 || purgeTexts.length > 0 || coreGone > 0)) {
1861
1556
  try {
1862
- dry = await control.deleteResource({ userId, spaceId: spaceContext.space_id, resourceId: shareID, dryRun: true })
1557
+ const purged = await purge.afterForget({ space: purgeSpace, texts: purgeTexts, scope: scoped })
1558
+ if (purged.purged > 0) parts.push(`Deleted ${purged.purged} turn(s) waiting on this machine to be sent that held the forgotten text.`)
1559
+ if (purged.pending) parts.push("This machine could not read the forget's purge entry yet; turns of this space waiting to be sent are held back until it can, for at most 24 hours.")
1863
1560
  } catch (error) {
1864
- return refused(error) ? text(`revoke refused: ${errorMessage(error)}`) : fail(errorMessage(error))
1561
+ log.warn("forget purge failed", errorMessage(error))
1865
1562
  }
1866
- wikiID = String(dry?.resource?.upstream_id ?? "").trim()
1867
- if (dry?.resource?.kind !== "wiki" || !wikiID) {
1868
- return text(`${oneLine(shareID, 80)} is not a share; mem_promote revoke deletes only shares. Nothing was deleted.`)
1869
- }
1870
- }
1871
- const state = await shareState(scoped, wikiID)
1872
- if (state === "other" || (!spaceContext && state === "absent")) {
1873
- return text(
1874
- state === "other"
1875
- ? `${oneLine(shareID, 80)} is not a share made by mem_promote; nothing was deleted.`
1876
- : `share ${oneLine(shareID, 80)} was not found; nothing was deleted.`,
1877
- )
1878
- }
1879
- if (typeof state === "object") return fail(`could not confirm that ${oneLine(shareID, 80)} is a share (${state.error}). Nothing was deleted.`)
1880
-
1881
- try {
1882
- await toolkit.assert({
1883
- sessionID: context?.sessionID,
1884
- agent: context?.agent,
1885
- source: { type: "tool", messageID: context?.messageID, id: context?.id },
1886
- action: "memory.promote.revoke",
1887
- resources: [shareID],
1888
- save: [],
1889
- metadata: { space: spaceContext?.space_id ?? "local", wiki: wikiID },
1890
- })
1891
- } catch (error) {
1892
- return text(`revoke denied: ${errorMessage(error)}`)
1893
- }
1894
-
1895
- const where = spaceContext ? displayScope(spaceContext, scoped) : "the local shared scope"
1896
- const tail =
1897
- "Your private originals are unchanged. Anyone who already read the share may still have it in their own memory or transcripts."
1898
- if (!spaceContext) {
1899
- const removed = await deleteLocalShare(scoped, wikiID)
1900
- log.info("share revoke", { space: "local", ok: removed.ok })
1901
- return removed.ok
1902
- ? text(`revoked share ${oneLine(shareID, 80)} in ${where}: the copy was deleted. ${removed.text} ${tail}`)
1903
- : fail(`share ${oneLine(shareID, 80)} was not revoked: ${removed.text}.`)
1904
1563
  }
1905
-
1906
- let result
1907
- try {
1908
- result = await control.deleteResource({ userId, spaceId: spaceContext.space_id, resourceId: shareID })
1909
- } catch (error) {
1910
- log.warn("share revoke failed", error)
1911
- return refused(error) ? text(`revoke refused: ${errorMessage(error)}`) : fail(`share ${oneLine(shareID, 80)} was not revoked: ${errorMessage(error)}`)
1912
- }
1913
- if (result?.deleted !== true) return fail(`share ${oneLine(shareID, 80)} was not revoked: the gateway did not confirm the delete.`)
1914
- const back = await readBack(scoped, wikiID)
1915
- log.info("share revoke", { space: spaceContext.space_id, verified: back.gone })
1916
- if (back.gone === false) {
1917
- return fail(`share ${oneLine(shareID, 80)}: the gateway reported a delete, but ${back.text.replace(/^Read back: /, "")} Report this to an operator.`)
1918
- }
1919
- return text(
1920
- `revoked share ${oneLine(shareID, 80)} in ${where}: the copy (wiki ${oneLine(wikiID, 120)}) and its catalog entry were deleted. ${back.text} ${tail}`,
1921
- )
1564
+ log.info("revise forget", { records: gone.length, core: coreIDs.length, copies: copyIDs.length })
1565
+ parts.push("Coverage is incomplete: other agents (including a fifth or unknown agent), rows beyond 300 per layer/agent, older record versions, other users and spaces, L2/L3, wiki, backups and derived copies were not comprehensively searched. Searches use at most 20 record and 25 core hits per query and can miss paraphrases. The persona and scenarios (L2/L3) are not changed by an id forget; the person erases a phrase there on the Profile page of Memory's console.")
1566
+ return [parts.join(" "), refusedBlock, report].filter(Boolean).join("\n")
1922
1567
  }
1923
-
1924
- editor.add({
1925
- name: "promote",
1926
- description:
1927
- "Copy private memories into a shared space, or revoke such a copy. Only when the user explicitly asks. Copies the text of the ids from your personal space into one new wiki in the shared space (passed or session-bound; editor access; approval), with provenance. Originals stay private; later edits do not reach the copy. Readers use mem_wiki or mem_recall sources \"knowledge\". revoke: the share id it returned; deletes the copy and reads it back (sharer or space owner/admin only).",
1928
- input: {
1929
- type: "object",
1930
- properties: {
1931
- ids: {
1932
- type: "array",
1933
- items: { type: "string" },
1934
- description:
1935
- '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"}',
1936
- },
1937
- name: { type: "string", description: "Short name for the share" },
1938
- rationale: { type: "string", description: "Why the shared space should see this; required to share, recorded on the share" },
1939
- space: {
1940
- type: "string",
1941
- 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",
1942
- },
1943
- revoke: {
1944
- type: "string",
1945
- description: 'To revoke instead: the share id an earlier mem_promote returned; deletes that copy. Example: {"revoke": "res_...", "space": "space-team"}',
1946
- },
1947
- },
1948
- additionalProperties: false,
1949
- },
1950
- options: { namespace: "mem" },
1951
- execute: async (input, context) => {
1952
- if (String(input?.revoke ?? "").trim()) return revoke(input, context)
1953
- return share(input, context)
1954
- },
1955
- })
1956
- }
1957
-
1958
- /**
1959
- * Memory writes as registered before 0.9 (remember, forget, promote), for a
1960
- * tool index that has not moved to the 0.9 set.
1961
- *
1962
- * @param {any} editor
1963
- * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
1964
- */
1965
- export function registerMemory(editor, toolkit) {
1966
- registerRemember(editor, toolkit)
1967
- registerForget(editor, toolkit)
1968
- registerPromote(editor, toolkit)
1969
1568
  }