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