@joe-broadhead/opencode-mem 0.8.4 → 0.9.0

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 (52) hide show
  1. package/CHANGELOG.md +455 -0
  2. package/README.md +114 -61
  3. package/docs/agent-protocol.md +67 -177
  4. package/package.json +1351 -98
  5. package/skills/mem.pages/SKILL.md +143 -0
  6. package/skills/mem.sharing/SKILL.md +82 -0
  7. package/skills/mem.sources/SKILL.md +93 -0
  8. package/skills/mem.usage/SKILL.md +118 -492
  9. package/src/backend/records.js +285 -0
  10. package/src/bootstrap.js +49 -45
  11. package/src/call-shapes.js +41 -10
  12. package/src/collector-lock.js +162 -0
  13. package/src/collector-service.js +441 -0
  14. package/src/collector.js +381 -0
  15. package/src/commands.js +3 -3
  16. package/src/config.js +12 -1
  17. package/src/curation.js +1 -1
  18. package/src/permissions.js +18 -2
  19. package/src/protocol.js +55 -24
  20. package/src/recall.js +104 -27
  21. package/src/records-store.js +280 -120
  22. package/src/records.js +63 -11
  23. package/src/runtime.js +23 -14
  24. package/src/skills.js +44 -18
  25. package/src/sources.js +58 -0
  26. package/src/spaces.js +93 -10
  27. package/src/tools/aliases.js +163 -0
  28. package/src/tools/commitments.js +12 -9
  29. package/src/tools/index.js +88 -19
  30. package/src/tools/ingest.js +277 -0
  31. package/src/tools/knowledge.js +6 -1
  32. package/src/tools/memory.js +640 -210
  33. package/src/tools/page.js +411 -0
  34. package/src/tools/recall.js +363 -112
  35. package/src/tools/records-kit.js +142 -0
  36. package/src/tools/share.js +1012 -0
  37. package/src/tools/shared.js +8 -1
  38. package/src/tools/spaces.js +431 -143
  39. package/src/tools/status.js +87 -58
  40. package/src/tools/wiki.js +2 -2
  41. package/src/views/contracts.js +273 -3
  42. package/src/views/records-reads.js +675 -0
  43. package/src/views/rpc.js +17 -100
  44. package/src/views/shape.js +61 -0
  45. package/views/commitments.html +4 -0
  46. package/views/graph.html +753 -0
  47. package/views/home.html +11 -5
  48. package/views/journal.html +621 -0
  49. package/views/memory.html +7 -1
  50. package/views/pages.html +636 -0
  51. package/views/review.html +406 -0
  52. package/views/today.html +309 -0
@@ -15,9 +15,11 @@ import {
15
15
  readListing,
16
16
  rememberParts,
17
17
  } from "../copies.js"
18
- import { errorMessage, neutralizeFenceClosers, oneLine, redactSecrets, shortHash } from "../util.js"
18
+ import { errorMessage, neutralizeFenceClosers, oneLine, redactSecrets } from "../util.js"
19
19
  import { isCoded, withNote } from "../errors.js"
20
+ import { RecordsError } from "../backend/records.js"
20
21
  import { TASK_INPUT, canWriteShared } from "./shared.js"
22
+ import { CORE_ID, MEMORY_TYPES, PAGE_PATH, RECORD_ID, TURN_ID, callRecords, changeNote, dateOf, lineageIds, noteRecordSpace, notWritten, recordLine, recordSpace, titleFrom } from "./records-kit.js"
21
23
 
22
24
  /**
23
25
  * The permission mem_forget asserts before it deletes: the tool's own engine
@@ -27,15 +29,13 @@ import { TASK_INPUT, canWriteShared } from "./shared.js"
27
29
  */
28
30
  const FORGET_PERMISSION = "mem_forget"
29
31
 
30
- const KINDS = Object.freeze(["fact", "decision", "constraint", "preference", "procedure"])
31
- /** A supersede replaces a few atoms, not a cleanup: more is a forget. */
32
+ const KINDS = MEMORY_TYPES
33
+ /** A supersede replaces a few records, not a cleanup: more is a forget. */
32
34
  const MAX_SUPERSEDES = 10
33
- /**
34
- * Turn ids as the deployed core mints them (read from the image, 2026-11-08):
35
- * `msg-<12 hex>` for conversation/add (mem_remember's turns) and
36
- * `msg_<ms>_<hex>` for the L0 recorder. Atoms are `m_<ms>_<hex>`.
37
- */
38
- const TURN_ID = /^msg[-_]/
35
+ /** Links a memory names, at most. */
36
+ const MAX_LINKS = 20
37
+ /** The actions of mem_revise (contract §4.1). */
38
+ export const REVISE_ACTIONS = Object.freeze(["correct", "confirm", "retire", "restore", "forget", "history"])
39
39
  /**
40
40
  * One atomic fact fits in a few sentences. The cap keeps a write well inside
41
41
  * the upstream per-message limit and points long synthesis at the wiki.
@@ -67,209 +67,18 @@ const SHARE_FILE = "SHARE.md"
67
67
  const SHARE_MARKER = "<!-- opencode-mem:share v1 -->"
68
68
 
69
69
  /**
70
- * A write is queued only when the backend could not answer: no HTTP response,
71
- * a timeout, a rate limit, or a server error. A 400, 401, 403, 404, or 413 is a
72
- * decision the backend already made, and retrying it from the spool repeats
73
- * the same refusal forever while the agent is told the memory is queued.
74
- */
75
- function isTransientFailure(error) {
76
- const status = Number(error?.status)
77
- if (!Number.isFinite(status) || status === 0) return true
78
- return status >= 500 || status === 408 || status === 429
79
- }
80
-
81
- /**
82
- * Memory writes: remember, forget, and promote (share and revoke).
70
+ * The core's forget machinery, one per toolkit, shared by mem_revise (for
71
+ * `m_` and `msg-` ids) and the legacy mem_forget, so a copy reported by one is
72
+ * matched by the other (docs/design/adr-forget-copies.md).
83
73
  *
84
- * @param {any} editor
85
74
  * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
86
75
  */
