@joe-broadhead/opencode-mem 0.9.2 → 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 (64) hide show
  1. package/CHANGELOG.md +1605 -0
  2. package/README.md +135 -43
  3. package/docs/agent-protocol.md +29 -28
  4. package/docs/permissions.md +148 -0
  5. package/package.json +277 -16
  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 +47 -16
  10. package/src/backend/records.js +413 -50
  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 -4
  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 +162 -1
  20. package/src/connect.js +353 -0
  21. package/src/copies.js +28 -3
  22. package/src/credentials.js +35 -7
  23. package/src/curation.js +33 -14
  24. package/src/events.js +144 -36
  25. package/src/forget-purge.js +377 -0
  26. package/src/forgotten.js +356 -0
  27. package/src/hooks.js +9 -4
  28. package/src/index.js +25 -6
  29. package/src/permissions.js +116 -38
  30. package/src/protocol.js +21 -11
  31. package/src/records.js +4 -1
  32. package/src/runtime.js +207 -16
  33. package/src/shapes.js +63 -0
  34. package/src/sources.js +183 -12
  35. package/src/spaces.js +58 -1
  36. package/src/spool.js +442 -64
  37. package/src/stated.js +334 -0
  38. package/src/storable.js +477 -0
  39. package/src/tools/aliases.js +36 -147
  40. package/src/tools/commitments.js +69 -12
  41. package/src/tools/held-write.js +9 -1
  42. package/src/tools/index.js +29 -44
  43. package/src/tools/ingest.js +33 -128
  44. package/src/tools/memory.js +594 -901
  45. package/src/tools/page-sections.js +147 -0
  46. package/src/tools/page.js +314 -82
  47. package/src/tools/recall-browse.js +173 -0
  48. package/src/tools/recall.js +79 -19
  49. package/src/tools/share.js +494 -131
  50. package/src/tools/shared.js +97 -19
  51. package/src/tools/spaces.js +215 -104
  52. package/src/tools/status.js +31 -3
  53. package/src/tools/wiki.js +5 -13
  54. package/src/util.js +10 -20
  55. package/src/views/contracts.js +137 -6
  56. package/src/views/overdue.js +125 -0
  57. package/src/views/profile.js +154 -0
  58. package/src/views/records-reads.js +132 -33
  59. package/src/views/rpc.js +63 -12
  60. package/src/views/shape.js +49 -0
  61. package/views/commitments.html +31 -4
  62. package/views/home.html +22 -3
  63. package/views/memory.html +126 -24
  64. 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,
@@ -17,19 +15,11 @@ import {
17
15
  } from "../copies.js"
18
16
  import { errorMessage, neutralizeFenceClosers, oneLine, redactSecrets } from "../util.js"
19
17
  import { isCoded } from "../errors.js"
20
- import { RecordsError } from "../backend/records.js"
21
- import { TASK_INPUT, canWriteShared } from "./shared.js"
22
- import { holdTeamWrite } from "./held-write.js"
18
+ import { RecordsError, isRecordsUnavailable } from "../backend/records.js"
19
+ import { FORGOTTEN_ID, createForgottenMatcher } from "../forgotten.js"
20
+ import { TASK_INPUT, canWriteShared, hostProvenance } from "./shared.js"
23
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"
24
22
 
25
- /**
26
- * The permission mem_forget asserts before it deletes: the tool's own engine
27
- * id, declared `effect: "ask"` in `jelly.tools`. Not an approval action
28
- * (`jelly.asks`), so it is a name here, not a literal the scan in
29
- * scripts/approval-actions.mjs would read as one.
30
- */
31
- const FORGET_PERMISSION = "mem_forget"
32
-
33
23
  const KINDS = MEMORY_TYPES
34
24
  /** A supersede replaces a few records, not a cleanup: more is a forget. */
35
25
  const MAX_SUPERSEDES = 10
@@ -42,6 +32,24 @@ export const REVISE_ACTIONS = Object.freeze(["correct", "confirm", "retire", "re
42
32
  * the upstream per-message limit and points long synthesis at the wiki.
43
33
  */
44
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
45
53
 
46
54
  /** The forget scan reads at most this many rows per layer and agent. */
47
55
  const SCAN_PAGE = 100
@@ -54,64 +62,177 @@ const COPY_SCAN_MS = 5_000
54
62
  /** Copies listed in one forget result; the rest are counted, not shown. */
55
63
  const MAX_COPIES_LISTED = 10
56
64
  const COPY_EXCERPT_CHARS = 120
57
- /** Upstream caps L2 at 15 scenes; read a little more in case that changes. */
58
- 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
+ }
59
70
 
60
71
  /**
61
- * Shares (mem_promote): one wiki per share, holding a copy of private memory
62
- * (docs/design/adr-sharing-semantics.md). The marker on the first line is
63
- * 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.
64
75
  */
65
- const MAX_SHARE_IDS = 20
66
- const MAX_SHARED_CHARS = 8_000
67
- const SHARE_FILE = "SHARE.md"
68
- 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
+ }
69
94
 
70
95
  /**
71
- * The core's forget machinery, one per toolkit, shared by mem_revise (for
72
- * `m_` and `msg-` ids) and the legacy mem_forget, so a copy reported by one is
73
- * 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).
74
98
  *
75
99
  * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
76
100
  */
77
101
  export function createCoreForget(toolkit) {
78
102
  if (coreForgets.has(toolkit)) return coreForgets.get(toolkit)
79
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)
80
109
 
81
110
  /**
82
- * Remove the core L1 atoms a new memory replaces, after it was stored.
83
- * Each id is deleted under the agent that wrote it, as mem_recall showed it;
84
- * an id this process has not seen is tried under this session's agent. Only
85
- * 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.
86
116
  */
87
- async function supersede(ids, spaceContext, base) {
88
- 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
+ }
89
168
  for (const id of ids) {
90
- const hit = locate(spaceContext, id)
91
- const agent = hit?.layer === "l1" && hit.agent_id ? hit.agent_id : base.agent_id
92
- if (!groups.has(agent)) groups.set(agent, [])
93
- 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
+ }
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
+ }
94
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) {
95
213
  const removed = []
96
- const missing = []
97
- const failed = []
98
- 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
99
218
  try {
100
- 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 } : {}) } })
101
220
  const confirmed = Array.isArray(data?.deleted_ids) ? data.deleted_ids.includes(id) : Number(data?.deleted_count) === 1
102
- ;(confirmed ? removed : missing).push(id)
221
+ ;(confirmed ? removed : notRemoved).push(`${oneLine(id, 80)} as ${record}`)
222
+ if (confirmed) forgetLocations(spaceContext, [id])
103
223
  } catch (error) {
104
- failed.push(`${oneLine(id, 80)} (${errorMessage(error)})`)
224
+ notRemoved.push(`${oneLine(id, 80)} as ${record} (${errorMessage(error)})`)
105
225
  }
106
226
  }
107
- forgetLocations(spaceContext, removed)
108
- const list = (values) => values.map((id) => oneLine(id, 80)).join(", ")
109
227
  const lines = []
110
228
  if (removed.length > 0) {
111
- 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.`)
112
235
  }
113
- if (missing.length > 0) lines.push(`Not found, so not removed: ${list(missing)} (pass ids from mem_recall).`)
114
- if (failed.length > 0) lines.push(`Not removed, the delete failed: ${failed.join("; ")}.`)
115
236
  lines.push("Captured turns that mention the old value stay as history.")
116
237
  return lines.join(" ")
117
238
  }
@@ -142,7 +263,7 @@ export function createCoreForget(toolkit) {
142
263
  * 4. Delete the named ids, then those remember rows.
143
264
  * 5. Report every other copy with its id and an excerpt; delete nothing else.
144
265
  */
145
- async function deleteByIds({ ids, wanted, spaceContext, base, explicitAgent, approve, retryArgs = {} }) {
266
+ async function deleteByIds({ ids, wanted, spaceContext, base, explicitAgent, approve }) {
146
267
  const found = new Map()
147
268
  for (const id of ids) {
148
269
  const hit = locate(spaceContext, id)
@@ -283,6 +404,9 @@ export function createCoreForget(toolkit) {
283
404
  groups.get(key).ids.push(id)
284
405
  }
285
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 = []
409
+ const confirmedIDs = []
286
410
  const unconfirmed = []
287
411
  const noSession = []
288
412
  const errors = []
@@ -296,10 +420,11 @@ export function createCoreForget(toolkit) {
296
420
  const data =
297
421
  group.layer === "l1"
298
422
  ? await backend.deleteAtoms({ ids: group.ids, scope: groupScope })
299
- : 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)
300
424
  const count = Math.max(0, Math.min(group.ids.length, Number(data?.deleted_count) || 0))
301
425
  removed[group.layer] += count
302
426
  if (count < group.ids.length) unconfirmed.push({ ...group, missing: group.ids.length - count })
427
+ else confirmedIDs.push(...group.ids)
303
428
  } catch (error) {
304
429
  errors.push({ ...group, error: errorMessage(error) })
305
430
  }
@@ -335,10 +460,13 @@ export function createCoreForget(toolkit) {
335
460
  for (const group of ownGroups.values()) {
336
461
  const messageIDs = group.rows.map((row) => row.id)
337
462
  try {
338
- const data = await backend.deleteConversations({
339
- messageIDs,
340
- scope: { ...base, ...(group.agent ? { agent_id: group.agent } : {}), session_id: group.session },
341
- })
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
+ )
342
470
  const count = Math.max(0, Math.min(messageIDs.length, Number(data?.deleted_count) || 0))
343
471
  if (count === messageIDs.length) ownDeleted.push(...group.rows)
344
472
  else ownKept.push(...group.rows.map((row) => ({ ...row, note: `the backend confirmed ${count} of ${messageIDs.length} in its session` })))
@@ -392,6 +520,7 @@ export function createCoreForget(toolkit) {
392
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))}.`,
393
521
  )