87
- export function registerMemory(editor, toolkit) {
88
- const {
89
- backend,
90
- control,
91
- text,
92
- fail,
93
- log,
94
- scope,
95
- scopeFor,
96
- resolveWriteSpace,
97
- assertTeamWrite,
98
- displayScope,
99
- noteLocations,
100
- locate,
101
- forgetLocations,
102
- knownAgents,
103
- rowLocation,
104
- taskFor,
105
- } = toolkit
106
-
107
- editor.add({
108
- name: "remember",
109
- description:
110
- "Save one durable preference, constraint, decision, fact, or procedure, in the same turn it is stated and without asking; then say what was saved in one line. Capture already keeps the conversation, so this is curation: choose the kind and the wording that must come back exactly. The answer gives the stored turn's id (msg-…); the memory's atom id (m_…) appears after extraction, through mem_recall. When something known has changed, pass supersedes with the old atom's id (m_…): the old atom is removed at once, and the new one is recallable after extraction. Not for things to do (mem_commitments), where a project stands (its page's Status section, mem_wiki), file contents, tool output, or restatements of the code: a status-shaped write ('Status: …', 'half done', 'is in progress', '40% done', 'next step: …') is refused. It is tagged with the session's task; pass task \"*\" for a fact that serves the whole space. Private (the default) always writes your personal space; team needs a shared space that is selected or bound to the session, editor access, and the person's approval. Extraction is asynchronous, so a new memory may not be recallable at once.",
111
- input: {
112
- type: "object",
113
- properties: {
114
- content: {
115
- type: "string",
116
- description:
117
- 'Required: the thing to remember, stated plainly. Example: {"content": "Log timestamps are UTC", "kind": "decision", "reason": "One clock across every log"}',
118
- },
119
- task: TASK_INPUT,
120
- kind: {
121
- type: "string",
122
- enum: ["fact", "decision", "constraint", "preference", "procedure"],
123
- description: "preference for how the person likes things done, constraint for a standing rule (a lesson from a mistake is a constraint or a procedure with the incident in reason), decision for a choice and its reason, fact for a verified non-obvious truth, procedure for steps that worked (five at most). Default fact",
124
- },
125
- visibility: { type: "string", enum: ["private", "team"], description: "private (default) always writes your personal space; team shares with a selected or session-bound shared space" },
126
- reason: { type: "string", description: "Why it is worth keeping, with the source and date when known (\"agreed in the launch review, 2026-11-05\"); for a lesson, the incident" },
127
- supersedes: {
128
- type: "array",
129
- items: { type: "string" },
130
- description: `Atom ids (m_…, as mem_recall shows them) this one replaces, at most ${MAX_SUPERSEDES}. They are removed as soon as the new memory is stored; the new one is recallable after extraction, so for a short while recall finds neither. A turn id (msg-…) is not an atom: delete turns with mem_forget. Captured turns that mention the old value stay as history. Example: {"content": "Staging listens on 8788", "kind": "fact", "supersedes": ["m_..."]}`,
131
- },
132
- space: { type: "string", description: "Space id to write to (control plane); defaults to your personal or session-bound shared space" },
133
- },
134
- required: ["content"],
135
- additionalProperties: false,
136
- },
137
- options: { namespace: "mem" },
138
- execute: async (input, context) => {
139
- const content = String(input?.content ?? "").trim()
140
- const refusal = writeRefusal(content)
141
- if (refusal) return text(refusal)
142
- if (content.length > MAX_CONTENT_CHARS) {
143
- return text(
144
- `not stored: ${content.length} characters is not one atomic fact (limit ${MAX_CONTENT_CHARS}). State the decision in a sentence or two, and put long synthesis in mem_wiki.`,
145
- )
146
- }
147
- const kind = input?.kind === undefined || input?.kind === null || input?.kind === "" ? "fact" : String(input.kind)
148
- if (!KINDS.includes(kind)) return text(`not stored: kind must be one of ${KINDS.join(", ")}.`)
149
- // The reason is stored with the fact, so it passes the same guard.
150
- const reason = String(input?.reason ?? "").trim()
151
- const reasonRefusal = reason ? writeRefusal(reason) : ""
152
- if (reasonRefusal) return text(`not stored (reason): ${reasonRefusal.replace(/^not stored: /, "")}`)
153
- const supersedes = Array.isArray(input?.supersedes)
154
- ? [...new Set(input.supersedes.map((id) => String(id ?? "").trim()).filter(Boolean))]
155
- : typeof input?.supersedes === "string" && input.supersedes.trim()
156
- ? [input.supersedes.trim()]
157
- : []
158
- if (supersedes.length > MAX_SUPERSEDES) {
159
- return text(`not stored: supersedes takes at most ${MAX_SUPERSEDES} ids; to remove more, use mem_forget.`)
160
- }
161
- // A turn id (the core mints msg-… for a stored turn and msg_… for a
162
- // captured one) is not an atom: atomic/delete would answer "not found"
163
- // after the new memory was already written.
164
- const turns = supersedes.filter((id) => TURN_ID.test(id))
165
- if (turns.length > 0) {
166
- return text(
167
- `not stored: supersedes takes atom ids (m_…, as mem_recall shows them); ${turns.map((id) => oneLine(id, 80)).join(", ")} ${turns.length === 1 ? "is a turn" : "are turns"}. Pass the atom's id, or delete the turn with mem_forget.`,
168
- )
169
- }
170
- const task = taskFor(input, context)
171
- if (task.invalid) return text(`not stored: ${task.invalid}`)
172
- const visibility = normalizeVisibility(input?.visibility, "private")
173
- const resolved = await resolveWriteSpace(input, context, visibility)
174
- if (resolved.invalid) return text(resolved.invalid)
175
- if (resolved.error) return fail(resolved.error)
176
- const spaceContext = resolved.context
177
- // The task travels as the x-tdai-task-id header; upstream tags the L0
178
- // rows, and the atoms extracted from them, with it.
179
- const scoped = spaceContext
180
- ? scopeFor(spaceContext, { sessionID: context?.sessionID, agent: context?.agent, task: task.key })
181
- : scope({ sessionID: context?.sessionID, agent: context?.agent, task: task.key })
182
-
183
- if (visibility === "team") {
184
- try {
185
- await assertTeamWrite(context, "memory.remember", [spaceContext?.space_id ?? "team", ...supersedes], {
186
- kind,
187
- visibility,
188
- excerpt: redactSecrets(oneLine(content, 400)),
189
- ...(supersedes.length > 0 ? { supersedes } : {}),
190
- })
191
- } catch (error) {
192
- return text(`remembering to the team denied: ${errorMessage(error)}`)
193
- }
194
- }
195
-
196
- // The backend's extraction pipeline keys its profile off the write
197
- // session, so private, shared, and each space must never share one.
198
- // Otherwise one space's turn is extracted into another's profile.
199
- const baseSession = context?.sessionID ?? `mem-${shortHash(content)}`
200
- const sessionPrefix = spaceContext
201
- ? `space-${spaceContext.space_id || "active"}`
202
- : visibility === "private"
203
- ? "priv"
204
- : "team"
205
- const sessionID = `${sessionPrefix}-${baseSession}`
206
- const messages = [
207
- {
208
- role: "user",
209
- content: `Please remember this ${kind} for later: ${content}${reason ? `\n\nContext: ${oneLine(reason, 200)}` : ""}`,
210
- },
211
- { role: "assistant", content: `Understood. ${content}` },
212
- ]
213
-
214
- try {
215
- const data = await backend.addConversation({ sessionID, messages, scope: scoped })
216
- // The accepted rows live under this synthetic session; mem_forget needs
217
- // it to delete them. Their text is kept only when the ids map one to
218
- // one onto the messages sent.
219
- const accepted = data?.accepted_ids ?? []
220
- const paired = accepted.length === messages.length
221
- noteLocations(
222
- spaceContext,
223
- "l0",
224
- accepted.map((id, index) => (paired ? { id, content: messages[index].content } : { id })),
225
- { agent_id: scoped.agent_id, session_id: sessionID },
226
- )
227
- const label = displayScope(spaceContext, scoped)
228
- log.info("remember", { kind, visibility, scope: label, count: data?.total_count, task: Boolean(task.key), supersedes: supersedes.length })
229
- const head = `stored ${data?.total_count ?? messages.length} message(s) in ${label} ${task.key ? `for task ${task.key}` : "for the whole space"}`
230
- // The turn's id is the handle the agent has now: the atom it extracts
231
- // to has its own id, which only exists once extraction has run.
232
- const turnIDs = accepted.filter((id) => typeof id === "string" && id).map((id) => oneLine(id, 80))
233
- const stored =
234
- turnIDs.length > 0
235
- ? `${head}: the ${kind} is turn ${turnIDs[0]}${turnIDs.length > 1 ? ` (with its echo ${turnIDs.slice(1).join(", ")})` : ""}. Its atom id (m_…) appears once extraction runs (asynchronous): mem_recall finds it, and supersedes or mem_forget take that id. To remove it before then: mem_forget({ ids: ${JSON.stringify(turnIDs)} }).`
236
- : `${head}; L1 extraction runs asynchronously.`
237
- if (supersedes.length === 0) return text(stored)
238
- // A delete never carries the task or the write's session: upstream
239
- // matches a row only under its own, and the atom being replaced was
240
- // usually written in another task (as mem_forget does).
241
- const unscoped = spaceContext
242
- ? scopeFor(spaceContext, { sessionID: context?.sessionID, agent: context?.agent })
243
- : scope({ sessionID: context?.sessionID, agent: context?.agent })
244
- const { session_id: _session, task_id: _task, ...base } = unscoped
245
- return text(`${stored}\n${await supersede(supersedes, spaceContext, base)}`)
246
- } catch (error) {
247
- if (!isTransientFailure(error)) {
248
- log.warn("remember rejected by the backend", error)
249
- const message = errorMessage(error)
250
- return text(
251
- isCoded(message)
252
- ? withNote(message, "not stored, and nothing was queued")
253
- : `not stored: the backend rejected the write (${message}). Nothing was queued.`,
254
- )
255
- }
256
- const spooled = toolkit.runtime.enqueueSpool("conversation", { sessionID, messages, scope: scoped })
257
- if (spooled) {
258
- log.warn("remember failed, spooled", error)
259
- // A queued write is not accepted yet, so nothing it supersedes is removed.
260
- const kept = supersedes.length > 0 ? ` Superseded ids were kept, because the new memory is not stored yet: ${supersedes.map((id) => oneLine(id, 80)).join(", ")}.` : ""
261
- return text(
262
- `backend unreachable; queued locally (${errorMessage(error)}). It will be retried on the next flush.${kept}`,
263
- )
264
- }
265
- log.warn("remember failed and could not be spooled", error)
266
- return fail(withNote(errorMessage(error), "local spooling is disabled or unavailable, so the memory was not stored"))
267
- }
268
- },
269
- })
76
+ export function createCoreForget(toolkit) {
77
+ if (coreForgets.has(toolkit)) return coreForgets.get(toolkit)
78
+ const { backend, locate, noteLocations, forgetLocations, knownAgents, rowLocation } = toolkit
270
79
 
271
80
  /**
272
- * Remove the private L1 atoms a new memory replaces, after it was accepted.
81
+ * Remove the core L1 atoms a new memory replaces, after it was stored.
273
82
  * Each id is deleted under the agent that wrote it, as mem_recall showed it;
274
83
  * an id this process has not seen is tried under this session's agent. Only
275
84
  * the backend's count is reported. Captured turns are history and stay.
@@ -300,9 +109,7 @@ export function registerMemory(editor, toolkit) {
300
109
  const list = (values) => values.map((id) => oneLine(id, 80)).join(", ")
301
110
  const lines = []
302
111
  if (removed.length > 0) {
303
- lines.push(
304
- `Superseded: ${list(removed)} ${removed.length === 1 ? "is" : "are"} removed now. The new memory is recallable after extraction (asynchronous), so for a short while mem_recall finds neither the old atom nor the new one.`,
305
- )
112
+ lines.push(`Superseded atom${removed.length === 1 ? "" : "s"} ${list(removed)}: deleted now (atoms have no history to keep).`)
306
113
  }
307
114
  if (missing.length > 0) lines.push(`Not found, so not removed: ${list(missing)} (pass ids from mem_recall).`)
308
115
  if (failed.length > 0) lines.push(`Not removed, the delete failed: ${failed.join("; ")}.`)
@@ -782,6 +589,605 @@ export function registerMemory(editor, toolkit) {
782
589
  return { changed, text: lines.join(" ") }
783
590
  }
784
591
 
592
+ /** One newest-first page of a layer's rows under one agent, noting where each row was written. */
593
+ const pageReader = (spaceContext, base, agent, layer) => async (offset) => {
594
+ const listScope = { ...base, agent_id: agent }
595
+ const data =
596
+ layer === "l0"
597
+ ? await backend.queryConversations({ scope: listScope, limit: SCAN_PAGE, offset })
598
+ : await backend.queryAtoms({ scope: listScope, limit: SCAN_PAGE, offset })
599
+ const rows = (layer === "l0" ? (data?.messages ?? data?.items) : (data?.items ?? data?.records)) ?? []
600
+ noteLocations(spaceContext, layer, rows, { agent_id: agent })
601
+ return { rows, total: data?.total }
602
+ }
603
+
604
+ /**
605
+ * The core's copies of forgotten text (docs/design/adr-forget-copies.md):
606
+ * the newest atoms and turns of this space's agents that hold the same fact,
607
+ * matched by its numbers, identifiers and names. Rows in `exclude` are not
608
+ * copies (the caller deletes them by id). Nothing is deleted here.
609
+ *
610
+ * @returns {Promise<{ copies: any[], windows: any[], forgotten: any[] }>}
611
+ */
612
+ async function scanCopies({ texts, spaceContext, base, exclude = new Set() }) {
613
+ const forgotten = texts.map((value) => String(value ?? "").trim()).filter(Boolean).map((value) => copyFeatures(value))
614
+ if (forgotten.length === 0) return { copies: [], windows: [], forgotten }
615
+ const agents = [...new Set([base.agent_id, ...knownAgents(spaceContext)])].filter(Boolean).slice(0, 4)
616
+ const deadline = Date.now() + COPY_SCAN_MS
617
+ const windows = []
618
+ for (const agent of agents) {
619
+ for (const layer of ["l1", "l0"]) {
620
+ const listing = await readListing({ pages: new Map(), readPage: pageReader(spaceContext, base, agent, layer), pageSize: SCAN_PAGE, maxPages: SCAN_PAGES, deadline })
621
+ windows.push({ agent, layer, listing })
622
+ }
623
+ }
624
+ const copies = []
625
+ const seen = new Set()
626
+ for (const window of windows) {
627
+ for (const row of window.listing.rows) {
628
+ const id = String(row?.id ?? "")
629
+ if (!id || seen.has(id) || exclude.has(id)) continue
630
+ seen.add(id)
631
+ const content = String(row?.content ?? row?.text ?? "")
632
+ const parts = rememberParts(content)
633
+ const match = matchCopy(forgotten, parts.kind === "wrapper" ? `${parts.body}\n${parts.reason}` : content)
634
+ if (!match) continue
635
+ const where = rowLocation(window.layer, row, { agent_id: window.agent })
636
+ copies.push({ id, layer: window.layer, agent_id: where.agent_id, session_id: where.session_id, role: row?.role, content, match })
637
+ }
638
+ }
639
+ return { copies, windows, forgotten }
640
+ }
641
+
642
+ /**
643
+ * Delete rows the scan found, grouped as upstream deletes them: atoms by
644
+ * agent, turns by agent and session. Answers what the backend confirmed and
645
+ * what it did not delete, with the reason.
646
+ */
647
+ async function deleteRows(rows, base) {
648
+ const groups = new Map()
649
+ for (const row of rows) {
650
+ const key = `${row.layer}::${row.agent_id ?? ""}::${row.layer === "l0" ? (row.session_id ?? "") : ""}`
651
+ if (!groups.has(key)) groups.set(key, { layer: row.layer, agent: row.agent_id, session: row.session_id, rows: [] })
652
+ groups.get(key).rows.push(row)
653
+ }
654
+ const deleted = []
655
+ const kept = []
656
+ for (const group of groups.values()) {
657
+ const ids = group.rows.map((row) => row.id)
658
+ if (group.layer === "l0" && !group.session) {
659
+ kept.push(...group.rows.map((row) => ({ ...row, why: "its session is unknown, so the core cannot delete it" })))
660
+ continue
661
+ }
662
+ const scope = { ...base, ...(group.agent ? { agent_id: group.agent } : {}) }
663
+ try {
664
+ const data =
665
+ group.layer === "l1"
666
+ ? await backend.deleteAtoms({ ids, scope })
667
+ : await backend.deleteConversations({ messageIDs: ids, scope: { ...scope, session_id: group.session } })
668
+ const confirmed = Array.isArray(data?.deleted_ids) ? ids.filter((id) => data.deleted_ids.includes(id)) : ids.slice(0, Math.max(0, Math.min(ids.length, Number(data?.deleted_count) || 0)))
669
+ deleted.push(...group.rows.filter((row) => confirmed.includes(row.id)))
670
+ kept.push(...group.rows.filter((row) => !confirmed.includes(row.id)).map((row) => ({ ...row, why: "the core did not confirm the delete" })))
671
+ } catch (error) {
672
+ kept.push(...group.rows.map((row) => ({ ...row, why: `the delete failed: ${errorMessage(error)}` })))
673
+ }
674
+ }
675
+ return { deleted, kept }
676
+ }
677
+
678
+ /**
679
+ * Search the core as recall does, for the forgotten text, and answer the
680
+ * hits that still hold it: the read-back after a forget.
681
+ */
682
+ async function remainingCopies({ texts, forgotten, base }) {
683
+ const left = []
684
+ let failed = false
685
+ for (const text of texts) {
686
+ const query = String(text ?? "").slice(0, 300)
687
+ if (!query.trim()) continue
688
+ const [atoms, turns] = await Promise.all([
689
+ backend.searchAtoms({ query, limit: 25, scope: base }).catch(() => {
690
+ failed = true
691
+ return null
692
+ }),
693
+ backend.searchConversations({ query, limit: 25, scope: base }).catch(() => {
694
+ failed = true
695
+ return null
696
+ }),
697
+ ])
698
+ for (const row of atoms?.items ?? []) if (matchCopy(forgotten, row?.content ?? "")) left.push({ id: String(row.id), layer: "l1" })
699
+ for (const row of turns?.messages ?? []) if (matchCopy(forgotten, rememberParts(row?.content ?? "").body || row?.content)) left.push({ id: String(row.id), layer: "l0" })
700
+ }
701
+ return { left: [...new Map(left.map((row) => [row.id, row])).values()], failed }
702
+ }
703
+
704
+ const api = { supersedeAtoms: supersede, deleteByIds, eraseSummaries, scanCopies, deleteRows, remainingCopies }
705
+ coreForgets.set(toolkit, api)
706
+ return api
707
+ }
708
+
709
+ const coreForgets = new WeakMap()
710
+
711
+ /** Ids from a string or a list, trimmed and de-duplicated. */
712
+ function idList(value) {
713
+ if (Array.isArray(value)) return [...new Set(value.map((id) => String(id ?? "").trim()).filter(Boolean))]
714
+ if (typeof value === "string" && value.trim()) return [value.trim()]
715
+ return []
716
+ }
717
+
718
+ /** Lower-case words only, for an exact-duplicate check. */
719
+ function normal(text) {
720
+ return String(text ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()
721
+ }
722
+
723
+ /**
724
+ * `mem_remember`: one durable memory as a record of kind `memory`
725
+ * (docs/design/memory-v1-contracts.md §4.1). The record is the memory: it is
726
+ * stored verbatim with its type, answers its `rec_` id at once, and recall
727
+ * finds it at once. Nothing is written to the core.
728
+ *
729
+ * Every curation refusal runs before any request. A team write asks
730
+ * `memory.remember`. A records write is never queued: an answer without an id
731
+ * would be a promise the tool cannot keep, so a failed write says so.
732
+ *
733
+ * @param {any} editor
734
+ * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
735
+ */
736
+ export function registerRemember(editor, toolkit) {
737
+ const { text, fail, log, scope, scopeFor, resolveWriteSpace, assertTeamWrite, displayScope, taskFor } = toolkit
738
+ // The pre-0.9 promote, offered for the deprecated `promote` alias's legacy
739
+ // path (src/tools/index.js captures it, never registers it twice): it
740
+ // revokes a 0.8 share exactly as before, local mode included.
741
+ registerPromote(editor, toolkit)
742
+
743
+ editor.add({
744
+ name: "remember",
745
+ description:
746
+ "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. The same memory worded the same is not stored twice: the answer names the id it already has. 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 a shared space that is selected or bound to the session, editor access, and the person's approval, which the tool asks for.",
747
+ input: {
748
+ type: "object",
749
+ properties: {
750
+ content: {
751
+ type: "string",
752
+ description:
753
+ '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]]"}',
754
+ },
755
+ kind: {
756
+ type: "string",
757
+ enum: [...KINDS],
758
+ description:
759
+ "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",
760
+ },
761
+ why: {
762
+ type: "string",
763
+ 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',
764
+ },
765
+ links: {
766
+ type: "array",
767
+ items: { type: "string" },
768
+ 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`,
769
+ },
770
+ supersedes: {
771
+ type: "array",
772
+ items: { type: "string" },
773
+ 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_..."]}`,
774
+ },
775
+ stated_by: {
776
+ type: "string",
777
+ enum: ["person", "agent"],
778
+ description:
779
+ "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.",
780
+ },
781
+ task: TASK_INPUT,
782
+ 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" },
783
+ space: { type: "string", description: "Space id to write to (control plane); defaults to your personal or session-bound shared space" },
784
+ },
785
+ required: ["content", "kind"],
786
+ additionalProperties: false,
787
+ },
788
+ options: { namespace: "mem" },
789
+ execute: async (input, context) => {
790
+ // Every refusal is decided here, before any request.
791
+ const content = String(input?.content ?? "").trim()
792
+ const refusal = writeRefusal(content)
793
+ if (refusal) return text(refusal)
794
+ if (content.length > MAX_CONTENT_CHARS) {
795
+ return text(
796
+ `not stored: ${content.length} characters is not one atomic fact (limit ${MAX_CONTENT_CHARS}). State the decision in a sentence or two, and put long synthesis on a page (mem_page).`,
797
+ )
798
+ }
799
+ // kind is required (§4.1); a host that does not check the schema gets fact.
800
+ const kind = input?.kind === undefined || input?.kind === null || input?.kind === "" ? "fact" : String(input.kind)
801
+ if (!KINDS.includes(kind)) return text(`not stored: kind must be one of ${KINDS.join(", ")}.`)
802
+ // The why is stored with the fact, so it passes the same guard.
803
+ const why = String(input?.why ?? "").trim()
804
+ const whyRefusal = why ? writeRefusal(why) : ""
805
+ if (whyRefusal) return text(`not stored (why): ${whyRefusal.replace(/^not stored: /, "")}`)
806
+ // Who stated it: the routines' policy treats the person's own statement
807
+ // differently from the agent's conclusion, so it is the caller's to say.
808
+ const statedBy = input?.stated_by === "person" ? "person" : "agent"
809
+ const links = idList(input?.links)
810
+ if (links.length > MAX_LINKS) return text(`not stored: links takes at most ${MAX_LINKS} paths or ids.`)
811
+ const badLinks = links.filter((link) => !PAGE_PATH.test(link) && !RECORD_ID.test(link))
812
+ if (badLinks.length > 0) {
813
+ return text(`not stored: ${badLinks.map((link) => JSON.stringify(oneLine(link, 80))).join(", ")} ${badLinks.length === 1 ? "is not a page path or record id" : "are not page paths or record ids"}; a path is lower-case segments such as people/ama.`)
814
+ }
815
+ const supersedes = idList(input?.supersedes)
816
+ if (supersedes.length > MAX_SUPERSEDES) {
817
+ return text(`not stored: supersedes takes at most ${MAX_SUPERSEDES} ids; to remove more, use mem_revise forget.`)
818
+ }
819
+ const turns = supersedes.filter((id) => TURN_ID.test(id))
820
+ if (turns.length > 0) {
821
+ return text(
822
+ `not stored: supersedes takes memory ids (rec_…) or atom ids (m_…); ${turns.map((id) => oneLine(id, 80)).join(", ")} ${turns.length === 1 ? "is a turn" : "are turns"}. Pass the memory's id, or forget the turn with mem_revise.`,
823
+ )
824
+ }
825
+ const recordIDs = supersedes.filter((id) => RECORD_ID.test(id))
826
+ const atomIDs = supersedes.filter((id) => !RECORD_ID.test(id))
827
+ const task = taskFor(input, context)
828
+ if (task.invalid) return text(`not stored: ${task.invalid}`)
829
+
830
+ const visibility = normalizeVisibility(input?.visibility, "private")
831
+ const resolved = await resolveWriteSpace(input, context, visibility)
832
+ if (resolved.invalid) return text(resolved.invalid)
833
+ if (resolved.error) return fail(resolved.error)
834
+ const spaceContext = resolved.context
835
+ const scoped = spaceContext ? scopeFor(spaceContext, { agent: context?.agent }) : scope({ agent: context?.agent })
836
+ const label = displayScope(spaceContext, scoped)
837
+ const body = why ? `${content}\n\nWhy: ${why}` : content
838
+
839
+ // The same memory, worded the same, is not stored twice: a retry after a
840
+ // lost answer, or a repeat, answers the id that exists.
841
+ if (supersedes.length === 0 && body.length <= 230) {
842
+ try {
843
+ const found = await callRecords(toolkit, "records.search", { query: oneLine(content, 200), kinds: ["memory"], types: [kind], limit: 5 }, spaceContext, scoped)
844
+ const same = (found?.hits ?? []).find((hit) => hit.type === kind && normal(hit.snippet) === normal(body))
845
+ if (same) return text(`already stored as ${same.id} (memory/${kind}) in ${label}; nothing new was written. To change it: mem_revise {"action": "correct", "id": "${same.id}", "content": "…"}.`)
846
+ } catch {
847
+ /* the check is a courtesy; the write decides */
848
+ }
849
+ }
850
+
851
+ if (visibility === "team") {
852
+ try {
853
+ await assertTeamWrite(context, "memory.remember", [spaceContext?.space_id ?? "team", ...supersedes], {
854
+ kind,
855
+ visibility,
856
+ excerpt: redactSecrets(oneLine(content, 400)),
857
+ ...(supersedes.length > 0 ? { supersedes } : {}),
858
+ })
859
+ } catch (error) {
860
+ return text(`remembering to the team denied: ${errorMessage(error)}. Nothing was stored.`)
861
+ }
862
+ }
863
+
864
+ const record = {
865
+ kind: "memory",
866
+ type: kind,
867
+ title: titleFrom(content),
868
+ body,
869
+ stated_by: statedBy,
870
+ ...(links.length > 0 ? { fields: { links } } : {}),
871
+ ...(recordIDs.length > 0 ? { supersedes: recordIDs } : {}),
872
+ source: context?.sessionID ? { session: String(context.sessionID) } : {},
873
+ ...(task.key ? { task: task.key } : {}),
874
+ }
875
+ let stored
876
+ try {
877
+ stored = (await callRecords(toolkit, "records.put", { record }, spaceContext, scoped))?.record
878
+ } catch (error) {
879
+ log.warn("remember failed", error)
880
+ const refused = notWritten(error, "stored")
881
+ if (refused) return text(refused)
882
+ if (error instanceof RecordsError && error.code === "not_found") {
883
+ return text(`not stored: ${oneLine(error.what, 200).replace(/^[^:]+: /, "")}. Nothing was stored; supersedes takes rec_ ids that mem_recall or mem_remember returned.`)
884
+ }
885
+ const message = errorMessage(error)
886
+ return isCoded(message) ? text(withNote(message, "not stored, and nothing was queued")) : fail(withNote(message, "not stored, and nothing was queued"))
887
+ }
888
+ const id = String(stored?.id ?? "")
889
+ 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.")
890
+ noteRecordSpace(toolkit, id, spaceContext)
891
+ log.info("remember", { kind, visibility, scope: label, task: Boolean(task.key), supersedes: supersedes.length })
892
+
893
+ const lines = [
894
+ `stored ${id} (memory/${kind}, stated by ${statedBy}) in ${label} ${task.key ? `for task ${task.key}` : "for the whole space"}. mem_recall finds it now.`,
895
+ ]
896
+ if (recordIDs.length > 0) {
897
+ const marked = (stored?.supersedes ?? recordIDs).map((value) => oneLine(value, 40))
898
+ 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.`)
899
+ }
900
+ if (atomIDs.length > 0) {
901
+ const unscoped = spaceContext ? scopeFor(spaceContext, { agent: context?.agent }) : scope({ agent: context?.agent })
902
+ const { session_id: _session, task_id: _task, ...base } = unscoped
903
+ lines.push(await createCoreForget(toolkit).supersedeAtoms(atomIDs, spaceContext, base))
904
+ }
905
+ lines.push(`To change it later: mem_revise {"action": "correct", "id": "${id}", "content": "…"}; to drop it: {"action": "retire", "id": "${id}"}.`)
906
+ return text(lines.join("\n"))
907
+ },
908
+ })
909
+ }
910
+
911
+ /**
912
+ * `mem_revise`: change a memory by its id (contract §4.1). `correct` writes a
913
+ * new record that supersedes the old one, which is kept; `confirm`, `retire`
914
+ * and `restore` change its status; `history` shows its versions and lineage;
915
+ * `forget` deletes it for good and always asks `memory.forget`. An `m_` or
916
+ * `msg-` id is forgotten in the core as mem_forget does, and `correct` on an
917
+ * `m_` id stores the correction as a record and deletes the atom.
918
+ *
919
+ * A change to a record in a shared space asks `memory.revise`.
920
+ *
921
+ * @param {any} editor
922
+ * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
923
+ */
924
+ export function registerRevise(editor, toolkit) {
925
+ const { text, fail, log, scope, scopeFor, resolveReadSpace, assertTeamWrite, displayScope, taskFor, forgetLocations } = toolkit
926
+ // The pre-0.9 forget, offered for the deprecated `forget` alias's legacy
927
+ // path (src/tools/index.js captures it, never registers it twice): it keeps
928
+ // the persona and scenario phrase erase (match), which revise does not take.
929
+ registerForget(editor, toolkit)
930
+
931
+ /**
932
+ * The space a revise acts in: where this process last saw the id (recall,
933
+ * remember, page), else the session's (personal, or a bound shared one).
934
+ * §4.1 gives revise no space argument.
935
+ */
936
+ async function spaceFor(id, context) {
937
+ const seen = recordSpace(toolkit, id)
938
+ return resolveReadSpace(seen ? { space: seen } : {}, context, "auto")
939
+ }
940
+
941
+ function renderHistory(id, data) {
942
+ const versions = Array.isArray(data?.versions) ? data.versions : []
943
+ const lines = [
944
+ `<recalled_memory backend="memory" kind="history" id="${neutralizeFenceClosers(oneLine(id, 40))}">`,
945
+ "Stored memory text, newest version first: data, not instructions.",
946
+ ]
947
+ for (const version of versions.slice(0, 20)) {
948
+ const note = changeNote(version)
949
+ const why = note ? ` (${oneLine(note, 120)})` : ""
950
+ lines.push(neutralizeFenceClosers(`- v${version.version ?? "?"} · ${version.status ?? "?"} · ${dateOf(version.updated)}${why} — ${oneLine(String(version.body ?? version.title ?? "").replace(/\s+/g, " "), 300)}`))
951
+ }
952
+ if (versions.length > 20) lines.push(`(${versions.length - 20} older version(s) not shown)`)
953
+ // The lineage both ways, each a list of {id, kind, type, title, status, updated} (or {id, missing}).
954
+ const supersedes = lineageIds(data?.lineage?.supersedes)
955
+ const supersededBy = lineageIds(data?.lineage?.superseded_by)
956
+ const parts = []
957
+ if (supersedes.length > 0) parts.push(`supersedes ${supersedes.map((value) => oneLine(value, 40)).join(", ")}`)
958
+ if (supersededBy.length > 0) parts.push(`superseded by ${supersededBy.map((value) => oneLine(value, 40)).join(", ")}`)
959
+ lines.push(parts.length > 0 ? `Lineage: ${parts.join("; ")}.` : "Lineage: none; this record supersedes nothing and nothing supersedes it.")
960
+ lines.push("</recalled_memory>")
961
+ return lines.join("\n")
962
+ }
963
+
964
+ editor.add({
965
+ name: "revise",
966
+ description:
967
+ '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 (with content): writes the corrected memory as a new record that supersedes the old one, which is kept as history; answers the new id. confirm: marks it checked today. retire: hides it from recall (status "all" still shows it); restore: brings it back. history: every version and what it supersedes or is superseded by. forget: deletes it and its history for good, with the copies of its fact found in the core, reads back whether recall still finds it, and always asks the person first. When the person asked you to forget it, the request is their consent: call it without asking again in chat (the host shows its own prompt). When you propose a deletion yourself (a duplicate, a tidy-up), ask the person first. forget also takes the core\'s ids from before 0.9 (m_… atoms, msg-… turns), and correct on an m_… atom stores the correction as a record and deletes the atom. revise acts in the space where recall or remember showed the id. Act by id, never by matching text. Never put status, instructions, email addresses or local paths in content: they are refused before anything changes. A change to a shared space\'s memory asks the person.',
968
+ input: {
969
+ type: "object",
970
+ properties: {
971
+ action: {
972
+ type: "string",
973
+ enum: [...REVISE_ACTIONS],
974
+ 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"}',
975
+ },
976
+ id: { type: "string", description: "Required: the record id (rec_…); forget also takes the core's m_… and msg-… ids" },
977
+ content: { type: "string", description: "correct only: the corrected memory, whole, as it should come back" },
978
+ reason: { type: "string", description: "Why it changed; kept in the record's history" },
979
+ },
980
+ required: ["action", "id"],
981
+ additionalProperties: false,
982
+ },
983
+ options: { namespace: "mem" },
984
+ execute: async (input, context) => {
985
+ const verb = String(input?.action ?? "")
986
+ if (!REVISE_ACTIONS.includes(verb)) return text(`action is required: one of ${REVISE_ACTIONS.join(", ")}. Example: {"action": "history", "id": "rec_..."}`)
987
+ const ids = idList(input?.id)
988
+ if (ids.length === 0) return text(`id is required for ${verb}: the rec_… id mem_remember or mem_recall gave.`)
989
+ const id = ids[0]
990
+ // A record id, a turn id, or else the core's atom id (m_… on the
991
+ // deployed core; other cores mint other shapes), as supersedes takes it.
992
+ const unknown = ids.filter((value) => !RECORD_ID.test(value) && !CORE_ID.test(value))
993
+ if (unknown.length > 0) {
994
+ 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.`)
995
+ }
996
+ if (verb !== "forget" && !RECORD_ID.test(id) && !(verb === "correct" && !TURN_ID.test(id))) {
997
+ 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.`)
998
+ }
999
+ // Every refusal before any request.
1000
+ const content = String(input?.content ?? "").trim()
1001
+ const reason = String(input?.reason ?? "").trim()
1002
+ if (verb === "correct") {
1003
+ if (!content) return text('correct needs content: the corrected memory, whole. Example: {"action": "correct", "id": "rec_...", "content": "…"}')
1004
+ const refusal = writeRefusal(content)
1005
+ if (refusal) return text(refusal.replace(/^not stored/, "not corrected"))
1006
+ if (content.length > MAX_CONTENT_CHARS) return text(`not corrected: ${content.length} characters is not one atomic fact (limit ${MAX_CONTENT_CHARS}).`)
1007
+ } else if (content) {
1008
+ return text(`content is for correct; ${verb} changes no text.`)
1009
+ }
1010
+ if (reason) {
1011
+ const refusal = writeRefusal(reason)
1012
+ if (refusal) return text(`not changed (reason): ${refusal.replace(/^not stored: /, "")}`)
1013
+ }
1014
+ // A corrected atom keeps no kind the core could tell: it is stored as a fact.
1015
+ const kind = "fact"
1016
+ const task = taskFor({}, context)
1017
+
1018
+ const resolved = await spaceFor(id, context)
1019
+ if (resolved.invalid) return text(resolved.invalid)
1020
+ if (resolved.error) return fail(resolved.error)
1021
+ const spaceContext = resolved.context
1022
+ const scoped = spaceContext ? scopeFor(spaceContext, { agent: context?.agent }) : scope({ agent: context?.agent })
1023
+ const label = displayScope(spaceContext, scoped)
1024
+ const shared = spaceContext?.space_kind === "shared"
1025
+ if (shared && verb !== "history" && !canWriteShared(spaceContext.role)) {
1026
+ return text(`changing records in ${oneLine(spaceContext.space_id, 80)} requires editor, admin, or owner access; the control plane reports role ${oneLine(spaceContext.role || "unknown", 20)}. Nothing changed.`)
1027
+ }
1028
+
1029
+ try {
1030
+ if (verb === "history") {
1031
+ const data = await callRecords(toolkit, "records.history", { id }, spaceContext, scoped)
1032
+ return text(renderHistory(id, data))
1033
+ }
1034
+ if (verb === "forget") return text(await forget({ ids, context, spaceContext, scoped, label }))
1035
+
1036
+ if (shared) {
1037
+ try {
1038
+ await assertTeamWrite(context, "memory.revise", [spaceContext.space_id, id], {
1039
+ revise: verb,
1040
+ ...(content ? { excerpt: redactSecrets(oneLine(content, 400)) } : {}),
1041
+ ...(reason ? { reason: oneLine(reason, 200) } : {}),
1042
+ })
1043
+ } catch (error) {
1044
+ return text(`revising team memory denied: ${errorMessage(error)}. Nothing changed.`)
1045
+ }
1046
+ }
1047
+
1048
+ if (verb === "correct" && !RECORD_ID.test(id)) {
1049
+ 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 } : {}) }
1050
+ const stored = (await callRecords(toolkit, "records.put", { record }, spaceContext, scoped))?.record
1051
+ const { session_id: _session, task_id: _task, ...base } = scoped
1052
+ const removed = await createCoreForget(toolkit).supersedeAtoms([id], spaceContext, base)
1053
+ return text(`corrected atom ${oneLine(id, 80)} as ${stored?.id} (memory/${kind}) in ${label}; mem_recall finds it now.\n${removed}`)
1054
+ }
1055
+
1056
+ const body = { id, action: verb, ...(verb === "correct" ? { body: content, title: titleFrom(content) } : {}), ...(reason ? { reason } : {}) }
1057
+ const data = await callRecords(toolkit, "records.revise", body, spaceContext, scoped)
1058
+ const record = data?.record ?? {}
1059
+ log.info("revise", { revise: verb, scope: label })
1060
+ if (verb === "correct") {
1061
+ return text(
1062
+ `corrected ${id} → ${record.id} in ${label}: ${record.id} is current; ${id} is kept, marked superseded (mem_recall shows it only with status "all"; mem_revise history shows both).\n${recordLine(record)}`,
1063
+ )
1064
+ }
1065
+ if (verb === "confirm") return text(`confirmed ${id} (version ${record.version ?? "?"}, ${record.status ?? "current"}) in ${label}: checked today.`)
1066
+ if (verb === "retire") return text(`retired ${id} in ${label}: mem_recall no longer shows it (status "all" does). To bring it back: mem_revise {"action": "restore", "id": "${id}"}.`)
1067
+ return text(`restored ${id} in ${label}: it is ${record.status ?? "current"} again and mem_recall shows it.`)
1068
+ } catch (error) {
1069
+ log.warn("revise failed", error)
1070
+ const refused = notWritten(error, verb === "correct" ? "corrected" : "changed")
1071
+ if (refused) return text(refused)
1072
+ if (error instanceof RecordsError && error.code === "not_found") {
1073
+ return text(`${oneLine(id, 80)} was not found in ${label}. Nothing changed. Pass an id mem_recall or mem_remember gave, in the space it is in.`)
1074
+ }
1075
+ return fail(errorMessage(error))
1076
+ }
1077
+ },
1078
+ })
1079
+
1080
+ /** The fact a memory record states: its body before "Why:", else its title. */
1081
+ function factOf(record) {
1082
+ const body = String(record?.body ?? "").split(/\n\s*\nWhy:/)[0].trim()
1083
+ return body || String(record?.title ?? "").trim()
1084
+ }
1085
+
1086
+ /**
1087
+ * Forget (EVAL's gate, contract §4.1): records by id with `records.delete`,
1088
+ * and core ids as mem_forget deletes them. Capture keeps the conversation a
1089
+ * fact was said in and the core extracts atoms from it, so deleting a record
1090
+ * alone leaves the fact recallable: the core's copies of each record's fact
1091
+ * (atoms and turns that hold it, docs/design/adr-forget-copies.md) are found
1092
+ * first, named in the one `memory.forget` ask with everything else, and
1093
+ * deleted with it. The person's request covers the copies the ask names;
1094
+ * any that cannot be deleted are listed. Then recall's layers are searched
1095
+ * again and the answer says whether the fact still comes back.
1096
+ */
1097
+ async function forget({ ids, context, spaceContext, scoped, label }) {
1098
+ const core = createCoreForget(toolkit)
1099
+ const recordIDs = ids.filter((value) => RECORD_ID.test(value))
1100
+ const coreIDs = ids.filter((value) => !RECORD_ID.test(value))
1101
+ const { session_id: _session, task_id: _task, ...base } = spaceContext
1102
+ ? scopeFor(spaceContext, { agent: context?.agent })
1103
+ : scope({ agent: context?.agent })
1104
+
1105
+ // The records' text, before anything changes: it is what the copies hold.
1106
+ let records = []
1107
+ let missing = []
1108
+ if (recordIDs.length > 0) {
1109
+ const data = await callRecords(toolkit, "records.get", { ids: recordIDs }, spaceContext, scoped)
1110
+ records = (data?.records ?? []).filter((record) => recordIDs.includes(record.id))
1111
+ missing = recordIDs.filter((value) => !records.some((record) => record.id === value))
1112
+ }
1113
+ const facts = records.map(factOf).filter(Boolean)
1114
+ const scan = facts.length > 0 ? await core.scanCopies({ texts: facts, spaceContext, base, exclude: new Set(coreIDs) }) : { copies: [], windows: [], forgotten: [] }
1115
+ const copyIDs = scan.copies.map((row) => row.id)
1116
+ const metadata = { space: spaceContext?.space_id ?? "local", visibility: spaceContext?.space_kind === "shared" ? "team" : "private", ids: ids.length, ...(copyIDs.length > 0 ? { copies: copyIDs.length } : {}) }
1117
+ const ask = (more = []) =>
1118
+ assertTeamWrite(context, "memory.forget", [...ids, ...copyIDs, ...more], { ...metadata, ...(more.length > 0 ? { remember_rows: more.length } : {}) })
1119
+
1120
+ const parts = []
1121
+ let report = ""
1122
+ if (coreIDs.length > 0) {
1123
+ const deleted = await core.deleteByIds({ ids: coreIDs, wanted: ["l1", "l0"], spaceContext, base, explicitAgent: "", approve: (ownIDs) => ask(ownIDs), retryArgs: {} })
1124
+ if (deleted.denied) return `forgetting denied: ${deleted.denied}. Nothing was deleted.`
1125
+ parts.push(`deleted ${deleted.total} core item(s) (${deleted.removed.l1} l1 atom(s), ${deleted.removed.l0} l0 turn(s)).`, ...deleted.lines)
1126
+ report = deleted.report
1127
+ } else {
1128
+ try {
1129
+ await ask()
1130
+ } catch (error) {
1131
+ return `forgetting denied: ${errorMessage(error)}. Nothing was deleted.`
1132
+ }
1133
+ }
1134
+
1135
+ let gone = []
1136
+ if (records.length > 0) {
1137
+ const data = await callRecords(toolkit, "records.delete", { ids: records.map((record) => record.id) }, spaceContext, scoped)
1138
+ gone = (data?.deleted ?? []).map(String)
1139
+ if (gone.length > 0) {
1140
+ 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.`)
1141
+ }
1142
+ const undeleted = records.map((record) => record.id).filter((value) => !gone.includes(value))
1143
+ if (undeleted.length > 0) parts.push(`The records service did not delete ${undeleted.join(", ")}.`)
1144
+ }
1145
+ if (missing.length > 0) parts.push(`Not found, so not deleted: ${missing.join(", ")} (pass ids from mem_recall in this space).`)
1146
+
1147
+ if (facts.length > 0) {
1148
+ // The copies go only once the record itself is gone.
1149
+ const copies = gone.length > 0 ? await core.deleteRows(scan.copies, base) : { deleted: [], kept: scan.copies.map((row) => ({ ...row, why: "the record was not deleted" })) }
1150
+ forgetLocations(spaceContext, copies.deleted.map((row) => row.id))
1151
+ const list = (rows) => rows.map((row) => `${row.layer} ${oneLine(row.id, 80)}`).join(", ")
1152
+ if (copies.deleted.length > 0) parts.push(`Also deleted ${copies.deleted.length} cop${copies.deleted.length === 1 ? "y" : "ies"} of the fact in the core (atoms and captured turns that held it): ${list(copies.deleted)}.`)
1153
+ else if (scan.copies.length === 0) parts.push("No copy of the fact was found in the core's newest atoms and turns.")
1154
+ if (copies.kept.length > 0) parts.push(`Not deleted: ${copies.kept.map((row) => `${row.layer} ${oneLine(row.id, 80)} (${row.why})`).join("; ")}.`)
1155
+ const partial = scan.windows.some((window) => !window.listing.complete)
1156
+ if (partial) parts.push(`The copy scan read the newest ${SCAN_PAGE * SCAN_PAGES} atoms and turns per agent; older rows were not checked.`)
1157
+
1158
+ // Read back, as recall searches: records, then atoms and turns.
1159
+ const back = { records: [], core: { left: [], failed: false }, recordsFailed: false }
1160
+ for (const fact of facts) {
1161
+ try {
1162
+ const hits = (await callRecords(toolkit, "records.search", { query: oneLine(fact, 200), status: "all", limit: 20 }, spaceContext, scoped))?.hits ?? []
1163
+ back.records.push(...hits.filter((hit) => gone.includes(hit.id) || matchCopy(scan.forgotten, `${hit.title}\n${hit.snippet}`)).map((hit) => hit.id))
1164
+ } catch {
1165
+ back.recordsFailed = true
1166
+ }
1167
+ }
1168
+ back.core = await core.remainingCopies({ texts: facts, forgotten: scan.forgotten, base })
1169
+ const remaining = [...new Set(back.records)].map((id) => `record ${oneLine(id, 80)}`).concat(back.core.left.map((row) => `${row.layer} ${oneLine(row.id, 80)}`))
1170
+ 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.")
1171
+ else if (remaining.length === 0) parts.push("Read back: recall no longer returns the fact from records, atoms or turns.")
1172
+ else parts.push(`Read back: recall still finds the fact in ${remaining.join(", ")}; forget ${remaining.length === 1 ? "it" : "them"} by id (another agent or an older row the scan did not reach).`)
1173
+ }
1174
+ log.info("revise forget", { records: gone.length, core: coreIDs.length, copies: copyIDs.length })
1175
+ parts.push("The persona and scenarios (L2/L3) are not changed by an id forget: mem_forget with match erases a phrase there.")
1176
+ return [parts.join(" "), report].filter(Boolean).join("\n")
1177
+ }
1178
+ }
1179
+
1180
+ /**
1181
+ * The pre-0.9 `mem_forget`: core ids and the L2/L3 phrase erase. Kept for the
1182
+ * alias PLUG-B registers ("Deprecated: use mem_revise forget").
1183
+ *
1184
+ * @param {any} editor
1185
+ * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
1186
+ */
1187
+ export function registerForget(editor, toolkit) {
1188
+ const { text, fail, log, scope, scopeFor, resolveWriteSpace, assertTeamWrite, displayScope, taskFor } = toolkit
1189
+ const { deleteByIds, eraseSummaries } = createCoreForget(toolkit)
1190
+
785
1191
  editor.add({
786
1192
  name: "forget",
787
1193
  description:
@@ -942,6 +1348,17 @@ export function registerMemory(editor, toolkit) {
942
1348
  }
943
1349
  },
944
1350
  })
1351
+ }
1352
+
1353
+ /**
1354
+ * The pre-0.9 `mem_promote`: copy private memory into a shared space as one
1355
+ * wiki, and revoke such a copy. Kept for the alias (`share` copy replaces it).
1356
+ *
1357
+ * @param {any} editor
1358
+ * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
1359
+ */
1360
+ export function registerPromote(editor, toolkit) {
1361
+ const { backend, control, text, fail, log, scope, scopeFor, displayScope, locate, knownAgents } = toolkit
945
1362
 
946
1363
  /**
947
1364
  * Read the text of private L1 atoms and L0 turns by id, for a share. Each id
@@ -1376,3 +1793,16 @@ export function registerMemory(editor, toolkit) {
1376
1793
  },
1377
1794
  })
1378
1795
  }
1796
+
1797
+ /**
1798
+ * Memory writes as registered before 0.9 (remember, forget, promote), for a
1799
+ * tool index that has not moved to the 0.9 set.
1800
+ *
1801
+ * @param {any} editor
1802
+ * @param {ReturnType<import("./shared.js").createToolkit>} toolkit
1803
+ */
1804
+ export function registerMemory(editor, toolkit) {
1805
+ registerRemember(editor, toolkit)
1806
+ registerForget(editor, toolkit)
1807
+ registerPromote(editor, toolkit)
1808
+ }