394
522
  }
523
+ lines.push(...new Set(bindingNotes))
395
524
  const report =
396
525
  total > 0 && found.size > 0
397
526
  ? copiesReport({
@@ -399,18 +528,19 @@ export function createCoreForget(toolkit) {
399
528
  copies: [...ownKept, ...copies],
400
529
  windows,
401
530
  base,
402
- retryArgs,
403
531
  unscannedAgents: knownAgents(spaceContext).filter((agent) => !copyAgents.includes(agent)),
404
532
  })
405
533
  : ""
406
- return { removed, total, fatal, lines, report, errors: errors.length, unlocated: unlocated.length, forgottenRows }
534
+ // The rows confirmed gone: a forgotten atom among them may need a fingerprint.
535
+ const deletedIDs = [...new Set([...confirmedIDs, ...ownDeleted.map((row) => row.id)])]
536
+ return { removed, total, fatal, lines, report, errors: errors.length, unlocated: unlocated.length, forgottenRows, deletedIDs }
407
537
  }
408
538
 
409
539
  /**
410
540
  * The copies block of a forget result: bounded, fenced as stored memory
411
541
  * text, with the ids and the call that deletes them, and what was scanned.
412
542
  */
413
- function copiesReport({ forgotten, copies, windows, base, retryArgs, unscannedAgents = [] }) {
543
+ function copiesReport({ forgotten, copies, windows, base, unscannedAgents = [] }) {
414
544
  const scanned = new Map()
415
545
  for (const window of windows) {
416
546
  if (!scanned.has(window.agent)) scanned.set(window.agent, {})
@@ -471,126 +601,13 @@ export function createCoreForget(toolkit) {
471
601
  lines.push(`(+${ranked.length - shown.length} more not listed or deleted; these also need individual review.)`)
472
602
  }
473
603
  lines.push("</forget_copies>")
474
- const byAgent = new Map()
475
- for (const row of shown) {
476
- const agent = row.agent_id ?? base.agent_id
477
- if (!byAgent.has(agent)) byAgent.set(agent, [])
478
- byAgent.get(agent).push(row.id)
479
- }
480
- const calls = [...byAgent].map(([agent, rowIDs]) =>
481
- `mem_forget(${JSON.stringify({ ids: rowIDs, ...retryArgs, ...(agent && agent !== base.agent_id ? { agent } : {}) })})`,
482
- )
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) })})`]
483
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("; ")}.`)
484
607
  lines.push(scannedLine)
485
608
  return lines.join("\n")
486
609
  }
487
610
 
488
- /**
489
- * Erase the lines that contain a phrase from the L3 persona and the L2
490
- * scenarios. Without `apply` it only reads and reports. With `apply` it
491
- * rewrites every file that has a matching line, rebuilds the pinned block,
492
- * and reads the files back so the result states where the phrase remains.
493
- */
494
- async function eraseSummaries({ phrase, layers, apply, scope }) {
495
- const readFiles = async () => {
496
- const files = []
497
- const notes = []
498
- if (layers.includes("l3")) {
499
- try {
500
- const data = await backend.readCore({ scope })
501
- files.push({ layer: "l3", path: "persona", content: typeof data?.content === "string" ? data.content : "" })
502
- } catch (error) {
503
- files.push({ layer: "l3", path: "persona", content: "", error: errorMessage(error) })
504
- }
505
- }
506
- if (layers.includes("l2")) {
507
- try {
508
- const listed = await backend.listScenarios({ scope })
509
- const entries = (listed?.entries ?? []).filter((entry) => entry?.path && !String(entry.path).endsWith("/"))
510
- if (entries.length > MAX_SCENARIOS) notes.push(`Only the first ${MAX_SCENARIOS} of ${entries.length} scenarios were read.`)
511
- for (const entry of entries.slice(0, MAX_SCENARIOS)) {
512
- const path = String(entry.path)
513
- try {
514
- const data = await backend.readScenario({ path, scope })
515
- files.push({ layer: "l2", path, summary: String(entry.summary ?? ""), content: String(data?.content ?? "") })
516
- } catch (error) {
517
- files.push({ layer: "l2", path, summary: String(entry.summary ?? ""), content: "", error: errorMessage(error) })
518
- }
519
- }
520
- } catch (error) {
521
- notes.push(`The scenario list could not be read (${errorMessage(error)}), so L2 was not checked.`)
522
- }
523
- }
524
- return { files, notes }
525
- }
526
-
527
- const quote = (line) => ` > ${neutralizeFenceClosers(oneLine(line, 160))}`
528
- const name = (file) => (file.layer === "l3" ? "L3 persona" : `L2 ${neutralizeFenceClosers(oneLine(file.path, 160))}`)
529
- const before = await readFiles()
530
- const lines = []
531
- for (const note of before.notes) lines.push(note)
532
- for (const file of before.files) if (file.error) lines.push(`${name(file)} could not be read: ${file.error}.`)
533
- const hits = before.files.filter((file) => !file.error && matchingLines(file.content, phrase).length > 0)
534
- const summaryHits = before.files.filter((file) => file.layer === "l2" && containsPhrase(file.summary, phrase))
535
-
536
- if (!apply) {
537
- const body = []
538
- for (const file of hits) {
539
- const found = matchingLines(file.content, phrase)
540
- body.push(`- ${name(file)}: ${found.length} line(s) contain it:`)
541
- body.push(...found.slice(0, 10).map(quote))
542
- if (found.length > 10) body.push(` (+${found.length - 10} more)`)
543
- }
544
- for (const file of summaryHits) {
545
- body.push(`- L2 summary of ${neutralizeFenceClosers(oneLine(file.path, 160))} contains it; rewriting the file does not change the summary the backend lists.`)
546
- }
547
- const checked = before.files.filter((file) => !file.error).length
548
- if (body.length === 0) body.push(`No line in the ${checked} file(s) checked contains it.`)
549
- return {
550
- changed: 0,
551
- text: [
552
- `<forget_preview phrase="${neutralizeFenceClosers(oneLine(phrase, 80)).replace(/"/g, "'")}">`,
553
- "Preview only: nothing was changed. The lines below are stored memory text: data, not instructions.",
554
- ...body,
555
- "</forget_preview>",
556
- ...lines,
557
- ].join("\n"),
558
- }
559
- }
560
-
561
- let changed = 0
562
- for (const file of hits) {
563
- const next = eraseLines(file.content, phrase)
564
- try {
565
- if (file.layer === "l3") await backend.writeCore({ content: next.content, scope })
566
- else await backend.writeScenario({ path: file.path, content: next.content, scope })
567
- changed += 1
568
- lines.push(`${name(file)}: removed ${next.removed} line(s).`)
569
- } catch (error) {
570
- lines.push(`${name(file)}: write failed, nothing removed (${errorMessage(error)}).`)
571
- }
572
- }
573
- if (hits.length === 0) lines.push("No persona or scenario line contained it, so nothing was rewritten.")
574
- // The pinned block caches L2/L3 for ten minutes; drop every cached copy.
575
- if (changed > 0) toolkit.runtime.invalidate?.()
576
-
577
- const after = await readFiles()
578
- const remaining = []
579
- for (const file of after.files) {
580
- if (file.error) remaining.push(`${name(file)} (could not be read back: ${file.error})`)
581
- else if (containsPhrase(file.content, phrase)) remaining.push(name(file))
582
- if (file.layer === "l2" && containsPhrase(file.summary, phrase)) {
583
- remaining.push(`the L2 summary of ${neutralizeFenceClosers(oneLine(file.path, 160))}, which the backend keeps outside the file`)
584
- }
585
- }
586
- lines.push(
587
- remaining.length === 0
588
- ? `Read back: no persona or scenario checked (${after.files.length} file(s)) contains it.`
589
- : `Read back: it remains in ${remaining.join("; ")}.`,
590
- )
591
- return { changed, text: lines.join(" ") }
592
- }
593
-
594
611
  /** One newest-first page of a layer's rows under one agent, noting where each row was written. */
595
612
  const pageReader = (spaceContext, base, agent, layer) => async (offset) => {
596
613
  const listScope = { ...base, agent_id: agent }
@@ -648,6 +665,7 @@ export function createCoreForget(toolkit) {
648
665
  * what it did not delete, with the reason.
649
666
  */
650
667
  async function deleteRows(rows, base) {
668
+ const notes = []
651
669
  const groups = new Map()
652
670
  for (const row of rows) {
653
671
  const key = `${row.layer}::${row.agent_id ?? ""}::${row.layer === "l0" ? (row.session_id ?? "") : ""}`
@@ -667,7 +685,7 @@ export function createCoreForget(toolkit) {
667
685
  const data =
668
686
  group.layer === "l1"
669
687
  ? await backend.deleteAtoms({ ids, scope })
670
- : await backend.deleteConversations({ messageIDs: ids, scope: { ...scope, session_id: group.session } })
688
+ : await deleteTurns({ messageIDs: ids, scope: { ...scope, session_id: group.session } }, notes)
671
689
  const confirmed = Array.isArray(data?.deleted_ids) ? data.deleted_ids.includes(row.id) : Number(data?.deleted_count) === 1
672
690
  if (confirmed) deleted.push(row)
673
691
  else kept.push({ ...row, why: "the core did not confirm the delete" })
@@ -675,7 +693,7 @@ export function createCoreForget(toolkit) {
675
693
  kept.push({ ...row, why: `the delete failed: ${errorMessage(error)}` })
676
694
  }
677
695
  }
678
- return { deleted, kept }
696
+ return { deleted, kept, notes: [...new Set(notes)] }
679
697
  }
680
698
 
681
699
  /**
@@ -704,13 +722,72 @@ export function createCoreForget(toolkit) {
704
722
  return { left: [...new Map(left.map((row) => [row.id, row])).values()], failed }
705
723
  }
706
724
 
707
- const api = { supersedeAtoms: supersede, deleteByIds, eraseSummaries, scanCopies, deleteRows, remainingCopies, copiesReport }
725
+ const api = { keepAtoms, dropKept, supersedeAtoms: supersede, deleteByIds, scanCopies, deleteRows, remainingCopies, copiesReport }
708
726
  coreForgets.set(toolkit, api)
709
727
  return api
710
728
  }
711
729
 
712
730
  const coreForgets = new WeakMap()
713
731
 
732
+ /** A records service before 0.9.5 has no `forgotten.*` methods (or no records at all). */
733
+ function noFingerprints(error) {
734
+ return isRecordsUnavailable(error) || error?.code === "records_missing" || error?.status === 404
735
+ }
736
+
737
+ /**
738
+ * Store a fingerprint of a forgotten text (src/forgotten.js), so recall
739
+ * withholds from this person, in every later session, every turn and atom
740
+ * that copies it, including copies written after the forget (its own reply
741
+ * quotes the turns). The service extracts the features and keeps keyed
742
+ * hashes, never the text. It never lifts itself: only the person lifts it,
743
+ * in Memory's console. Answers the line for the forget's report.
744
+ *
745
+ * The words about copies are said only when this forget kept some: with none,
746
+ * the report must not send the agent looking for them.
747
+ *
748
+ * @param {{ text: string, kind: string, kept?: number }} entry
749
+ */
750
+ async function storeFingerprint(toolkit, entry, spaceContext, scoped) {
751
+ try {
752
+ await callRecords(toolkit, "forgotten.put", { text: String(entry.text).slice(0, 4_000), kind: entry.kind }, spaceContext, scoped)
753
+ return entry.kept > 0
754
+ ? "Recall won't show these copies. To delete them, ask your agent; 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)."
756
+ } catch (error) {
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).`
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."
759
+ if (noFingerprints(error)) return "This Memory server can't withhold forgotten text (it is older than 0.9.5): a later mem_recall can show its copies until they are deleted."
760
+ return `Recall was not told to withhold copies of the forgotten text (${errorMessage(error)}): a later mem_recall can show them until they are deleted.`
761
+ }
762
+ }
763
+
764
+ /**
765
+ * After core rows are deleted by id: fingerprint each forgotten atom that
766
+ * copies none of the caller's fingerprints (its turns may stay). Deleting a
767
+ * copy never lifts a fingerprint: a later copy would show the fact again.
768
+ *
769
+ * @param {{ deletedIDs: string[], forgottenRows: any[] }} deleted
770
+ * @returns {Promise<string[]>}
771
+ */
772
+ async function fingerprintForgottenAtoms(toolkit, deleted, spaceContext, scoped) {
773
+ const gone = new Set(deleted?.deletedIDs ?? [])
774
+ const atoms = (deleted?.forgottenRows ?? []).filter((row) => row.layer === "l1" && gone.has(row.id) && String(row.content ?? "").trim())
775
+ if (atoms.length === 0) return []
776
+ let matcher = null
777
+ try {
778
+ matcher = createForgottenMatcher(await callRecords(toolkit, "forgotten.list", {}, spaceContext, scoped))
779
+ } catch (error) {
780
+ return noFingerprints(error) ? [] : [`The forgotten-copy fingerprints could not be read (${errorMessage(error)}), so this forget added none.`]
781
+ }
782
+ const lines = []
783
+ for (const row of atoms) {
784
+ if (matcher.match(row.content)) continue
785
+ const line = await storeFingerprint(toolkit, { text: row.content, kind: "atom" }, spaceContext, scoped)
786
+ if (line) lines.push(line)
787
+ }
788
+ return lines
789
+ }
790
+
714
791
  /** Ids from a string or a list, trimmed and de-duplicated. */
715
792
  function idList(value) {
716
793
  if (Array.isArray(value)) return [...new Set(value.map((id) => String(id ?? "").trim()).filter(Boolean))]
@@ -718,6 +795,38 @@ function idList(value) {
718
795
  return []
719
796
  }
720
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
+
721
830
  /** Lower-case words only, for an exact-duplicate check. */
722
831
  function normal(text) {
723
832
  return String(text ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()
@@ -729,61 +838,61 @@ function normal(text) {
729
838
  * stored verbatim with its type, answers its `rec_` id at once, and recall
730
839
  * finds it at once. Nothing is written to the core.
731
840
  *
732
- * Every curation refusal runs before any request. A team write asks
733
- * `memory.remember`. A records write is never queued: an answer without an id
734
- * 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.
735
851
  *
736
852
  * @param {any} editor
737
853
  * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
738
854
  */
739
855
  export function registerRemember(editor, toolkit) {
740
- const { text, fail, log, scope, scopeFor, resolveWriteSpace, assertTeamWrite, displayScope, taskFor } = toolkit
741
- // The pre-0.9 promote, offered for the deprecated `promote` alias's legacy
742
- // path (src/tools/index.js captures it, never registers it twice): it
743
- // revokes a 0.8 share exactly as before, local mode included.
744
- registerPromote(editor, toolkit)
745
-
856
+ const { text, fail, log, scope, scopeFor, resolvePrivateSpace, displayScope, taskFor } = toolkit
746
857
  editor.add({
747
858
  name: "remember",
748
859
  description:
749
- "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.",
750
861
  input: {
751
862
  type: "object",
752
863
  properties: {
753
864
  content: {
754
865
  type: "string",
755
866
  description:
756
- '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",
757
868
  },
758
869
  kind: {
759
870
  type: "string",
760
871
  enum: [...KINDS],
761
872
  description:
762
- "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)",
763
874
  },
764
875
  why: {
765
876
  type: "string",
766
- 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",
767
878
  },
768
879
  links: {
769
880
  type: "array",
770
881
  items: { type: "string" },
771
- 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`,
772
883
  },
773
884
  supersedes: {
774
885
  type: "array",
775
886
  items: { type: "string" },
776
- 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`,
777
888
  },
778
889
  stated_by: {
779
890
  type: "string",
780
891
  enum: ["person", "agent"],
781
- description:
782
- "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",
783
893
  },
784
894
  task: TASK_INPUT,
785
- 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" },
786
- 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" },
787
896
  },
788
897
  required: ["content", "kind"],
789
898
  additionalProperties: false,
@@ -805,10 +914,15 @@ export function registerRemember(editor, toolkit) {
805
914
  // The why is stored with the fact, so it passes the same guard.
806
915
  const why = String(input?.why ?? "").trim()
807
916
  const whyRefusal = why ? writeRefusal(why) : ""
808
- if (whyRefusal) return text(`not stored (why): ${whyRefusal.replace(/^not stored: /, "")}`)
809
- // Who stated it: the routines' policy treats the person's own statement
810
- // differently from the agent's conclusion, so it is the caller's to say.
811
- 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"
812
926
  const links = idList(input?.links)
813
927
  if (links.length > MAX_LINKS) return text(`not stored: links takes at most ${MAX_LINKS} paths or ids.`)
814
928
  const badLinks = links.filter((link) => !PAGE_PATH.test(link) && !RECORD_ID.test(link))
@@ -830,8 +944,10 @@ export function registerRemember(editor, toolkit) {
830
944
  const task = taskFor(input, context)
831
945
  if (task.invalid) return text(`not stored: ${task.invalid}`)
832
946
 
833
- const visibility = normalizeVisibility(input?.visibility, "private")
834
- 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)
835
951
  if (resolved.invalid) return text(resolved.invalid)
836
952
  if (resolved.error) return fail(resolved.error)
837
953
  const spaceContext = resolved.context
@@ -856,42 +972,32 @@ export function registerRemember(editor, toolkit) {
856
972
  type: kind,
857
973
  title: titleFrom(content),
858
974
  body,
859
- stated_by: statedBy,
975
+ // A held write carries the claim: the person reads and approves it in the Inbox.
976
+ stated_by: claimed,
860
977
  ...(links.length > 0 ? { fields: { links } } : {}),
861
978
  ...(recordIDs.length > 0 ? { supersedes: recordIDs } : {}),
862
979
  source: context?.sessionID ? { session: String(context.sessionID) } : {},
863
980
  ...(task.key ? { task: task.key } : {}),
864
981
  }
865
982
 
866
- if (visibility === "team" && toolkit.config.heldTeamWrites) {
867
- if (atomIDs.length) return text("not held: legacy atom supersession cannot be applied transactionally. Nothing was stored.")
868
- try {
869
- return text(await holdTeamWrite(toolkit, context, spaceContext, [record]))
870
- } catch (error) {
871
- if (error?.outcomeUnknown) return fail(errorMessage(error))
872
- return fail(`held write was not confirmed: ${errorMessage(error)}`)
873
- }
874
- }
875
- if (visibility === "team") {
876
- try {
877
- await assertTeamWrite(context, "memory.remember", [spaceContext?.space_id ?? "team", ...supersedes], {
878
- kind,
879
- visibility,
880
- ...(spaceContext?.space_name ? { space_name: oneLine(spaceContext.space_name, 200) } : {}),
881
- ...(spaceContext?.space_id ? { space_id: spaceContext.space_id } : {}),
882
- excerpt: oneLine(redactSecrets(content), 400),
883
- ...(supersedes.length > 0 ? { supersedes } : {}),
884
- })
885
- } catch (error) {
886
- return text(`remembering to the team denied: ${errorMessage(error)}. Nothing was stored.`)
887
- }
888
- }
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]
889
994
 
890
995
  let stored
891
996
  try {
892
997
  stored = (await callRecords(toolkit, "records.put", { record }, spaceContext, scoped))?.record
893
998
  } catch (error) {
894
999
  log.warn("remember failed", error)
1000
+ if (!error?.outcomeUnknown) await core?.dropKept(keep, spaceContext, scoped)
895
1001
  if (error?.outcomeUnknown) return fail(errorMessage(error))
896
1002
  const refused = notWritten(error, "stored")
897
1003
  if (refused) return text(refused)
@@ -904,20 +1010,22 @@ export function registerRemember(editor, toolkit) {
904
1010
  const id = String(stored?.id ?? "")
905
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.")
906
1012
  noteRecordSpace(toolkit, id, spaceContext)
907
- 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 })
908
1014
 
909
1015
  const lines = [
910
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.`,
911
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.")
912
1024
  if (recordIDs.length > 0) {
913
- 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))
914
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.`)
915
1027
  }
916
- if (atomIDs.length > 0) {
917
- const unscoped = spaceContext ? scopeFor(spaceContext, { agent: context?.agent }) : scope({ agent: context?.agent })
918
- const { session_id: _session, task_id: _task, ...base } = unscoped
919
- lines.push(await createCoreForget(toolkit).supersedeAtoms(atomIDs, spaceContext, base))
920
- }
1028
+ if (core) lines.push(await core.supersedeAtoms(keep, id, spaceContext, base))
921
1029
  lines.push(`To change it later: mem_revise {"action": "correct", "id": "${id}", "content": "…"}; to drop it: {"action": "retire", "id": "${id}"}.`)
922
1030
  return text(lines.join("\n"))
923
1031
  },
@@ -929,8 +1037,9 @@ export function registerRemember(editor, toolkit) {
929
1037
  * new record that supersedes the old one, which is kept; `confirm`, `retire`
930
1038
  * and `restore` change its status; `history` shows its versions and lineage;
931
1039
  * `forget` deletes it for good and always asks `memory.forget`. An `m_` or
932
- * `msg-` id is forgotten in the core as mem_forget does, and `correct` on an
933
- * `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).
934
1043
  *
935
1044
  * A change to a record in a shared space asks `memory.revise`.
936
1045
  *
@@ -938,12 +1047,7 @@ export function registerRemember(editor, toolkit) {
938
1047
  * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
939
1048
  */
940
1049
  export function registerRevise(editor, toolkit) {
941
- const { text, fail, log, scope, scopeFor, resolveReadSpace, assertTeamWrite, displayScope, taskFor, forgetLocations } = toolkit
942
- // The pre-0.9 forget, offered for the deprecated `forget` alias's legacy
943
- // path (src/tools/index.js captures it, never registers it twice): it keeps
944
- // the persona and scenario phrase erase (match), which revise does not take.
945
- registerForget(editor, toolkit)
946
-
1050
+ const { text, fail, log, scope, scopeFor, resolveReadSpace, assertTeamWrite, gateWrite, displayScope, taskFor, forgetLocations } = toolkit
947
1051
  /**
948
1052
  * The space a revise acts in: where this process last saw the id (recall,
949
1053
  * remember, page), else the session's (personal, or a bound shared one).
@@ -980,36 +1084,53 @@ export function registerRevise(editor, toolkit) {
980
1084
  editor.add({
981
1085
  name: "revise",
982
1086
  description:
983
- '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.",
984
1088
  input: {
985
1089
  type: "object",
986
1090
  properties: {
987
1091
  action: {
988
1092
  type: "string",
989
1093
  enum: [...REVISE_ACTIONS],
990
- 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\"}",
991
1095
  },
992
- id: { type: "string", description: "Required: the record id (rec_…); forget also takes the core's m_… and msg-… ids" },
993
- content: { type: "string", description: "correct only: the corrected memory, whole, as it should come back" },
994
- 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" },
995
1105
  },
996
- required: ["action", "id"],
1106
+ required: ["action"],
997
1107
  additionalProperties: false,
998
1108
  },
999
1109
  options: { namespace: "mem" },
1000
1110
  execute: async (input, context) => {
1001
1111
  const verb = String(input?.action ?? "")
1002
1112
  if (!REVISE_ACTIONS.includes(verb)) return text(`action is required: one of ${REVISE_ACTIONS.join(", ")}. Example: {"action": "history", "id": "rec_..."}`)
1003
- const ids = idList(input?.id)
1004
- 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.`)
1005
1121
  const id = ids[0]
1122
+ const fingerprint = verb === "restore" && ids.some((value) => FORGOTTEN_ID.test(value))
1006
1123
  // A record id, a turn id, or else the core's atom id (m_… on the
1007
1124
  // deployed core; other cores mint other shapes), as supersedes takes it.
1008
1125
  const unknown = ids.filter((value) => !RECORD_ID.test(value) && !CORE_ID.test(value))
1009
1126
  if (unknown.length > 0) {
1010
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.`)
1011
1128
  }
1012
- if (verb !== "forget" && !RECORD_ID.test(id) && !(verb === "correct" && !TURN_ID.test(id))) {
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
+ }
1133
+ if (verb !== "forget" && !fingerprint && !RECORD_ID.test(id) && !(verb === "correct" && !TURN_ID.test(id))) {
1013
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.`)
1014
1135
  }
1015
1136
  // Every refusal before any request.
@@ -1031,7 +1152,10 @@ export function registerRevise(editor, toolkit) {
1031
1152
  const kind = "fact"
1032
1153
  const task = taskFor({}, context)
1033
1154
 
1034
- 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)
1035
1159
  if (resolved.invalid) return text(resolved.invalid)
1036
1160
  if (resolved.error) return fail(resolved.error)
1037
1161
  const spaceContext = resolved.context
@@ -1047,25 +1171,44 @@ export function registerRevise(editor, toolkit) {
1047
1171
  const data = await callRecords(toolkit, "records.history", { id }, spaceContext, scoped)
1048
1172
  return text(renderHistory(id, data))
1049
1173
  }
1050
- if (verb === "forget") return text(await forget({ ids, context, spaceContext, scoped, label }))
1051
-
1052
- if (shared) {
1053
- try {
1054
- await assertTeamWrite(context, "memory.revise", [spaceContext.space_id, id], {
1055
- revise: verb,
1056
- ...(content ? { excerpt: redactSecrets(oneLine(content, 400)) } : {}),
1057
- ...(reason ? { reason: oneLine(reason, 200) } : {}),
1058
- })
1059
- } catch (error) {
1060
- return text(`revising team memory denied: ${errorMessage(error)}. Nothing changed.`)
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.`)
1061
1182
  }
1062
1183
  }
1184
+ if (verb === "forget") return text(await forget({ ids, context, spaceContext, scoped, label }))
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.`)
1063
1196
 
1064
1197
  if (verb === "correct" && !RECORD_ID.test(id)) {
1065
- 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 } : {}) }
1066
- const stored = (await callRecords(toolkit, "records.put", { record }, spaceContext, scoped))?.record
1198
+ // The atom's text is kept as a record the correction supersedes, as remember's supersedes does.
1199
+ const core = createCoreForget(toolkit)
1067
1200
  const { session_id: _session, task_id: _task, ...base } = scoped
1068
- const removed = await createCoreForget(toolkit).supersedeAtoms([id], spaceContext, base)
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
1205
+ try {
1206
+ stored = (await callRecords(toolkit, "records.put", { record }, spaceContext, scoped))?.record
1207
+ } catch (error) {
1208
+ if (!error?.outcomeUnknown) await core.dropKept(keep, spaceContext, scoped)
1209
+ throw error
1210
+ }
1211
+ const removed = await core.supersedeAtoms(keep, stored?.id, spaceContext, base)
1069
1212
  return text(`corrected atom ${oneLine(id, 80)} as ${stored?.id} (memory/${kind}) in ${label}; mem_recall finds it now.\n${removed}`)
1070
1213
  }
1071
1214
 
@@ -1080,7 +1223,7 @@ export function registerRevise(editor, toolkit) {
1080
1223
  const scan = await createCoreForget(toolkit).scanCopies({ texts: [factOf(old)], spaceContext, base })
1081
1224
  const atoms = scan.copies.filter((row) => row.layer === "l1")
1082
1225
  correctionWarning = atoms.length
1083
- ? `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.`
1084
1227
  : "Old atoms and turns may still appear in recall; provenance and the bounded scan cannot rule out stale conflicts."
1085
1228
  if (scan.windows.some((window) => !window.listing.complete)) correctionWarning += " The core scan was incomplete."
1086
1229
  } catch (error) {
@@ -1111,6 +1254,91 @@ export function registerRevise(editor, toolkit) {
1111
1254
  },
1112
1255
  })
1113
1256
 
1257
+ /**
1258
+ * Showing again the copies a forget withholds undoes the forget in recall.
1259
+ * Only the person does that, in Memory's console, in a browser session: the
1260
+ * records service refuses `forgotten.lift` to every key and token, so the
1261
+ * plugin does not call it, and says where it is done.
1262
+ */
1263
+ function restoreCopies() {
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."
1265
+ }
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
+
1114
1342
  /** The fact a memory record states: its body before "Why:", else its title. */
1115
1343
  function factOf(record) {
1116
1344
  const body = String(record?.body ?? "").split(/\n\s*\nWhy:/)[0].trim()
@@ -1119,7 +1347,7 @@ export function registerRevise(editor, toolkit) {
1119
1347
 
1120
1348
  /**
1121
1349
  * Forget (EVAL's gate, contract §4.1): records by id with `records.delete`,
1122
- * 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
1123
1351
  * fact was said in and the core extracts atoms from it, so deleting a record
1124
1352
  * alone leaves the fact recallable: the core's copies of each record's fact
1125
1353
  * (atoms and turns that hold it, docs/design/adr-forget-copies.md) are found
@@ -1147,17 +1375,50 @@ export function registerRevise(editor, toolkit) {
1147
1375
  const facts = records.map(factOf).filter(Boolean)
1148
1376
  const scan = facts.length > 0 ? await core.scanCopies({ texts: facts, spaceContext, base, exclude: new Set(coreIDs) }) : { copies: [], windows: [], forgotten: [] }
1149
1377
  const copyIDs = scan.copies.map((row) => row.id)
1150
- 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
+ }
1151
1400
  const ask = (more = []) =>
1152
1401
  assertTeamWrite(context, "memory.forget", [...ids, ...copyIDs, ...more], { ...metadata, ...(more.length > 0 ? { remember_rows: more.length } : {}) })
1153
1402
 
1154
1403
  const parts = []
1155
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
1156
1411
  if (coreIDs.length > 0) {
1157
- 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) })
1158
1413
  if (deleted.denied) return `forgetting denied: ${deleted.denied}. Nothing was deleted.`
1159
1414
  parts.push(`deleted ${deleted.total} core item(s) (${deleted.removed.l1} l1 atom(s), ${deleted.removed.l0} l0 turn(s)).`, ...deleted.lines)
1415
+ parts.push(...(await fingerprintForgottenAtoms(toolkit, deleted, spaceContext, scoped)))
1160
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))
1161
1422
  for (const row of deleted.forgottenRows ?? []) {
1162
1423
  if (!row.content) {
1163
1424
  parts.push(`Record copies of ${oneLine(row.id, 80)} were not searched: its text was unavailable.`)
@@ -1181,21 +1442,37 @@ export function registerRevise(editor, toolkit) {
1181
1442
  }
1182
1443
 
1183
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 = ""
1184
1449
  if (records.length > 0) {
1185
1450
  let data
1186
1451
  let deleteUnknown = false
1452
+ const recordList = records.map((record) => record.id)
1187
1453
  try {
1188
- 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
+ }
1189
1463
  } catch (error) {
1190
1464
  data = {}
1191
1465
  deleteUnknown = error?.outcomeUnknown === true
1192
1466
  parts.push(`Record delete failed (${errorMessage(error)}); the record(s) remain unconfirmed. Any core deletions above already happened.`)
1193
1467
  }
1194
- 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)
1195
1471
  if (gone.length > 0) {
1196
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.`)
1197
1473
  }
1198
- 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))
1199
1476
  if (undeleted.length > 0 && !deleteUnknown) parts.push(`The records service did not delete ${undeleted.join(", ")}.`)
1200
1477
  }
1201
1478
  if (missing.length > 0) parts.push(`Not found, so not deleted: ${missing.join(", ")} (pass ids from mem_recall in this space).`)
@@ -1220,656 +1497,72 @@ export function registerRevise(editor, toolkit) {
1220
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)}.`)
1221
1498
  else if (scan.copies.length === 0) parts.push("No candidate copy of the fact was found in the rows actually scanned.")
1222
1499
  if (copies.kept.length > 0) parts.push(`Not deleted: ${copies.kept.map((row) => `${row.layer} ${oneLine(row.id, 80)} (${row.why})`).join("; ")}.`)
1223
- 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")
1502
+
1503
+ // The kept copies stay in the core until the person consents, and the
1504
+ // forget's own reply may copy the fact again: a fingerprint makes every
1505
+ // later recall withhold all of them from this person.
1506
+ const printLines = []
1507
+ for (const record of goneRecords) {
1508
+ const fact = factOf(record)
1509
+ if (!fact) continue
1510
+ const kind = MEMORY_TYPES.includes(record.type) ? record.type : "fact"
1511
+ const features = [copyFeatures(fact)]
1512
+ const copiesKept = copies.kept.filter((row) => {
1513
+ const parts = rememberParts(row.content)
1514
+ return matchCopy(features, parts.kind === "wrapper" ? `${parts.body}\n${parts.reason}` : row.content)
1515
+ }).length
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.`)
1525
+ }
1224
1526
 
1225
- // 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.
1226
1529
  const back = { records: [], core: { left: [], failed: false }, recordsFailed: false }
1227
- 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) {
1228
1534
  try {
1229
1535
  const hits = (await callRecords(toolkit, "records.search", { query: oneLine(fact, 200), status: "all", limit: 20 }, spaceContext, scoped))?.hits ?? []
1230
- 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))
1231
1537
  } catch {
1232
1538
  back.recordsFailed = true
1233
1539
  }
1234
1540
  }
1235
- back.core = await core.remainingCopies({ texts: facts, forgotten: scan.forgotten, base })
1541
+ back.core = await core.remainingCopies({ texts: readBack, forgotten: scan.forgotten, base })
1236
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)}`))
1237
- 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.")
1238
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.")
1239
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.`)
1240
1547
  }
1241
- log.info("revise forget", { records: gone.length, core: coreIDs.length, copies: copyIDs.length })
1242
- 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.")
1243
- return [parts.join(" "), report].filter(Boolean).join("\n")
1244
- }
1245
- }
1246
-
1247
- /**
1248
- * The pre-0.9 `mem_forget`: core ids and the L2/L3 phrase erase. Kept for the
1249
- * alias PLUG-B registers ("Deprecated: use mem_revise forget").
1250
- *
1251
- * @param {any} editor
1252
- * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
1253
- */
1254
- export function registerForget(editor, toolkit) {
1255
- const { text, fail, log, scope, scopeFor, resolveWriteSpace, assertTeamWrite, displayScope, taskFor } = toolkit
1256
- const { deleteByIds, eraseSummaries } = createCoreForget(toolkit)
1257
-
1258
- editor.add({
1259
- name: "forget",
1260
- description:
1261
- "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.",
1262
- input: {
1263
- type: "object",
1264
- properties: {
1265
- ids: {
1266
- type: "array",
1267
- items: { type: "string" },
1268
- description: 'L0/L1 ids from mem_recall or mem_remember. Pass ids or match (one is needed). Example: {"ids": ["m_...", "msg-..."]}',
1269
- },
1270
- layer: {
1271
- type: "string",
1272
- enum: ["all", "l0", "l1", "l2", "l3"],
1273
- description: "all (default); l0/l1 for ids; l2/l3 for match",
1274
- },
1275
- match: {
1276
- type: "string",
1277
- 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"}`,
1278
- },
1279
- confirm: { type: "boolean", description: "Apply the match erase (default: preview only, nothing deleted)" },
1280
- agent: { type: "string", description: "The agent that wrote the ids, if not this session's agent" },
1281
- task: { type: "string", description: "Declares the session task, as in mem_recall; deletes are not narrowed by task" },
1282
- visibility: { type: "string", enum: ["private", "team"] },
1283
- space: { type: "string", description: "Space id containing the records (control plane); defaults to your personal or session-bound shared space" },
1284
- },
1285
- additionalProperties: false,
1286
- },
1287
- options: { namespace: "mem" },
1288
- execute: async (input, context) => {
1289
- const ids = Array.isArray(input?.ids) ? [...new Set(input.ids.map(String).map((id) => id.trim()).filter(Boolean))] : []
1290
- const match = String(input?.match ?? "").trim()
1291
- const layer = ["all", "l0", "l1", "l2", "l3"].includes(String(input?.layer)) ? String(input.layer) : "all"
1292
- if (ids.length === 0 && !match) return text("nothing to forget: pass ids, or match with layer l2, l3, or all")
1293
- if (match && match.length < MIN_ERASE_CHARS) {
1294
- return text(`match needs at least ${MIN_ERASE_CHARS} characters, so it cannot erase unrelated lines.`)
1295
- }
1296
- if (match && (layer === "l0" || layer === "l1")) {
1297
- return text("match erases lines from the L2 scenarios and the L3 persona; use ids for l0 and l1.")
1298
- }
1299
- if (ids.length > 0 && (layer === "l2" || layer === "l3")) {
1300
- return text("ids delete l0 and l1 records; use match for l2 and l3.")
1301
- }
1302
- // Declares the session's task like the other tools. A delete never sends
1303
- // it: ids are exact, and a task filter would make a delete of a record
1304
- // found by a space-wide recall silently match nothing.
1305
- const task = taskFor(input, context)
1306
- if (task.invalid) return text(task.invalid)
1307
- const visibility = normalizeVisibility(input?.visibility, "private")
1308
- const resolved = await resolveWriteSpace(input, context, visibility)
1309
- if (resolved.invalid) return text(resolved.invalid)
1310
- if (resolved.error) return fail(resolved.error)
1311
- const spaceContext = resolved.context
1312
- const scoped = spaceContext
1313
- ? scopeFor(spaceContext, { sessionID: context?.sessionID, agent: context?.agent })
1314
- : scope({ sessionID: context?.sessionID, agent: context?.agent })
1315
- const label = displayScope(spaceContext, scoped)
1316
-
1317
- const preview = Boolean(match) && input?.confirm !== true
1318
- // Forget asks (D17): a delete cannot be undone, so the call asserts the
1319
- // tool's own permission before anything is deleted, and the plugin's
1320
- // default rule (src/permissions.js) or Jelly's declared `ask` makes the
1321
- // host ask. A preview deletes nothing and does not ask.
1322
- if (!preview) {
1323
- try {
1324
- await toolkit.assert({
1325
- sessionID: context?.sessionID,
1326
- agent: context?.agent,
1327
- source: { type: "tool", messageID: context?.messageID, id: context?.id },
1328
- action: FORGET_PERMISSION,
1329
- resources: [visibility],
1330
- save: [visibility],
1331
- metadata: { visibility, layer, space: label, ...(ids.length > 0 ? { ids: ids.length } : {}), ...(match ? { erase: true } : {}) },
1332
- })
1333
- } catch (error) {
1334
- return text(`forgetting denied: ${errorMessage(error)}. Nothing was deleted.`)
1335
- }
1336
- }
1337
- const approvalMetadata = { layer, space: spaceContext?.space_id ?? "team", ...(match ? { erase: true } : {}) }
1338
- // An id delete asks once it knows every row it will delete: the named ids
1339
- // and the mem_remember rows that hold only their text. Nothing is
1340
- // deleted before the answer, and a denial deletes nothing.
1341
- const approve =
1342
- visibility === "team" && !preview && ids.length > 0
1343
- ? (ownIDs) =>
1344
- assertTeamWrite(context, "memory.forget", [...ids, ...ownIDs], {
1345
- ...approvalMetadata,
1346
- ...(ownIDs.length > 0 ? { remember_rows: ownIDs.length } : {}),
1347
- })
1348
- : undefined
1349
- if (visibility === "team" && !preview && ids.length === 0) {
1350
- try {
1351
- await assertTeamWrite(context, "memory.forget", [spaceContext?.space_id ?? "team"], approvalMetadata)
1352
- } catch (error) {
1353
- return text(`forgetting team memory denied: ${errorMessage(error)}`)
1354
- }
1355
- }
1356
-
1357
- // The caller's session is never the scope of a delete: each row is
1358
- // addressed under the agent and session it was written with.
1359
- const { session_id: _session, ...base } = scoped
1360
- const explicitAgent = String(input?.agent ?? "").trim()
1361
- const idLayers = ids.length === 0 ? [] : layer === "all" ? ["l1", "l0"] : [layer]
1362
- const textLayers = !match ? [] : layer === "all" ? ["l3", "l2"] : [layer]
1363
- const textScope = { ...base, agent_id: explicitAgent || base.agent_id }
1364
- const footer =
1365
- "Not erased or verified by this call: other spaces and agents, wiki pages, raw logs and backups."
1366
-
1367
- try {
1368
- if (preview) {
1369
- const erase = await eraseSummaries({ phrase: match, layers: textLayers, apply: false, scope: textScope })
1370
- const pendingIDs = ids.length > 0 ? ` ${ids.length} id(s) would also be deleted from ${idLayers.join("/")}.` : ""
1371
- return text(
1372
- `${erase.text}\nNothing was deleted from ${label}.${pendingIDs} To apply, call mem_forget again with the same arguments and confirm: true.`,
1373
- )
1374
- }
1375
-
1376
- const parts = []
1377
- let deleted = null
1378
- let report = ""
1379
- if (ids.length > 0) {
1380
- // A suggested follow-up delete must address the same space.
1381
- const retryArgs = {
1382
- ...(visibility === "team" ? { visibility: "team" } : {}),
1383
- ...(String(input?.space ?? "").trim() ? { space: String(input.space).trim() } : {}),
1384
- }
1385
- deleted = await deleteByIds({ ids, wanted: idLayers, spaceContext, base, explicitAgent, approve, retryArgs })
1386
- if (deleted.denied) return text(`forgetting team memory denied: ${deleted.denied}`)
1387
- if (deleted.fatal && !match) {
1388
- log.warn("forget failed", deleted.fatal)
1389
- return fail(deleted.fatal)
1390
- }
1391
- parts.push(
1392
- `deleted ${deleted.total} item(s) from ${label} (${idLayers.map((name) => `${deleted.removed[name]} ${name}`).join(" and ")}).`,
1393
- ...deleted.lines,
1394
- )
1395
- report = deleted.report
1396
- }
1397
- const head = parts.splice(0, parts.length).join(" ")
1398
- if (match) {
1399
- const erase = await eraseSummaries({ phrase: match, layers: textLayers, apply: true, scope: textScope })
1400
- parts.push(`Erase of "${neutralizeFenceClosers(oneLine(match, 80))}" from ${textLayers.join("/")} in ${label}:`, erase.text)
1401
- parts.push(
1402
- ids.length > 0
1403
- ? "The next consolidation rebuilds L2/L3 from the remaining atoms, so an atom that still holds the phrase can bring it back."
1404
- : "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.",
1405
- )
1406
- } else {
1407
- parts.push("An id delete does not change the L2 scenarios or the L3 persona; use match to erase a phrase there.")
1408
- }
1409
- parts.push(footer)
1410
- log.info("forget", { removed: deleted?.removed ?? null, erase: Boolean(match), copies: Boolean(report) })
1411
- return text([head, report, parts.join(" ")].filter(Boolean).join("\n"))
1412
- } catch (error) {
1413
- log.warn("forget failed", error)
1414
- return fail(errorMessage(error))
1415
- }
1416
- },
1417
- })
1418
- }
1419
-
1420
- /**
1421
- * The pre-0.9 `mem_promote`: copy private memory into a shared space as one
1422
- * wiki, and revoke such a copy. Kept for the alias (`share` copy replaces it).
1423
- *
1424
- * @param {any} editor
1425
- * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
1426
- */
1427
- export function registerPromote(editor, toolkit) {
1428
- const { backend, control, text, fail, log, scope, scopeFor, displayScope, locate, knownAgents } = toolkit
1429
-
1430
- /**
1431
- * Read the text of private L1 atoms and L0 turns by id, for a share. Each id
1432
- * is looked up in the caller's personal space only, newest rows first, under
1433
- * the agents that wrote it (as mem_forget locates ids). The L0 text of a
1434
- * mem_remember turn drops its "Please remember this … for later:" wrapper.
1435
- */
1436
- async function readPrivateRecords({ ids, spaceContext, base }) {
1437
- const found = new Map()
1438
- const pending = () => ids.filter((id) => !found.has(id))
1439
- const agents = [
1440
- ...new Set(
1441
- [...ids.map((id) => locate(spaceContext, id)?.agent_id), base.agent_id, ...knownAgents(spaceContext)].filter(Boolean),
1442
- ),
1443
- ].slice(0, 4)
1444
- let failed = false
1445
- for (const layer of ["l1", "l0"]) {
1446
- for (const agent of agents) {
1447
- for (let page = 0; page < SCAN_PAGES && pending().length > 0; page += 1) {
1448
- const listScope = { ...base, agent_id: agent }
1449
- let data
1450
- try {
1451
- data =
1452
- layer === "l0"
1453
- ? await backend.queryConversations({ scope: listScope, limit: SCAN_PAGE, offset: page * SCAN_PAGE })
1454
- : await backend.queryAtoms({ scope: listScope, limit: SCAN_PAGE, offset: page * SCAN_PAGE })
1455
- } catch {
1456
- failed = true
1457
- break
1458
- }
1459
- const rows = (layer === "l0" ? (data?.messages ?? data?.items) : (data?.items ?? data?.records)) ?? []
1460
- for (const row of rows) {
1461
- const id = String(row?.id ?? "")
1462
- if (!ids.includes(id) || found.has(id)) continue
1463
- const raw = String(row?.content ?? row?.text ?? "").trim()
1464
- found.set(id, { id, layer, text: layer === "l0" ? raw.replace(REMEMBER_WRAPPER, "").trim() : raw })
1465
- }
1466
- if (rows.length < SCAN_PAGE) break
1467
- }
1468
- }
1469
- }
1470
- return { found, failed, agents }
1471
- }
1472
-
1473
- /** The Markdown a share holds: a marker, the provenance, then the copied text. */
1474
- function shareDocument({ key, label, sharer, at, space, rationale, records }) {
1475
- const lines = [
1476
- SHARE_MARKER,
1477
- `# Shared memory: ${label}`,
1478
- "",
1479
- "A copy of private memory, shared on request. It does not change when the originals change. Revoking the share deletes this wiki.",
1480
- "",
1481
- "| Field | Value |",
1482
- "|---|---|",
1483
- `| Share key | \`${key}\` |`,
1484
- `| Shared by | \`${sharer}\` |`,
1485
- `| Shared at | ${at} |`,
1486
- `| Space | \`${space}\` |`,
1487
- `| Sources | ${records.map((record) => `\`${record.layer}:${oneLine(record.id, 120)}\``).join(", ")} |`,
1488
- "",
1489
- `Rationale: ${oneLine(rationale, 500)}`,
1490
- "",
1491
- "## Copied memory",
1492
- ]
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.
1493
1551
  for (const record of records) {
1494
- lines.push("", `### ${record.layer} \`${oneLine(record.id, 120)}\``, "", record.text)
1495
- }
1496
- return `${lines.join("\n")}\n`
1497
- }
1498
-
1499
- /**
1500
- * Is this wiki a share? "share" when SHARE.md carries the marker, "other"
1501
- * when the wiki exists without it, "absent" when the wiki is already gone
1502
- * (a retry after a partial revoke), or `{ error }`.
1503
- */
1504
- async function shareState(scope, wikiID) {
1505
- try {
1506
- const raw = await backend.readWikiRaw({ scope, wikiID, filenames: [SHARE_FILE] })
1507
- const item = (raw?.items ?? []).find((entry) => entry?.filename === SHARE_FILE)
1508
- return String(item?.content ?? "").startsWith(SHARE_MARKER) ? "share" : "other"
1509
- } catch (error) {
1510
- if (Number(error?.status) === 404) return "absent"
1511
- return { error: errorMessage(error) }
1512
- }
1513
- }
1514
-
1515
- /**
1516
- * Read a revoked share back. Gone means the gateway refuses the id (the
1517
- * catalog row is deleted) or the cell no longer has it.
1518
- */
1519
- async function readBack(scope, wikiID) {
1520
- try {
1521
- await backend.getWiki({ scope, wikiID })
1522
- return { gone: false, text: `Read back: wiki ${oneLine(wikiID, 120)} is still readable.` }
1523
- } catch (error) {
1524
- const status = Number(error?.status)
1525
- if (status === 403 || status === 404) {
1526
- return { gone: true, text: `Read back: wiki ${oneLine(wikiID, 120)} is no longer reachable (${status}).` }
1527
- }
1528
- return { gone: null, text: `Read back failed (${errorMessage(error)}).` }
1529
- }
1530
- }
1531
-
1532
- /**
1533
- * The shared space a share is made in, or revoked from: passed explicitly,
1534
- * or bound to the session. Sharing also needs editor access; a revoke
1535
- * leaves the decision to control (owner or space admin).
1536
- */
1537
- async function resolveShareSpace(input, context, { write }) {
1538
- const requested = String(input?.space ?? "").trim()
1539
- if (!control) {
1540
- if (requested) return { message: "control plane not configured; set MEMORY_CONTROL_URL to select a space" }
1541
- return { spaceContext: null, scoped: scope({ sessionID: context?.sessionID, agent: context?.agent }) }
1552
+ if (!gone.includes(record.id)) continue
1553
+ purgeTexts.push(String(record.title ?? ""), factOf(record), String(record.body ?? "").replace(/^\s*why\s*:\s*/gim, ""))
1542
1554
  }
1543
- // An explicit space applies to this call only. A space and a session sent
1544
- // together bind the session to that space (control's context route, and
1545
- // the gateway for a data-plane call with both hints), so the next plain
1546
- // recall searched the team space: neither is sent with the session here.
1547
- let spaceContext
1548
- try {
1549
- spaceContext = await toolkit.resolveContext({
1550
- space: requested || undefined,
1551
- sessionID: requested ? undefined : context?.sessionID,
1552
- agent: context?.agent,
1553
- })
1554
- } catch (error) {
1555
- return { error: errorMessage(error) }
1556
- }
1557
- if (!spaceContext) return { error: "the control plane returned no space context" }
1558
- if (spaceContext.space_kind !== "shared") {
1559
- return {
1560
- message: requested
1561
- ? `mem_promote cannot use personal space ${oneLine(spaceContext.space_id || "personal", 80)}; pass a shared space.`
1562
- : "no shared space is bound to this session; pass a shared space with the space argument.",
1563
- }
1564
- }
1565
- if (!requested && !toolkit.isSessionBound(spaceContext)) {
1566
- return { message: "the active shared space is not bound to this session; pass a shared space with the space argument." }
1567
- }
1568
- if (write) {
1569
- const role = String(spaceContext.role ?? "").trim().toLowerCase()
1570
- if (!canWriteShared(role)) {
1571
- return {
1572
- message: `sharing requires editor access to ${oneLine(spaceContext.space_id, 80)}; the control plane reports role ${role || "unknown"}.`,
1573
- }
1574
- }
1575
- }
1576
- return { spaceContext, scoped: scopeFor(spaceContext, { sessionID: requested ? undefined : context?.sessionID, agent: context?.agent }) }
1577
- }
1578
-
1579
- /** Delete a share in local mode: the wiki itself, then read it back. */
1580
- async function deleteLocalShare(scoped, wikiID) {
1581
- let data
1582
- try {
1583
- data = await backend.deleteWiki({ scope: scoped, wikiIDs: [wikiID] })
1584
- } catch (error) {
1585
- return { ok: false, text: `the cell did not delete wiki ${oneLine(wikiID, 120)} (${errorMessage(error)})` }
1586
- }
1587
- const deleted = (data?.deleted_ids ?? []).map(String).includes(wikiID)
1588
- const missing = (data?.failed ?? []).some((entry) => String(entry?.id) === wikiID && /not\s*found/i.test(String(entry?.reason ?? "")))
1589
- if (!deleted && !missing) {
1590
- return { ok: false, text: `the cell did not delete wiki ${oneLine(wikiID, 120)}` }
1591
- }
1592
- const back = await readBack(scoped, wikiID)
1593
- return { ok: back.gone === true, text: back.text }
1594
- }
1595
-
1596
- async function share(input, context) {
1597
- const ids = [...new Set((Array.isArray(input?.ids) ? input.ids : []).map((id) => String(id).trim()).filter(Boolean))]
1598
- if (ids.length === 0) return text("nothing to share: ids is empty")
1599
- if (ids.length > MAX_SHARE_IDS) return text(`not shared: at most ${MAX_SHARE_IDS} ids per share.`)
1600
- const rationale = String(input?.rationale ?? "").trim()
1601
- if (!rationale) return text("not shared: rationale is required; it is recorded on the share.")
1602
- const rationaleRefusal = writeRefusal(rationale)
1603
- if (rationaleRefusal) return text(`not shared (rationale): ${rationaleRefusal.replace(/^not stored: /, "")}`)
1604
-
1605
- const target = await resolveShareSpace(input, context, { write: true })
1606
- if (target.message) return text(target.message)
1607
- if (target.error) return fail(target.error)
1608
- const { spaceContext, scoped } = target
1609
-
1610
- // The source is always the caller's personal space: a share copies the
1611
- // caller's own private memory, never another space's.
1612
- let personal = null
1613
- if (control) {
1614
- const resolved = await toolkit.resolvePrivateSpace({}, context)
1615
- if (resolved.invalid) return text(resolved.invalid)
1616
- if (resolved.error) return fail(resolved.error)
1617
- personal = resolved.context
1618
- }
1619
- const sourceScope = personal
1620
- ? scopeFor(personal, { agent: context?.agent })
1621
- : scope({ agent: context?.agent })
1622
- const { session_id: _session, ...base } = sourceScope
1623
- const read = await readPrivateRecords({ ids, spaceContext: personal, base })
1624
- const list = (values) => values.map((id) => oneLine(id, 80)).join(", ")
1625
- const missing = ids.filter((id) => !read.found.has(id))
1626
- if (missing.length > 0) {
1627
- const where = read.failed
1628
- ? "the backend did not answer the row listing"
1629
- : `searched the newest ${SCAN_PAGE * SCAN_PAGES} l1 and l0 rows for agent(s) ${read.agents.join(", ") || "unknown"}`
1630
- return text(
1631
- `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.`,
1632
- )
1633
- }
1634
- const records = ids.map((id) => read.found.get(id))
1635
- for (const record of records) {
1636
- if (!record.text) return text(`not shared: ${oneLine(record.id, 80)} has no text. Nothing was created.`)
1637
- if (record.text.length > MAX_SHARED_CHARS) {
1638
- return text(
1639
- `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.`,
1640
- )
1641
- }
1642
- const refusal = writeRefusal(record.text)
1643
- if (refusal) return text(`not shared: ${oneLine(record.id, 80)}: ${refusal.replace(/^not stored: /, "")} Nothing was created.`)
1644
- record.text = redactSecrets(record.text)
1645
- }
1646
-
1647
- const spaceID = spaceContext?.space_id ?? "local"
1648
- try {
1649
- await toolkit.assert({
1650
- sessionID: context?.sessionID,
1651
- agent: context?.agent,
1652
- source: { type: "tool", messageID: context?.messageID, id: context?.id },
1653
- action: "memory.promote",
1654
- resources: ids,
1655
- save: [],
1656
- metadata: {
1657
- space: spaceID,
1658
- rationale,
1659
- copies: records.map((record) => `${record.layer}:${oneLine(record.id, 80)}: ${oneLine(record.text, 160)}`),
1660
- },
1661
- })
1662
- } catch (error) {
1663
- return text(`sharing denied: ${errorMessage(error)}`)
1664
- }
1665
-
1666
- const key = `share-${randomBytes(4).toString("hex")}`
1667
- const label = oneLine(input?.name, 120).trim() || oneLine(records[0].text, 60)
1668
- const wikiName = `Shared memory: ${label} [${key}]`
1669
- let wiki
1670
- try {
1671
- wiki = await backend.createWiki({ scope: scoped, name: wikiName })
1672
- } catch (error) {
1673
- log.warn("share create failed", error)
1674
- return fail(`the share could not be created (${errorMessage(error)}). Nothing was shared.`)
1675
- }
1676
- const wikiID = String(wiki?.wiki_id ?? "").trim()
1677
- if (!wikiID) return fail("wiki/create returned no wiki_id. Nothing was shared.")
1678
-
1679
- // A gateway with the create hook registered it and says so; an older one
1680
- // did not, so register explicitly (the route is idempotent).
1681
- let shareID = wikiID
1682
- if (spaceContext) {
1683
- shareID = typeof wiki?.resource_id === "string" ? wiki.resource_id.trim() : ""
1684
- if (!shareID) {
1685
- try {
1686
- const registered = await control.createResource({
1687
- userId: spaceContext.user_id || toolkit.runtime.config.user,
1688
- spaceId: spaceContext.space_id,
1689
- resource: { kind: "wiki", upstream_id: wikiID, name: wikiName },
1690
- })
1691
- shareID = String(registered?.id ?? "").trim()
1692
- } catch (error) {
1693
- return fail(
1694
- `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.`,
1695
- )
1696
- }
1697
- if (!shareID) return fail(`wiki ${wikiID} was created but registration returned no id; nothing was shared.`)
1698
- }
1699
- }
1700
-
1701
- const document = shareDocument({
1702
- key,
1703
- label,
1704
- sharer: spaceContext?.user_id || toolkit.runtime.config.user || "local",
1705
- at: new Date().toISOString(),
1706
- space: spaceID,
1707
- rationale,
1708
- records,
1709
- })
1710
- try {
1711
- await backend.writeWikiRaw({ scope: scoped, wikiID, files: [{ filename: SHARE_FILE, content: document }] })
1712
- } catch (error) {
1713
- log.warn("share write failed", error)
1714
- // Do not leave an empty share behind.
1715
- let cleanup
1716
- if (spaceContext) {
1717
- try {
1718
- await control.deleteResource({
1719
- userId: spaceContext.user_id || toolkit.runtime.config.user,
1720
- spaceId: spaceContext.space_id,
1721
- resourceId: shareID,
1722
- })
1723
- cleanup = "the empty share was deleted"
1724
- } catch (cleanupError) {
1725
- cleanup = `the empty share ${shareID} remains (${errorMessage(cleanupError)}); revoke it with mem_promote revoke`
1726
- }
1727
- } else {
1728
- const removed = await deleteLocalShare(scoped, wikiID)
1729
- cleanup = removed.ok ? "the empty share was deleted" : `the empty share ${wikiID} remains: ${removed.text}`
1730
- }
1731
- return fail(`the copy could not be written (${errorMessage(error)}); ${cleanup}. Nothing was shared.`)
1732
- }
1733
-
1734
- let ingest = ""
1735
- try {
1736
- await backend.ingestWiki({ scope: scoped, wikiID })
1737
- } catch (error) {
1738
- ingest = ` Ingestion did not start (${errorMessage(error)}): mem_wiki read shows the copy now; search finds it after ingestion.`
1739
- }
1740
- const targetLabel = spaceContext ? displayScope(spaceContext, scoped) : "the local shared scope"
1741
- log.info("share", { space: spaceID, count: ids.length })
1742
- const revokeCall = spaceContext
1743
- ? `mem_promote({ revoke: "${shareID}", space: "${oneLine(spaceContext.space_id, 80)}" })`
1744
- : `mem_promote({ revoke: "${shareID}" })`
1745
- return text(
1746
- `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}.`,
1747
- )
1748
- }
1749
-
1750
- async function revoke(input, context) {
1751
- const shareID = String(input?.revoke ?? "").trim()
1752
- if (Array.isArray(input?.ids) && input.ids.length > 0) {
1753
- return text("pass ids to share, or revoke to delete a share, not both.")
1754
- }
1755
- const target = await resolveShareSpace(input, context, { write: false })
1756
- if (target.message) return text(target.message.replace("pass a shared space", "pass the shared space the share was made in"))
1757
- if (target.error) return fail(target.error)
1758
- const { spaceContext, scoped } = target
1759
- const userId = spaceContext ? spaceContext.user_id || toolkit.runtime.config.user : ""
1760
- const refused = (error) => [400, 403, 404].includes(Number(error?.status))
1761
-
1762
- // Learn what the id names, and whether this caller may delete it, before
1763
- // anything changes.
1764
- let wikiID = shareID
1765
- if (spaceContext) {
1766
- let dry
1555
+ if (purge && (gone.length > 0 || purgeTexts.length > 0 || coreGone > 0)) {
1767
1556
  try {
1768
- 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.")
1769
1560
  } catch (error) {
1770
- return refused(error) ? text(`revoke refused: ${errorMessage(error)}`) : fail(errorMessage(error))
1561
+ log.warn("forget purge failed", errorMessage(error))
1771
1562
  }
1772
- wikiID = String(dry?.resource?.upstream_id ?? "").trim()
1773
- if (dry?.resource?.kind !== "wiki" || !wikiID) {
1774
- return text(`${oneLine(shareID, 80)} is not a share; mem_promote revoke deletes only shares. Nothing was deleted.`)
1775
- }
1776
- }
1777
- const state = await shareState(scoped, wikiID)
1778
- if (state === "other" || (!spaceContext && state === "absent")) {
1779
- return text(
1780
- state === "other"
1781
- ? `${oneLine(shareID, 80)} is not a share made by mem_promote; nothing was deleted.`
1782
- : `share ${oneLine(shareID, 80)} was not found; nothing was deleted.`,
1783
- )
1784
- }
1785
- if (typeof state === "object") return fail(`could not confirm that ${oneLine(shareID, 80)} is a share (${state.error}). Nothing was deleted.`)
1786
-
1787
- try {
1788
- await toolkit.assert({
1789
- sessionID: context?.sessionID,
1790
- agent: context?.agent,
1791
- source: { type: "tool", messageID: context?.messageID, id: context?.id },
1792
- action: "memory.promote.revoke",
1793
- resources: [shareID],
1794
- save: [],
1795
- metadata: { space: spaceContext?.space_id ?? "local", wiki: wikiID },
1796
- })
1797
- } catch (error) {
1798
- return text(`revoke denied: ${errorMessage(error)}`)
1799
- }
1800
-
1801
- const where = spaceContext ? displayScope(spaceContext, scoped) : "the local shared scope"
1802
- const tail =
1803
- "Your private originals are unchanged. Anyone who already read the share may still have it in their own memory or transcripts."
1804
- if (!spaceContext) {
1805
- const removed = await deleteLocalShare(scoped, wikiID)
1806
- log.info("share revoke", { space: "local", ok: removed.ok })
1807
- return removed.ok
1808
- ? text(`revoked share ${oneLine(shareID, 80)} in ${where}: the copy was deleted. ${removed.text} ${tail}`)
1809
- : fail(`share ${oneLine(shareID, 80)} was not revoked: ${removed.text}.`)
1810
- }
1811
-
1812
- let result
1813
- try {
1814
- result = await control.deleteResource({ userId, spaceId: spaceContext.space_id, resourceId: shareID })
1815
- } catch (error) {
1816
- log.warn("share revoke failed", error)
1817
- return refused(error) ? text(`revoke refused: ${errorMessage(error)}`) : fail(`share ${oneLine(shareID, 80)} was not revoked: ${errorMessage(error)}`)
1818
- }
1819
- if (result?.deleted !== true) return fail(`share ${oneLine(shareID, 80)} was not revoked: the gateway did not confirm the delete.`)
1820
- const back = await readBack(scoped, wikiID)
1821
- log.info("share revoke", { space: spaceContext.space_id, verified: back.gone })
1822
- if (back.gone === false) {
1823
- return fail(`share ${oneLine(shareID, 80)}: the gateway reported a delete, but ${back.text.replace(/^Read back: /, "")} Report this to an operator.`)
1824
1563
  }
1825
- return text(
1826
- `revoked share ${oneLine(shareID, 80)} in ${where}: the copy (wiki ${oneLine(wikiID, 120)}) and its catalog entry were deleted. ${back.text} ${tail}`,
1827
- )
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")
1828
1567
  }
1829
-
1830
- editor.add({
1831
- name: "promote",
1832
- description:
1833
- "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).",
1834
- input: {
1835
- type: "object",
1836
- properties: {
1837
- ids: {
1838
- type: "array",
1839
- items: { type: "string" },
1840
- description:
1841
- '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"}',
1842
- },
1843
- name: { type: "string", description: "Short name for the share" },
1844
- rationale: { type: "string", description: "Why the shared space should see this; required to share, recorded on the share" },
1845
- space: {
1846
- type: "string",
1847
- 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",
1848
- },
1849
- revoke: {
1850
- type: "string",
1851
- description: 'To revoke instead: the share id an earlier mem_promote returned; deletes that copy. Example: {"revoke": "res_...", "space": "space-team"}',
1852
- },
1853
- },
1854
- additionalProperties: false,
1855
- },
1856
- options: { namespace: "mem" },
1857
- execute: async (input, context) => {
1858
- if (String(input?.revoke ?? "").trim()) return revoke(input, context)
1859
- return share(input, context)
1860
- },
1861
- })
1862
- }
1863
-
1864
- /**
1865
- * Memory writes as registered before 0.9 (remember, forget, promote), for a
1866
- * tool index that has not moved to the 0.9 set.
1867
- *
1868
- * @param {any} editor
1869
- * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
1870
- */
1871
- export function registerMemory(editor, toolkit) {
1872
- registerRemember(editor, toolkit)
1873
- registerForget(editor, toolkit)
1874
- registerPromote(editor, toolkit)
1875
1568
  }