@agentpro/scroll 0.0.0-stage → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +55 -0
- package/LICENSE +21 -0
- package/README.md +293 -2
- package/SPEC.md +1079 -0
- package/bin/scroll.js +8 -0
- package/docs/prompt-caching.md +128 -0
- package/index.js +33 -0
- package/lib/audit.js +358 -0
- package/lib/auth.js +849 -0
- package/lib/chat-sdk/admin-controller.js +289 -0
- package/lib/chat-sdk/debouncer.js +94 -0
- package/lib/chat-sdk/group-grants.js +150 -0
- package/lib/chat-sdk/index.js +222 -0
- package/lib/chat-sdk/long-task-runner.js +413 -0
- package/lib/chat-session.js +1788 -0
- package/lib/chat-telemetry.js +557 -0
- package/lib/codex-app-server.js +851 -0
- package/lib/digest.js +112 -0
- package/lib/effects.js +157 -0
- package/lib/eval.js +408 -0
- package/lib/grounding.js +356 -0
- package/lib/installers.js +176 -0
- package/lib/knowledge.js +335 -0
- package/lib/ledger.js +38 -0
- package/lib/loop.js +197 -0
- package/lib/mcp-client.js +926 -0
- package/lib/memory-cli.js +66 -0
- package/lib/memory-tracker.js +1472 -0
- package/lib/memory.js +1279 -0
- package/lib/people-cli.js +81 -0
- package/lib/people.js +534 -0
- package/lib/permissions.js +272 -0
- package/lib/providers.js +1572 -0
- package/lib/runtime.js +928 -0
- package/lib/sandbox.js +744 -0
- package/lib/scheduler.js +402 -0
- package/lib/scroll.js +1225 -0
- package/lib/skill-cli.js +120 -0
- package/lib/skill-eval.js +156 -0
- package/lib/skills.js +860 -0
- package/lib/style.js +126 -0
- package/lib/tool-retriever.js +489 -0
- package/lib/tools.js +1833 -0
- package/lib/user.js +711 -0
- package/lib/vault.js +151 -0
- package/package.json +88 -4
- package/templates/agent/IDENTITY.md +56 -0
- package/templates/agent/SOUL.md +23 -0
- package/templates/agent/TOOLS.md +25 -0
- package/templates/agent/evals/case-02-citation-discipline.md +29 -0
- package/templates/agent/evals/case-03-boundary.md +27 -0
- package/templates/agent/evals/case-example.md +43 -0
- package/templates/agent/hard-rules.md +11 -0
- package/templates/agent/memory/lessons.md +5 -0
- package/templates/agent/memory/log/.gitkeep +0 -0
- package/templates/external-safety-contract.md +5 -0
- package/templates/long-task-planner.md +17 -0
- package/templates/work/LOOP.md +37 -0
- package/templates/work/WORK.md +50 -0
- package/types/chat.d.ts +61 -0
- package/types/index.d.ts +112 -0
|
@@ -0,0 +1,1472 @@
|
|
|
1
|
+
// SCROLL 2.0 -- Channel-Agnostic 3-Axis Scoped Subject Memory Tracker + L5 Lessons + Nightly Dream.
|
|
2
|
+
//
|
|
3
|
+
// Works on ANY surface or transport (web chat, CLI, voice, Slack, Discord, Telegram, MCP, mobile app,
|
|
4
|
+
// collaborative room, CRM) without coupling core memory mechanics to any specific platform.
|
|
5
|
+
//
|
|
6
|
+
// Three strictly isolated subject axes backed by SCROLL §31-§33 (`lib/memory.js`) + L5 §7:
|
|
7
|
+
// 1. `user` -- `user:<channel>:<userId>` (or `user:<userId>` when `crossSurfaceUser: true`)
|
|
8
|
+
// Personal DM memory; NEVER leaks into any group/room or another user's DM.
|
|
9
|
+
// 2. `group` -- `group:<channel>:<roomId>`
|
|
10
|
+
// Shared room/group context, decisions, goals, open loops; isolated per room.
|
|
11
|
+
// 3. `member` -- `member:<channel>:<roomId>:<userId>`
|
|
12
|
+
// User-in-room profile isolated per (room, user) pair so room A never leaks to room B.
|
|
13
|
+
// 4. `L5` -- `agents/<agent>/memory/lessons.md` (§7)
|
|
14
|
+
// Never-decay procedural lessons loaded into the stable prompt prefix (§13).
|
|
15
|
+
//
|
|
16
|
+
// Zero runtime dependencies. Node >= 20 built-ins only.
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import crypto from 'node:crypto';
|
|
20
|
+
import { openStore, PERSONAL_TAXONOMY, fold } from './memory.js';
|
|
21
|
+
|
|
22
|
+
export function buildScopedMemoryPolicy(personalTaxonomy = PERSONAL_TAXONOMY, {
|
|
23
|
+
extraTaxonomy = {},
|
|
24
|
+
extraSecretPatterns = [],
|
|
25
|
+
extraInstructionPatterns = [],
|
|
26
|
+
utcOffsetMinutes = 0,
|
|
27
|
+
budgetChars = 6000,
|
|
28
|
+
capsuleTurns = 0,
|
|
29
|
+
capsuleChars = 0,
|
|
30
|
+
minQuoteTokens = 2,
|
|
31
|
+
requireQuoteOverlap = true,
|
|
32
|
+
} = {}) {
|
|
33
|
+
return {
|
|
34
|
+
profile: 'scroll-scoped-3axis',
|
|
35
|
+
taxonomy: {
|
|
36
|
+
...personalTaxonomy,
|
|
37
|
+
'role.*': { max_len: 300, always_load: true },
|
|
38
|
+
'decision.*': { max_len: 300, always_load: true },
|
|
39
|
+
'commitment.*': { max_len: 300, always_load: true },
|
|
40
|
+
'topic.*': { max_len: 300 },
|
|
41
|
+
'group.*': { max_len: 300, always_load: true },
|
|
42
|
+
'context.*': { max_len: 300 },
|
|
43
|
+
'lesson.*': { max_len: 300, always_load: true },
|
|
44
|
+
...(extraTaxonomy || {}),
|
|
45
|
+
},
|
|
46
|
+
allow_sensitive: true,
|
|
47
|
+
require_verified: false,
|
|
48
|
+
budget_chars: budgetChars,
|
|
49
|
+
capsule_turns: capsuleTurns,
|
|
50
|
+
capsule_chars: capsuleChars,
|
|
51
|
+
turn_chars: 240,
|
|
52
|
+
utc_offset_minutes: utcOffsetMinutes,
|
|
53
|
+
min_quote_tokens: minQuoteTokens,
|
|
54
|
+
require_quote_overlap: requireQuoteOverlap,
|
|
55
|
+
secret_patterns: Array.isArray(extraSecretPatterns) ? extraSecretPatterns : [],
|
|
56
|
+
instruction_patterns: Array.isArray(extraInstructionPatterns) ? extraInstructionPatterns : [],
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function writeAtomic(filePath, obj) {
|
|
61
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
|
|
62
|
+
const tmp = `${filePath}.tmp.${process.pid}.${crypto.randomBytes(3).toString('hex')}`;
|
|
63
|
+
fs.writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 });
|
|
64
|
+
fs.renameSync(tmp, filePath);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function parseJsonBlock(raw) {
|
|
68
|
+
const s = String(raw || '').trim();
|
|
69
|
+
const fence = /```(?:json)?\s*([\s\S]*?)```/i.exec(s);
|
|
70
|
+
const body = fence ? fence[1].trim() : s;
|
|
71
|
+
const first = body.indexOf('{');
|
|
72
|
+
const last = body.lastIndexOf('}');
|
|
73
|
+
if (first < 0 || last <= first) return null;
|
|
74
|
+
try {
|
|
75
|
+
return JSON.parse(body.slice(first, last + 1));
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function createScopedMemoryTracker({
|
|
82
|
+
rootDir,
|
|
83
|
+
workdir = null,
|
|
84
|
+
agentDir = null,
|
|
85
|
+
ownerIds = [],
|
|
86
|
+
channel = 'chat',
|
|
87
|
+
crossSurfaceUser = false,
|
|
88
|
+
utcOffsetMinutes = 0,
|
|
89
|
+
extraTaxonomy = {},
|
|
90
|
+
extraSecretPatterns = [],
|
|
91
|
+
extraInstructionPatterns = [],
|
|
92
|
+
autoSweepEveryTurns = 12,
|
|
93
|
+
workerPool = null,
|
|
94
|
+
onSweepRequest = null,
|
|
95
|
+
onScrubExternal = null,
|
|
96
|
+
onReloadAgent = null,
|
|
97
|
+
embedFn = null,
|
|
98
|
+
} = {}) {
|
|
99
|
+
const absRoot = path.resolve(rootDir);
|
|
100
|
+
fs.mkdirSync(absRoot, { recursive: true, mode: 0o700 });
|
|
101
|
+
|
|
102
|
+
const policy = buildScopedMemoryPolicy(PERSONAL_TAXONOMY, {
|
|
103
|
+
extraTaxonomy,
|
|
104
|
+
extraSecretPatterns,
|
|
105
|
+
extraInstructionPatterns,
|
|
106
|
+
utcOffsetMinutes,
|
|
107
|
+
});
|
|
108
|
+
const store = openStore({ root: absRoot, region: 'local', policy, workdir });
|
|
109
|
+
const ownerSet = new Set((ownerIds || []).map(String));
|
|
110
|
+
const registryPath = path.join(absRoot, 'registry.json');
|
|
111
|
+
const lessonsPath = agentDir ? path.join(path.resolve(agentDir), 'memory', 'lessons.md') : null;
|
|
112
|
+
|
|
113
|
+
function loadRegistry() {
|
|
114
|
+
if (!fs.existsSync(registryPath)) {
|
|
115
|
+
return { users: {}, groups: {}, members: {}, pendingSweeps: {}, meta: { totalSweeps: 0, totalDreams: 0 } };
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
const j = JSON.parse(fs.readFileSync(registryPath, 'utf8'));
|
|
119
|
+
return {
|
|
120
|
+
users: j.users && typeof j.users === 'object' ? j.users : {},
|
|
121
|
+
groups: j.groups && typeof j.groups === 'object' ? j.groups : {},
|
|
122
|
+
members: j.members && typeof j.members === 'object' ? j.members : {},
|
|
123
|
+
pendingSweeps: j.pendingSweeps && typeof j.pendingSweeps === 'object' ? j.pendingSweeps : {},
|
|
124
|
+
meta: j.meta && typeof j.meta === 'object' ? { totalSweeps: 0, totalDreams: 0, ...j.meta } : { totalSweeps: 0, totalDreams: 0 },
|
|
125
|
+
};
|
|
126
|
+
} catch {
|
|
127
|
+
return { users: {}, groups: {}, members: {}, pendingSweeps: {}, meta: { totalSweeps: 0, totalDreams: 0 } };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const registry = loadRegistry();
|
|
132
|
+
const seenMessages = new Map();
|
|
133
|
+
const frozenSnapshots = new Map();
|
|
134
|
+
const activeJobsBySid = new Map();
|
|
135
|
+
let registryDirty = false;
|
|
136
|
+
let flushTimer = null;
|
|
137
|
+
|
|
138
|
+
function markDirty({ immediate = false } = {}) {
|
|
139
|
+
registryDirty = true;
|
|
140
|
+
if (immediate) {
|
|
141
|
+
flushRegistry();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (!flushTimer) {
|
|
145
|
+
flushTimer = setTimeout(() => {
|
|
146
|
+
flushTimer = null;
|
|
147
|
+
flushRegistry();
|
|
148
|
+
}, 250);
|
|
149
|
+
if (typeof flushTimer.unref === 'function') flushTimer.unref();
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function flushRegistry() {
|
|
154
|
+
if (!registryDirty) return;
|
|
155
|
+
registryDirty = false;
|
|
156
|
+
if (flushTimer) {
|
|
157
|
+
clearTimeout(flushTimer);
|
|
158
|
+
flushTimer = null;
|
|
159
|
+
}
|
|
160
|
+
writeAtomic(registryPath, registry);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function serializeSidJob(sid, fn) {
|
|
164
|
+
const prev = activeJobsBySid.get(sid) || Promise.resolve();
|
|
165
|
+
const next = prev.catch(() => {}).then(fn);
|
|
166
|
+
activeJobsBySid.set(sid, next);
|
|
167
|
+
next.finally(() => {
|
|
168
|
+
if (activeJobsBySid.get(sid) === next) activeJobsBySid.delete(sid);
|
|
169
|
+
});
|
|
170
|
+
return next;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function invalidateFrozen(chatId = null) {
|
|
174
|
+
if (!chatId) {
|
|
175
|
+
frozenSnapshots.clear();
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const prefix = `${normId(chatId)}:`;
|
|
179
|
+
for (const k of [...frozenSnapshots.keys()]) {
|
|
180
|
+
if (k.startsWith(prefix)) frozenSnapshots.delete(k);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function normId(v) {
|
|
185
|
+
return String(v ?? '').replace(/^[a-z0-9_-]+:/i, '').trim();
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function resolveChannel(overrideChannel) {
|
|
189
|
+
return String(overrideChannel || channel || 'chat').toLowerCase().replace(/[^a-z0-9_-]/g, '') || 'chat';
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function userAlias(userId, ch = channel) {
|
|
193
|
+
return crossSurfaceUser ? `user:${normId(userId)}` : `user:${resolveChannel(ch)}:${normId(userId)}`;
|
|
194
|
+
}
|
|
195
|
+
function groupAlias(chatId, ch = channel) { return `group:${resolveChannel(ch)}:${normId(chatId)}`; }
|
|
196
|
+
function memberAlias(chatId, userId, ch = channel) { return `member:${resolveChannel(ch)}:${normId(chatId)}:${normId(userId)}`; }
|
|
197
|
+
|
|
198
|
+
function ensureUser(userId, { name = null, username = null, surface = channel } = {}) {
|
|
199
|
+
const uid = normId(userId);
|
|
200
|
+
if (!uid || uid === '0') return null;
|
|
201
|
+
const ch = resolveChannel(surface);
|
|
202
|
+
const alias = userAlias(uid, ch);
|
|
203
|
+
let sid = store.resolve(alias);
|
|
204
|
+
if (!sid) {
|
|
205
|
+
sid = store.createSubject({ kind: 'person', label: name || `user:${uid}` });
|
|
206
|
+
store.link(alias, sid);
|
|
207
|
+
}
|
|
208
|
+
const prev = registry.users[uid] || { userId: uid, sid, createdAt: new Date().toISOString(), turns: 0 };
|
|
209
|
+
const next = {
|
|
210
|
+
...prev,
|
|
211
|
+
sid,
|
|
212
|
+
name: name || prev.name || null,
|
|
213
|
+
username: username || prev.username || null,
|
|
214
|
+
lastSeenAt: new Date().toISOString(),
|
|
215
|
+
};
|
|
216
|
+
registry.users[uid] = next;
|
|
217
|
+
markDirty();
|
|
218
|
+
if (name && (!prev.name || prev.name !== name)) {
|
|
219
|
+
store.propose(sid, { key: 'profile.name', value: String(name).slice(0, 120), provenance: 'system_verified', system: ch }, { trusted: true });
|
|
220
|
+
}
|
|
221
|
+
return { sid, meta: next };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function ensureGroup(chatId, { title = null, surface = channel } = {}) {
|
|
225
|
+
const gid = normId(chatId);
|
|
226
|
+
if (!gid) return null;
|
|
227
|
+
const ch = resolveChannel(surface);
|
|
228
|
+
const alias = groupAlias(gid, ch);
|
|
229
|
+
let sid = store.resolve(alias);
|
|
230
|
+
if (!sid) {
|
|
231
|
+
sid = store.createSubject({ kind: 'group', label: title || `group:${gid}` });
|
|
232
|
+
store.link(alias, sid);
|
|
233
|
+
}
|
|
234
|
+
const prev = registry.groups[gid] || { chatId: gid, sid, createdAt: new Date().toISOString(), memberIds: [], turns: 0 };
|
|
235
|
+
const next = {
|
|
236
|
+
...prev,
|
|
237
|
+
sid,
|
|
238
|
+
title: title || prev.title || null,
|
|
239
|
+
lastSeenAt: new Date().toISOString(),
|
|
240
|
+
};
|
|
241
|
+
registry.groups[gid] = next;
|
|
242
|
+
markDirty();
|
|
243
|
+
if (title && (!prev.title || prev.title !== title)) {
|
|
244
|
+
store.propose(sid, { key: 'group.title', value: String(title).slice(0, 160), about: 'group', provenance: 'system_verified', system: ch }, { trusted: true });
|
|
245
|
+
}
|
|
246
|
+
return { sid, meta: next };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function ensureMemberInGroup(chatId, userId, { name = null, username = null, groupTitle = null, surface = channel } = {}) {
|
|
250
|
+
const gid = normId(chatId);
|
|
251
|
+
const uid = normId(userId);
|
|
252
|
+
if (!gid || !uid || uid === '0') return null;
|
|
253
|
+
const ch = resolveChannel(surface);
|
|
254
|
+
const grp = ensureGroup(gid, { title: groupTitle, surface: ch });
|
|
255
|
+
const alias = memberAlias(gid, uid, ch);
|
|
256
|
+
let sid = store.resolve(alias);
|
|
257
|
+
const isNew = !sid;
|
|
258
|
+
if (!sid) {
|
|
259
|
+
sid = store.createSubject({ kind: 'person', label: `${name || uid} @ ${groupTitle || gid}` });
|
|
260
|
+
store.link(alias, sid);
|
|
261
|
+
// read:[] prevents member snapshot from duplicating `## Shared (groups)` because recordAndLoad injects group snapshot directly
|
|
262
|
+
store.addMember(grp.sid, sid, {
|
|
263
|
+
role: ownerSet.has(uid) ? 'owner' : 'member',
|
|
264
|
+
read: [],
|
|
265
|
+
write: ownerSet.has(uid) ? ['*'] : ['topic', 'commitment'],
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
const mKey = `${gid}:${uid}`;
|
|
269
|
+
const prev = registry.members[mKey] || { chatId: gid, userId: uid, sid, createdAt: new Date().toISOString(), turns: 0, readIsolated: true };
|
|
270
|
+
if (!isNew && !prev.readIsolated) {
|
|
271
|
+
try {
|
|
272
|
+
store.addMember(grp.sid, sid, {
|
|
273
|
+
role: ownerSet.has(uid) ? 'owner' : 'member',
|
|
274
|
+
read: [],
|
|
275
|
+
write: ownerSet.has(uid) ? ['*'] : ['topic', 'commitment'],
|
|
276
|
+
});
|
|
277
|
+
} catch { /* ignore */ }
|
|
278
|
+
}
|
|
279
|
+
const next = {
|
|
280
|
+
...prev,
|
|
281
|
+
sid,
|
|
282
|
+
readIsolated: true,
|
|
283
|
+
name: name || prev.name || null,
|
|
284
|
+
username: username || prev.username || null,
|
|
285
|
+
lastSeenAt: new Date().toISOString(),
|
|
286
|
+
};
|
|
287
|
+
registry.members[mKey] = next;
|
|
288
|
+
if (!registry.groups[gid].memberIds.includes(uid)) {
|
|
289
|
+
registry.groups[gid].memberIds.push(uid);
|
|
290
|
+
}
|
|
291
|
+
markDirty();
|
|
292
|
+
if (name && (isNew || prev.name !== name)) {
|
|
293
|
+
store.propose(sid, { key: 'profile.name', value: String(name).slice(0, 120), provenance: 'system_verified', system: ch }, { trusted: true });
|
|
294
|
+
}
|
|
295
|
+
if (username && (isNew || prev.username !== username)) {
|
|
296
|
+
store.propose(sid, { key: 'profile.username', value: String(username).slice(0, 80), provenance: 'system_verified', system: ch }, { trusted: true });
|
|
297
|
+
}
|
|
298
|
+
return { sid, groupSid: grp.sid, meta: next };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function findTodaySession(sid) {
|
|
302
|
+
const todayPrefix = store.dayOf().replace(/-/g, '');
|
|
303
|
+
const sessions = store.listSessions(sid);
|
|
304
|
+
for (let i = sessions.length - 1; i >= 0; i--) {
|
|
305
|
+
if (sessions[i].startsWith(todayPrefix)) return sessions[i];
|
|
306
|
+
}
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function appendToSubjectSession(sid, { role = 'user', speaker = null, text = '', surface = channel } = {}) {
|
|
311
|
+
const clean = String(text || '').trim();
|
|
312
|
+
if (!sid || !clean) return null;
|
|
313
|
+
let sessId = findTodaySession(sid);
|
|
314
|
+
if (!sessId) sessId = store.openSession(sid, { surface });
|
|
315
|
+
try {
|
|
316
|
+
const rec = store.appendTurn(sid, sessId, { role, speaker: speaker || sid, text: clean, surface });
|
|
317
|
+
return { sessionId: sessId, ref: rec.ref, seq: rec.seq };
|
|
318
|
+
} catch (err) {
|
|
319
|
+
if (!/closed/i.test(String(err?.message || ''))) throw err;
|
|
320
|
+
sessId = store.openSession(sid, { surface });
|
|
321
|
+
const rec = store.appendTurn(sid, sessId, { role, speaker: speaker || sid, text: clean, surface });
|
|
322
|
+
return { sessionId: sessId, ref: rec.ref, seq: rec.seq };
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function scheduleSweep(sid, sessionId, meta, { immediate = false } = {}) {
|
|
327
|
+
if (!sid || !sessionId) return;
|
|
328
|
+
const prev = registry.pendingSweeps[sid] || { sid, sessionId, unsweptCount: 0 };
|
|
329
|
+
const nextCount = immediate ? Math.max(1, prev.unsweptCount) : (prev.unsweptCount || 0) + 1;
|
|
330
|
+
registry.pendingSweeps[sid] = {
|
|
331
|
+
...prev,
|
|
332
|
+
...meta,
|
|
333
|
+
sid,
|
|
334
|
+
sessionId,
|
|
335
|
+
unsweptCount: nextCount,
|
|
336
|
+
updatedAt: new Date().toISOString(),
|
|
337
|
+
};
|
|
338
|
+
markDirty();
|
|
339
|
+
|
|
340
|
+
const shouldRun = immediate || (autoSweepEveryTurns > 0 && nextCount >= autoSweepEveryTurns);
|
|
341
|
+
if (!shouldRun || typeof onSweepRequest !== 'function') return;
|
|
342
|
+
|
|
343
|
+
const run = () => serializeSidJob(sid, async () => {
|
|
344
|
+
const entry = registry.pendingSweeps[sid];
|
|
345
|
+
if (!entry) return null;
|
|
346
|
+
const res = await onSweepRequest({ sid, sessionId: entry.sessionId, ...meta });
|
|
347
|
+
if (res && res.ok) {
|
|
348
|
+
delete registry.pendingSweeps[sid];
|
|
349
|
+
markDirty({ immediate: true });
|
|
350
|
+
}
|
|
351
|
+
return res;
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
if (workerPool) {
|
|
355
|
+
workerPool.submit({ label: `memory-sweep:${meta.axis || 'subject'}`, chatId: meta.chatId || null, fn: run });
|
|
356
|
+
} else {
|
|
357
|
+
Promise.resolve().then(run).catch(() => {});
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ── 0-Token Realtime Observer (DM, rooms/groups, edits, forum/thread topics) ──
|
|
362
|
+
function observeMessage({
|
|
363
|
+
chatId,
|
|
364
|
+
chatTitle = null,
|
|
365
|
+
threadId = null,
|
|
366
|
+
isGroup = false,
|
|
367
|
+
isEdit = false,
|
|
368
|
+
senderId,
|
|
369
|
+
senderName = null,
|
|
370
|
+
senderUsername = null,
|
|
371
|
+
messageId = null,
|
|
372
|
+
text = '',
|
|
373
|
+
surface = channel,
|
|
374
|
+
} = {}) {
|
|
375
|
+
const clean = String(text || '').trim();
|
|
376
|
+
const cid = normId(chatId);
|
|
377
|
+
const uid = normId(senderId);
|
|
378
|
+
if (!clean || !cid || !uid || uid === '0') return null;
|
|
379
|
+
|
|
380
|
+
const ch = resolveChannel(surface);
|
|
381
|
+
const dedupKey = messageId != null ? `${cid}:${messageId}` : null;
|
|
382
|
+
if (dedupKey && !isEdit && seenMessages.has(dedupKey)) {
|
|
383
|
+
return { ...seenMessages.get(dedupKey), deduplicated: true };
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const label = senderName || senderUsername || `User ${uid}`;
|
|
387
|
+
const threadTag = threadId != null ? `[topic:${threadId}] ` : '';
|
|
388
|
+
const editTag = isEdit ? '(edited) ' : '';
|
|
389
|
+
let out;
|
|
390
|
+
|
|
391
|
+
if (isGroup) {
|
|
392
|
+
const mem = ensureMemberInGroup(cid, uid, { name: senderName, username: senderUsername, groupTitle: chatTitle, surface: ch });
|
|
393
|
+
if (!mem) return null;
|
|
394
|
+
const groupLine = `${messageId ? `#${messageId} ` : ''}${threadTag}${editTag}${label}: ${clean}`;
|
|
395
|
+
const memberLine = `${threadTag}${editTag}${clean}`;
|
|
396
|
+
const gRec = appendToSubjectSession(mem.groupSid, { role: 'user', speaker: mem.sid, text: groupLine, surface: `${ch}-group` });
|
|
397
|
+
const mRec = appendToSubjectSession(mem.sid, { role: 'user', speaker: mem.sid, text: memberLine, surface: `${ch}-group` });
|
|
398
|
+
registry.groups[cid].turns = (registry.groups[cid].turns || 0) + 1;
|
|
399
|
+
registry.members[`${cid}:${uid}`].turns = (registry.members[`${cid}:${uid}`].turns || 0) + 1;
|
|
400
|
+
if (gRec) scheduleSweep(mem.groupSid, gRec.sessionId, { axis: 'group', chatId: cid, chatTitle });
|
|
401
|
+
if (mRec) scheduleSweep(mem.sid, mRec.sessionId, { axis: 'member', chatId: cid, userId: uid, senderName: label });
|
|
402
|
+
out = {
|
|
403
|
+
axis: 'group+member',
|
|
404
|
+
groupSid: mem.groupSid,
|
|
405
|
+
memberSid: mem.sid,
|
|
406
|
+
groupTurnRef: gRec?.ref || null,
|
|
407
|
+
memberTurnRef: mRec?.ref || null,
|
|
408
|
+
groupSessionId: gRec?.sessionId || null,
|
|
409
|
+
memberSessionId: mRec?.sessionId || null,
|
|
410
|
+
};
|
|
411
|
+
} else {
|
|
412
|
+
const usr = ensureUser(uid, { name: senderName, username: senderUsername, surface: ch });
|
|
413
|
+
if (!usr) return null;
|
|
414
|
+
const uRec = appendToSubjectSession(usr.sid, { role: 'user', speaker: usr.sid, text: `${editTag}${clean}`, surface: `${ch}-dm` });
|
|
415
|
+
registry.users[uid].turns = (registry.users[uid].turns || 0) + 1;
|
|
416
|
+
if (uRec) scheduleSweep(usr.sid, uRec.sessionId, { axis: 'user', chatId: cid, userId: uid, senderName: label });
|
|
417
|
+
out = {
|
|
418
|
+
axis: 'user',
|
|
419
|
+
userSid: usr.sid,
|
|
420
|
+
userTurnRef: uRec?.ref || null,
|
|
421
|
+
userSessionId: uRec?.sessionId || null,
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
flushRegistry();
|
|
426
|
+
if (dedupKey) {
|
|
427
|
+
seenMessages.set(dedupKey, out);
|
|
428
|
+
if (seenMessages.size > 4000) {
|
|
429
|
+
const first = seenMessages.keys().next().value;
|
|
430
|
+
seenMessages.delete(first);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
return out;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// ── Scoped Context Loader for `lib/chat-session.js` (Frozen Prompt Cache §32.4 + Strict §31/§42 Isolation) ──
|
|
437
|
+
async function recordAndLoad({
|
|
438
|
+
conversationId,
|
|
439
|
+
text,
|
|
440
|
+
sender = null,
|
|
441
|
+
isGroup = false,
|
|
442
|
+
channel: callChannel = null,
|
|
443
|
+
messageId = null,
|
|
444
|
+
messageIds = null,
|
|
445
|
+
chatTitle = null,
|
|
446
|
+
threadId = null,
|
|
447
|
+
} = {}) {
|
|
448
|
+
const cid = normId(conversationId);
|
|
449
|
+
const uid = normId(sender?.id || sender?.channelId || '');
|
|
450
|
+
const senderName = sender?.name || null;
|
|
451
|
+
const ch = resolveChannel(callChannel || channel);
|
|
452
|
+
|
|
453
|
+
const burstRecords = [];
|
|
454
|
+
const ids = Array.isArray(messageIds) && messageIds.length ? messageIds : (messageId != null ? [messageId] : []);
|
|
455
|
+
for (const mid of ids) {
|
|
456
|
+
const hit = seenMessages.get(`${cid}:${mid}`);
|
|
457
|
+
if (hit) burstRecords.push(hit);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
let rec = burstRecords.length ? burstRecords[burstRecords.length - 1] : null;
|
|
461
|
+
if (!rec && uid && uid !== '0' && cid && text) {
|
|
462
|
+
rec = observeMessage({
|
|
463
|
+
chatId: cid,
|
|
464
|
+
chatTitle,
|
|
465
|
+
threadId,
|
|
466
|
+
isGroup,
|
|
467
|
+
senderId: uid,
|
|
468
|
+
senderName,
|
|
469
|
+
messageId,
|
|
470
|
+
text,
|
|
471
|
+
surface: ch,
|
|
472
|
+
});
|
|
473
|
+
if (rec) burstRecords.push(rec);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
const candidateGroupRefs = [...new Set(burstRecords.map((r) => r?.groupTurnRef).filter(Boolean))];
|
|
477
|
+
const candidateMemberRefs = [...new Set(burstRecords.map((r) => r?.memberTurnRef).filter(Boolean))];
|
|
478
|
+
const candidateUserRefs = [...new Set(burstRecords.map((r) => r?.userTurnRef).filter(Boolean))];
|
|
479
|
+
const today = store.dayOf();
|
|
480
|
+
|
|
481
|
+
if (isGroup) {
|
|
482
|
+
const grp = ensureGroup(cid, { title: chatTitle, surface: ch });
|
|
483
|
+
const mem = (uid && uid !== '0') ? ensureMemberInGroup(cid, uid, { name: senderName, groupTitle: chatTitle, surface: ch }) : null;
|
|
484
|
+
|
|
485
|
+
// Frozen Stable Block cached per (group, day) so systemPrompt stays byte-identical for Prompt Cache!
|
|
486
|
+
const cacheKey = `${cid}:group:${today}`;
|
|
487
|
+
let frozen = frozenSnapshots.get(cacheKey);
|
|
488
|
+
if (!frozen) {
|
|
489
|
+
const gSnap = grp ? store.snapshot(grp.sid, { budgetChars: 3000, excludeSession: rec?.groupSessionId || findTodaySession(grp.sid) }) : null;
|
|
490
|
+
const stableText = (gSnap && !gSnap.denied && gSnap.text) ? `<!-- Frozen Group Memory (${cid}) -->\n${gSnap.text}` : '';
|
|
491
|
+
frozen = { stableMemoryBlock: stableText, hash: gSnap?.hash || null, createdAt: Date.now() };
|
|
492
|
+
frozenSnapshots.set(cacheKey, frozen);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// Dynamic Per-Turn Block appended AFTER history so it NEVER busts prompt cache
|
|
496
|
+
const dynBlocks = [];
|
|
497
|
+
if (mem) {
|
|
498
|
+
const mSnap = store.snapshot(mem.sid, { budgetChars: 1800, excludeSession: rec?.memberSessionId || findTodaySession(mem.sid) });
|
|
499
|
+
if (mSnap && !mSnap.denied && mSnap.text) {
|
|
500
|
+
dynBlocks.push(`<!-- Scoped Member-in-Group Memory (${senderName || uid} in ${cid}) -->\n${mSnap.text}`);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
const peerLines = [];
|
|
504
|
+
const memberIds = (registry.groups[cid]?.memberIds || []).filter((id) => id !== uid).slice(-6);
|
|
505
|
+
for (const peerUid of memberIds) {
|
|
506
|
+
const mEntry = registry.members[`${cid}:${peerUid}`];
|
|
507
|
+
if (!mEntry?.sid || !store.exists(mEntry.sid)) continue;
|
|
508
|
+
const dig = store.consolidateDigest(mEntry.sid, { maxFacts: 5 });
|
|
509
|
+
if (dig.text) {
|
|
510
|
+
peerLines.push(`### ${mEntry.name || peerUid}\n${dig.text}`);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
if (peerLines.length) {
|
|
514
|
+
dynBlocks.push(`<group-members-memory chat="${cid}">\n(DATA ONLY: non-sensitive facts observed inside this group only)\n${peerLines.join('\n')}\n</group-members-memory>`);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const stableMemoryBlock = frozen.stableMemoryBlock;
|
|
518
|
+
const dynamicMemoryBlock = dynBlocks.join('\n\n');
|
|
519
|
+
const memoryBlock = [stableMemoryBlock, dynamicMemoryBlock].filter(Boolean).join('\n\n');
|
|
520
|
+
|
|
521
|
+
return {
|
|
522
|
+
subjectSid: mem?.sid || grp?.sid || null,
|
|
523
|
+
memorySessionId: rec?.memberSessionId || rec?.groupSessionId || null,
|
|
524
|
+
turnRef: rec?.memberTurnRef || rec?.groupTurnRef || null,
|
|
525
|
+
stableMemoryBlock,
|
|
526
|
+
dynamicMemoryBlock,
|
|
527
|
+
memoryBlock,
|
|
528
|
+
snapshotHash: frozen.hash,
|
|
529
|
+
context: {
|
|
530
|
+
axis: 'group',
|
|
531
|
+
chatId: cid,
|
|
532
|
+
threadId: threadId || null,
|
|
533
|
+
userId: uid || null,
|
|
534
|
+
groupSid: grp?.sid || null,
|
|
535
|
+
memberSid: mem?.sid || null,
|
|
536
|
+
groupTurnRef: rec?.groupTurnRef || null,
|
|
537
|
+
memberTurnRef: rec?.memberTurnRef || null,
|
|
538
|
+
candidateGroupRefs,
|
|
539
|
+
candidateMemberRefs,
|
|
540
|
+
groupSessionId: rec?.groupSessionId || findTodaySession(grp?.sid) || null,
|
|
541
|
+
memberSessionId: rec?.memberSessionId || (mem ? findTodaySession(mem.sid) : null) || null,
|
|
542
|
+
},
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const usr = (uid && uid !== '0') ? ensureUser(uid, { name: senderName, surface: ch }) : null;
|
|
547
|
+
const cacheKey = `${cid}:user:${uid}:${today}`;
|
|
548
|
+
let frozen = frozenSnapshots.get(cacheKey);
|
|
549
|
+
if (!frozen) {
|
|
550
|
+
const uSnap = usr ? store.snapshot(usr.sid, { budgetChars: 3800, excludeSession: rec?.userSessionId || findTodaySession(usr.sid) }) : null;
|
|
551
|
+
const stableText = (uSnap && !uSnap.denied && uSnap.text) ? `<!-- Frozen User DM Memory (${senderName || uid}) -->\n${uSnap.text}` : '';
|
|
552
|
+
frozen = { stableMemoryBlock: stableText, hash: uSnap?.hash || null, createdAt: Date.now() };
|
|
553
|
+
frozenSnapshots.set(cacheKey, frozen);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const dynBlocks = [];
|
|
557
|
+
if (uid && ownerSet.has(uid)) {
|
|
558
|
+
const grpList = Object.values(registry.groups);
|
|
559
|
+
if (grpList.length) {
|
|
560
|
+
const summary = grpList.map((g) => `- group ${g.chatId}${g.title ? ` (${g.title})` : ''}: ${g.memberIds.length} members, ${g.turns || 0} turns`).join('\n');
|
|
561
|
+
dynBlocks.push(`<tracked-groups-index>\n${summary}\n</tracked-groups-index>`);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const stableMemoryBlock = frozen.stableMemoryBlock;
|
|
566
|
+
const dynamicMemoryBlock = dynBlocks.join('\n\n');
|
|
567
|
+
const memoryBlock = [stableMemoryBlock, dynamicMemoryBlock].filter(Boolean).join('\n\n');
|
|
568
|
+
|
|
569
|
+
return {
|
|
570
|
+
subjectSid: usr?.sid || null,
|
|
571
|
+
memorySessionId: rec?.userSessionId || null,
|
|
572
|
+
turnRef: rec?.userTurnRef || null,
|
|
573
|
+
stableMemoryBlock,
|
|
574
|
+
dynamicMemoryBlock,
|
|
575
|
+
memoryBlock,
|
|
576
|
+
snapshotHash: frozen.hash,
|
|
577
|
+
context: {
|
|
578
|
+
axis: 'user',
|
|
579
|
+
chatId: cid,
|
|
580
|
+
userId: uid || null,
|
|
581
|
+
userSid: usr?.sid || null,
|
|
582
|
+
userTurnRef: rec?.userTurnRef || null,
|
|
583
|
+
candidateUserRefs,
|
|
584
|
+
userSessionId: rec?.userSessionId || (usr ? findTodaySession(usr.sid) : null) || null,
|
|
585
|
+
},
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
async function recordAssistantTurn({ text, agentName = 'assistant', memoryContext = null, channel: callChannel = null } = {}) {
|
|
590
|
+
const clean = String(text || '').trim();
|
|
591
|
+
if (!clean || !memoryContext) return;
|
|
592
|
+
const ch = resolveChannel(callChannel || channel);
|
|
593
|
+
if (memoryContext.axis === 'group' && memoryContext.groupSid) {
|
|
594
|
+
appendToSubjectSession(memoryContext.groupSid, { role: 'assistant', speaker: agentName, text: clean, surface: `${ch}-group` });
|
|
595
|
+
} else if (memoryContext.axis === 'user' && memoryContext.userSid) {
|
|
596
|
+
appendToSubjectSession(memoryContext.userSid, { role: 'assistant', speaker: agentName, text: clean, surface: `${ch}-dm` });
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
function onSessionReset(conversationId) {
|
|
601
|
+
invalidateFrozen(conversationId);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
async function onBeforeCompact({ conversationId, isGroup = false, memoryContext = null } = {}) {
|
|
605
|
+
const cid = normId(conversationId);
|
|
606
|
+
const mc = memoryContext || {};
|
|
607
|
+
const targets = [];
|
|
608
|
+
if (mc.groupSid && mc.groupSessionId) targets.push({ sid: mc.groupSid, sessionId: mc.groupSessionId, axis: 'group', chatId: cid });
|
|
609
|
+
if (mc.memberSid && mc.memberSessionId) targets.push({ sid: mc.memberSid, sessionId: mc.memberSessionId, axis: 'member', chatId: cid, userId: mc.userId });
|
|
610
|
+
if (mc.userSid && mc.userSessionId) targets.push({ sid: mc.userSid, sessionId: mc.userSessionId, axis: 'user', chatId: cid, userId: mc.userId });
|
|
611
|
+
if (!targets.length) {
|
|
612
|
+
if (isGroup && registry.groups[cid]?.sid) {
|
|
613
|
+
const s = findTodaySession(registry.groups[cid].sid);
|
|
614
|
+
if (s) targets.push({ sid: registry.groups[cid].sid, sessionId: s, axis: 'group', chatId: cid });
|
|
615
|
+
} else if (!isGroup && registry.users[cid]?.sid) {
|
|
616
|
+
const s = findTodaySession(registry.users[cid].sid);
|
|
617
|
+
if (s) targets.push({ sid: registry.users[cid].sid, sessionId: s, axis: 'user', chatId: cid, userId: cid });
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
for (const t of targets) {
|
|
621
|
+
scheduleSweep(t.sid, t.sessionId, t, { immediate: true });
|
|
622
|
+
}
|
|
623
|
+
invalidateFrozen(cid);
|
|
624
|
+
flushRegistry();
|
|
625
|
+
return { ok: true, flushed: targets.length };
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
async function flushIdleSessions({ idleMinutes = 45, provider = null, model = null } = {}) {
|
|
629
|
+
const todayPrefix = store.dayOf().replace(/-/g, '');
|
|
630
|
+
const cutoffMs = Date.now() - idleMinutes * 60_000;
|
|
631
|
+
const allEntries = [
|
|
632
|
+
...Object.values(registry.users).map((x) => ({ sid: x.sid, axis: 'user', chatId: x.userId, userId: x.userId, lastSeenAt: x.lastSeenAt })),
|
|
633
|
+
...Object.values(registry.groups).map((x) => ({ sid: x.sid, axis: 'group', chatId: x.chatId, lastSeenAt: x.lastSeenAt })),
|
|
634
|
+
...Object.values(registry.members).map((x) => ({ sid: x.sid, axis: 'member', chatId: x.chatId, userId: x.userId, lastSeenAt: x.lastSeenAt })),
|
|
635
|
+
];
|
|
636
|
+
let closed = 0, swept = 0;
|
|
637
|
+
for (const item of allEntries) {
|
|
638
|
+
if (!item.sid || !store.exists(item.sid)) continue;
|
|
639
|
+
const lastSeenMs = Date.parse(item.lastSeenAt || 0) || 0;
|
|
640
|
+
const isIdle = lastSeenMs > 0 && lastSeenMs < cutoffMs;
|
|
641
|
+
for (const s of store.listSessions(item.sid)) {
|
|
642
|
+
const isPastDay = !s.startsWith(todayPrefix);
|
|
643
|
+
if (!isPastDay && !isIdle) continue;
|
|
644
|
+
const lines = store.readSession(item.sid, s);
|
|
645
|
+
if (lines.some((l) => l.op === 'session_close')) continue;
|
|
646
|
+
if (provider && provider.ready) {
|
|
647
|
+
const r = await serializeSidJob(item.sid, () => runLlmSweep({ sid: item.sid, sessionId: s, axis: item.axis, provider, model }));
|
|
648
|
+
if (r?.ok && !r.skipped) swept++;
|
|
649
|
+
}
|
|
650
|
+
store.closeSession(item.sid, s, { reason: isPastDay ? 'daily' : 'idle' });
|
|
651
|
+
closed++;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
if (closed > 0 || swept > 0) invalidateFrozen(null);
|
|
655
|
+
return { ok: true, closed, swept };
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function pickEvidenceRef(evidenceSid, candidateRefs, quote) {
|
|
659
|
+
const refs = (candidateRefs || []).filter(Boolean);
|
|
660
|
+
if (!refs.length) return null;
|
|
661
|
+
if (quote && refs.length > 1) {
|
|
662
|
+
const q = String(quote).normalize('NFC').toLowerCase().replace(/\s+/g, ' ').trim();
|
|
663
|
+
for (const ref of refs) {
|
|
664
|
+
const turn = store.resolveRef(evidenceSid, ref);
|
|
665
|
+
if (turn?.text && String(turn.text).normalize('NFC').toLowerCase().replace(/\s+/g, ' ').includes(q)) {
|
|
666
|
+
return ref;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
return refs[refs.length - 1];
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
function rememberScoped({
|
|
674
|
+
scope = 'auto',
|
|
675
|
+
key,
|
|
676
|
+
value,
|
|
677
|
+
quote = null,
|
|
678
|
+
ctx = {},
|
|
679
|
+
targetChatId = null,
|
|
680
|
+
targetUserId = null,
|
|
681
|
+
explicitOwnerEdit = false,
|
|
682
|
+
} = {}) {
|
|
683
|
+
const mc = ctx.memoryContext || {};
|
|
684
|
+
const isGroup = mc.axis === 'group' || Boolean(ctx.turnClassification?.isGroup);
|
|
685
|
+
const callerUid = normId(ctx.sender?.id || ctx.sender?.channelId || mc.userId || '');
|
|
686
|
+
const isOwner = Boolean(callerUid && ownerSet.has(callerUid));
|
|
687
|
+
const isOwnerDm = !isGroup && isOwner;
|
|
688
|
+
|
|
689
|
+
const kStr = String(key || '');
|
|
690
|
+
const isGroupKey = kStr.startsWith('group.') || kStr.startsWith('decision.') || kStr.startsWith('topic.');
|
|
691
|
+
let targetAxis = 'user';
|
|
692
|
+
let targetSid = null;
|
|
693
|
+
let evidenceRef = null;
|
|
694
|
+
let evidenceSid = null;
|
|
695
|
+
let speakerSid = null;
|
|
696
|
+
|
|
697
|
+
if (scope === 'group' || (scope === 'auto' && isGroup && isGroupKey)) {
|
|
698
|
+
const gid = isOwnerDm && targetChatId ? normId(targetChatId) : mc.chatId;
|
|
699
|
+
if (!gid) return { ok: false, reason: 'missing_group_chat_id' };
|
|
700
|
+
targetAxis = 'group';
|
|
701
|
+
targetSid = ensureGroup(gid).sid;
|
|
702
|
+
evidenceSid = mc.groupSid || targetSid;
|
|
703
|
+
const gCandidates = mc.candidateGroupRefs?.length ? mc.candidateGroupRefs : [mc.groupTurnRef];
|
|
704
|
+
evidenceRef = pickEvidenceRef(evidenceSid, gCandidates, quote);
|
|
705
|
+
if (!evidenceRef && mc.memberTurnRef && mc.memberSid) {
|
|
706
|
+
evidenceSid = mc.memberSid;
|
|
707
|
+
evidenceRef = mc.memberTurnRef;
|
|
708
|
+
}
|
|
709
|
+
speakerSid = mc.memberSid || null;
|
|
710
|
+
} else if (scope === 'member' || (scope === 'auto' && isGroup)) {
|
|
711
|
+
const gid = isOwnerDm && targetChatId ? normId(targetChatId) : mc.chatId;
|
|
712
|
+
const uid = isOwnerDm && targetUserId ? normId(targetUserId) : callerUid;
|
|
713
|
+
if (!gid || !uid) return { ok: false, reason: 'missing_group_or_user_id' };
|
|
714
|
+
targetAxis = 'member';
|
|
715
|
+
const m = ensureMemberInGroup(gid, uid);
|
|
716
|
+
if (!m) return { ok: false, reason: 'invalid_member_id' };
|
|
717
|
+
targetSid = m.sid;
|
|
718
|
+
evidenceSid = m.sid;
|
|
719
|
+
const mCandidates = mc.candidateMemberRefs?.length ? mc.candidateMemberRefs : [mc.memberTurnRef];
|
|
720
|
+
evidenceRef = pickEvidenceRef(evidenceSid, mCandidates, quote);
|
|
721
|
+
speakerSid = m.sid;
|
|
722
|
+
} else {
|
|
723
|
+
if (isGroup) return { ok: false, reason: 'cannot_write_dm_user_memory_from_group' };
|
|
724
|
+
const uid = isOwnerDm && targetUserId ? normId(targetUserId) : callerUid;
|
|
725
|
+
if (!uid) return { ok: false, reason: 'missing_user_id' };
|
|
726
|
+
targetAxis = 'user';
|
|
727
|
+
const u = ensureUser(uid);
|
|
728
|
+
if (!u) return { ok: false, reason: 'invalid_user_id' };
|
|
729
|
+
targetSid = u.sid;
|
|
730
|
+
evidenceSid = u.sid;
|
|
731
|
+
const uCandidates = mc.candidateUserRefs?.length ? mc.candidateUserRefs : [mc.userTurnRef];
|
|
732
|
+
evidenceRef = pickEvidenceRef(evidenceSid, uCandidates, quote);
|
|
733
|
+
speakerSid = u.sid;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
const about = targetAxis === 'group' ? 'group' : 'self';
|
|
737
|
+
|
|
738
|
+
if (explicitOwnerEdit && isOwnerDm) {
|
|
739
|
+
const res = store.propose(targetSid, { key, value, about, provenance: 'user_edit', system: 'owner_dm' }, { trusted: true, reviewed: true, by: 'owner' });
|
|
740
|
+
if (res.ok) invalidateFrozen(mc.chatId || targetChatId);
|
|
741
|
+
return { ...res, axis: targetAxis };
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
if (!evidenceRef || !quote || !String(quote).trim()) {
|
|
745
|
+
return { ok: false, reason: 'missing_verbatim_evidence_quote', axis: targetAxis };
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
const proposal = {
|
|
749
|
+
key,
|
|
750
|
+
value,
|
|
751
|
+
about,
|
|
752
|
+
quote: String(quote).trim(),
|
|
753
|
+
ref: evidenceRef,
|
|
754
|
+
evidence_sid: evidenceSid || targetSid,
|
|
755
|
+
speaker_sid: speakerSid || targetSid,
|
|
756
|
+
provenance: 'stated',
|
|
757
|
+
};
|
|
758
|
+
|
|
759
|
+
if (isGroup && targetAxis === 'group' && !isOwner && (kStr.startsWith('group.') || kStr.startsWith('decision.'))) {
|
|
760
|
+
const check = store.gate(targetSid, proposal);
|
|
761
|
+
if (!check.ok) return { ...check, axis: targetAxis };
|
|
762
|
+
const revDir = path.join(store.subjectDir(targetSid), 'review');
|
|
763
|
+
fs.mkdirSync(revDir, { recursive: true });
|
|
764
|
+
const rid = 'r_' + crypto.createHash('sha256').update(JSON.stringify(proposal) + Date.now()).digest('hex').slice(0, 10);
|
|
765
|
+
writeAtomic(path.join(revDir, `${rid}.json`), {
|
|
766
|
+
id: rid,
|
|
767
|
+
ts: new Date().toISOString(),
|
|
768
|
+
kind: 'fact',
|
|
769
|
+
proposal,
|
|
770
|
+
reason: 'non_owner_group_decision_requires_review',
|
|
771
|
+
proposedBy: { userId: callerUid, name: ctx.sender?.name || null, chatId: mc.chatId },
|
|
772
|
+
});
|
|
773
|
+
return { ok: false, queued: rid, reason: 'queued_for_owner_review', axis: targetAxis };
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
const res = store.propose(targetSid, proposal);
|
|
777
|
+
if (res.ok) invalidateFrozen(mc.chatId || targetChatId);
|
|
778
|
+
return { ...res, axis: targetAxis };
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function forgetScoped({ scope = 'user', factId, chatId = null, userId = null, ctx = {} } = {}) {
|
|
782
|
+
const mc = ctx.memoryContext || {};
|
|
783
|
+
const isGroup = mc.axis === 'group' || Boolean(ctx.turnClassification?.isGroup);
|
|
784
|
+
const callerUid = normId(ctx.sender?.id || ctx.sender?.channelId || mc.userId || '');
|
|
785
|
+
const isOwnerDm = !isGroup && Boolean(callerUid && ownerSet.has(callerUid));
|
|
786
|
+
|
|
787
|
+
if (isGroup) return { ok: false, reason: 'forget_requires_dm' };
|
|
788
|
+
if (!factId) return { ok: false, reason: 'missing_fact_id' };
|
|
789
|
+
|
|
790
|
+
let targetSid = null;
|
|
791
|
+
let resolvedChatId = chatId ? normId(chatId) : null;
|
|
792
|
+
if (scope === 'group') {
|
|
793
|
+
if (!isOwnerDm) return { ok: false, reason: 'owner_dm_required' };
|
|
794
|
+
targetSid = resolvedChatId ? registry.groups[resolvedChatId]?.sid : null;
|
|
795
|
+
} else if (scope === 'member') {
|
|
796
|
+
if (!isOwnerDm) return { ok: false, reason: 'owner_dm_required' };
|
|
797
|
+
const uid = normId(userId);
|
|
798
|
+
targetSid = (resolvedChatId && uid) ? registry.members[`${resolvedChatId}:${uid}`]?.sid : null;
|
|
799
|
+
} else {
|
|
800
|
+
const uid = isOwnerDm && userId ? normId(userId) : callerUid;
|
|
801
|
+
resolvedChatId = uid || resolvedChatId;
|
|
802
|
+
targetSid = uid ? registry.users[uid]?.sid : null;
|
|
803
|
+
}
|
|
804
|
+
if (!targetSid || !store.exists(targetSid)) return { ok: false, reason: 'subject_not_found' };
|
|
805
|
+
|
|
806
|
+
const st = store.state(targetSid);
|
|
807
|
+
const targetFact = [...st.facts, ...st.history].find((f) => f.id === factId);
|
|
808
|
+
const needles = targetFact
|
|
809
|
+
? [targetFact.value, targetFact.evidence?.quote].filter((x) => x && String(x).trim().length >= 3)
|
|
810
|
+
: [];
|
|
811
|
+
|
|
812
|
+
const res = store.forget(targetSid, [factId], { reason: 'user_request', by: isOwnerDm ? 'owner' : 'user' });
|
|
813
|
+
if (!res.ok) return res;
|
|
814
|
+
|
|
815
|
+
let siblingScrubbed = 0;
|
|
816
|
+
if (needles.length && (scope === 'group' || scope === 'member') && resolvedChatId) {
|
|
817
|
+
const siblingSids = new Set();
|
|
818
|
+
if (registry.groups[resolvedChatId]?.sid) siblingSids.add(registry.groups[resolvedChatId].sid);
|
|
819
|
+
for (const uid of registry.groups[resolvedChatId]?.memberIds || []) {
|
|
820
|
+
const m = registry.members[`${resolvedChatId}:${uid}`];
|
|
821
|
+
if (m?.sid) siblingSids.add(m.sid);
|
|
822
|
+
}
|
|
823
|
+
siblingSids.delete(targetSid);
|
|
824
|
+
for (const sibSid of siblingSids) {
|
|
825
|
+
if (!store.exists(sibSid)) continue;
|
|
826
|
+
const sc = store.scrubSubject(sibSid, needles, { reason: 'cross_subject_forget', by: isOwnerDm ? 'owner' : 'user' });
|
|
827
|
+
if (sc.matchingFactIds?.length) {
|
|
828
|
+
store.forget(sibSid, sc.matchingFactIds, { reason: 'cross_subject_forget', by: isOwnerDm ? 'owner' : 'user' });
|
|
829
|
+
}
|
|
830
|
+
siblingScrubbed++;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
if (needles.length && typeof onScrubExternal === 'function') {
|
|
835
|
+
try { onScrubExternal({ chatId: resolvedChatId, needles }); } catch { /* ignore */ }
|
|
836
|
+
}
|
|
837
|
+
invalidateFrozen(resolvedChatId);
|
|
838
|
+
return { ...res, siblingScrubbed };
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
function recordLesson({ lesson, trigger = '', scope = 'agent', source = 'owner-correction', approved = false, ctx = {} } = {}) {
|
|
842
|
+
const cleanLesson = String(lesson || '').trim();
|
|
843
|
+
if (!cleanLesson) return { ok: false, reason: 'empty_lesson' };
|
|
844
|
+
const mc = ctx.memoryContext || {};
|
|
845
|
+
const isGroup = mc.axis === 'group' || Boolean(ctx.turnClassification?.isGroup);
|
|
846
|
+
const callerUid = normId(ctx.sender?.id || ctx.sender?.channelId || mc.userId || '');
|
|
847
|
+
const isOwnerDm = !isGroup && Boolean(callerUid && ownerSet.has(callerUid));
|
|
848
|
+
|
|
849
|
+
if (!isOwnerDm || !approved) {
|
|
850
|
+
const ownerId = [...ownerSet][0];
|
|
851
|
+
if (!ownerId) return { ok: false, reason: 'owner_required_for_lesson' };
|
|
852
|
+
const ownerSubj = ensureUser(ownerId);
|
|
853
|
+
const revDir = path.join(store.subjectDir(ownerSubj.sid), 'review');
|
|
854
|
+
fs.mkdirSync(revDir, { recursive: true });
|
|
855
|
+
const rid = 'r_' + crypto.createHash('sha256').update(cleanLesson + Date.now()).digest('hex').slice(0, 10);
|
|
856
|
+
writeAtomic(path.join(revDir, `${rid}.json`), {
|
|
857
|
+
id: rid,
|
|
858
|
+
ts: new Date().toISOString(),
|
|
859
|
+
kind: 'lesson',
|
|
860
|
+
lesson: cleanLesson,
|
|
861
|
+
trigger: String(trigger || '').trim(),
|
|
862
|
+
scope,
|
|
863
|
+
source,
|
|
864
|
+
reason: 'lesson_requires_owner_approval',
|
|
865
|
+
});
|
|
866
|
+
return { ok: false, queued: rid, reason: 'queued_for_owner_review' };
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
if (!lessonsPath) return { ok: false, reason: 'agent_dir_not_configured' };
|
|
870
|
+
fs.mkdirSync(path.dirname(lessonsPath), { recursive: true });
|
|
871
|
+
const existing = fs.existsSync(lessonsPath) ? fs.readFileSync(lessonsPath, 'utf8') : '# Procedural Lessons (L5 · Never-Decay)\n';
|
|
872
|
+
if (fold(existing).includes(fold(cleanLesson))) {
|
|
873
|
+
return { ok: true, duplicate: true, path: lessonsPath };
|
|
874
|
+
}
|
|
875
|
+
const day = store.dayOf();
|
|
876
|
+
const trigPart = trigger ? ` (trigger: ${String(trigger).replace(/\s+/g, ' ').trim().slice(0, 120)})` : '';
|
|
877
|
+
const entry = `\n- **[${day}] [${source}] [${scope}]** ${cleanLesson}${trigPart}\n`;
|
|
878
|
+
fs.appendFileSync(lessonsPath, entry, 'utf8');
|
|
879
|
+
try { onReloadAgent?.(); } catch { /* ignore */ }
|
|
880
|
+
return { ok: true, path: lessonsPath, reloaded: typeof onReloadAgent === 'function' };
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
function updateOpenLoops({ scope = 'auto', chatId = null, userId = null, items = [], ctx = {} } = {}) {
|
|
884
|
+
const mc = ctx.memoryContext || {};
|
|
885
|
+
const isGroup = mc.axis === 'group' || Boolean(ctx.turnClassification?.isGroup);
|
|
886
|
+
const callerUid = normId(ctx.sender?.id || ctx.sender?.channelId || mc.userId || '');
|
|
887
|
+
const isOwnerDm = !isGroup && Boolean(callerUid && ownerSet.has(callerUid));
|
|
888
|
+
|
|
889
|
+
let targetSid = null;
|
|
890
|
+
if (scope === 'group' || (scope === 'auto' && isGroup)) {
|
|
891
|
+
const gid = isOwnerDm && chatId ? normId(chatId) : mc.chatId;
|
|
892
|
+
targetSid = gid ? ensureGroup(gid)?.sid : null;
|
|
893
|
+
} else if (scope === 'member') {
|
|
894
|
+
const gid = isOwnerDm && chatId ? normId(chatId) : mc.chatId;
|
|
895
|
+
const uid = isOwnerDm && userId ? normId(userId) : callerUid;
|
|
896
|
+
targetSid = (gid && uid) ? ensureMemberInGroup(gid, uid)?.sid : null;
|
|
897
|
+
} else {
|
|
898
|
+
if (isGroup) return { ok: false, reason: 'cannot_write_dm_open_loops_from_group' };
|
|
899
|
+
const uid = isOwnerDm && userId ? normId(userId) : callerUid;
|
|
900
|
+
targetSid = uid ? ensureUser(uid)?.sid : null;
|
|
901
|
+
}
|
|
902
|
+
if (!targetSid) return { ok: false, reason: 'subject_not_found' };
|
|
903
|
+
const cleanItems = (Array.isArray(items) ? items : []).map((x) => String(x || '').trim()).filter(Boolean).slice(0, 15);
|
|
904
|
+
store.setOpenLoops(targetSid, cleanItems);
|
|
905
|
+
invalidateFrozen(mc.chatId || chatId);
|
|
906
|
+
return { ok: true, count: cleanItems.length };
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async function searchScoped({ query, axis = 'all', chatId = null, userId = null, limit = 8, ctx = {} } = {}) {
|
|
910
|
+
const mc = ctx.memoryContext || {};
|
|
911
|
+
const isGroup = mc.axis === 'group' || Boolean(ctx.turnClassification?.isGroup);
|
|
912
|
+
const callerUid = normId(ctx.sender?.id || ctx.sender?.channelId || mc.userId || '');
|
|
913
|
+
const isOwnerDm = !isGroup && Boolean(callerUid && ownerSet.has(callerUid));
|
|
914
|
+
|
|
915
|
+
const targets = [];
|
|
916
|
+
if (isGroup) {
|
|
917
|
+
const gid = mc.chatId;
|
|
918
|
+
if (!gid) return { hits: [] };
|
|
919
|
+
if ((axis === 'all' || axis === 'group') && registry.groups[gid]?.sid) {
|
|
920
|
+
targets.push({ axis: 'group', chatId: gid, label: registry.groups[gid].title || gid, sid: registry.groups[gid].sid, session: mc.groupSessionId || null, allowSensitive: false });
|
|
921
|
+
}
|
|
922
|
+
if (axis === 'all' || axis === 'member') {
|
|
923
|
+
const filterUid = userId ? normId(userId) : null;
|
|
924
|
+
for (const uid of registry.groups[gid]?.memberIds || []) {
|
|
925
|
+
if (filterUid && uid !== filterUid) continue;
|
|
926
|
+
const m = registry.members[`${gid}:${uid}`];
|
|
927
|
+
if (m?.sid) {
|
|
928
|
+
targets.push({
|
|
929
|
+
axis: 'member',
|
|
930
|
+
chatId: gid,
|
|
931
|
+
userId: uid,
|
|
932
|
+
label: m.name || uid,
|
|
933
|
+
sid: m.sid,
|
|
934
|
+
session: uid === callerUid ? (mc.memberSessionId || null) : null,
|
|
935
|
+
allowSensitive: uid === callerUid,
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
} else if (!isOwnerDm) {
|
|
941
|
+
if (callerUid && registry.users[callerUid]?.sid) {
|
|
942
|
+
targets.push({ axis: 'user', userId: callerUid, label: registry.users[callerUid].name || callerUid, sid: registry.users[callerUid].sid, session: mc.userSessionId || null, allowSensitive: true });
|
|
943
|
+
}
|
|
944
|
+
} else {
|
|
945
|
+
const filterGid = chatId ? normId(chatId) : null;
|
|
946
|
+
const filterUid = userId ? normId(userId) : null;
|
|
947
|
+
if (axis === 'all' || axis === 'user') {
|
|
948
|
+
for (const u of Object.values(registry.users)) {
|
|
949
|
+
if (filterUid && u.userId !== filterUid) continue;
|
|
950
|
+
targets.push({ axis: 'user', userId: u.userId, label: u.name || u.userId, sid: u.sid, session: u.userId === callerUid ? (mc.userSessionId || null) : null, allowSensitive: true });
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
if (axis === 'all' || axis === 'group') {
|
|
954
|
+
for (const g of Object.values(registry.groups)) {
|
|
955
|
+
if (filterGid && g.chatId !== filterGid) continue;
|
|
956
|
+
targets.push({ axis: 'group', chatId: g.chatId, label: g.title || g.chatId, sid: g.sid, session: mc.userSessionId || null, allowSensitive: true });
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
if (axis === 'all' || axis === 'member') {
|
|
960
|
+
for (const m of Object.values(registry.members)) {
|
|
961
|
+
if (filterGid && m.chatId !== filterGid) continue;
|
|
962
|
+
if (filterUid && m.userId !== filterUid) continue;
|
|
963
|
+
targets.push({ axis: 'member', chatId: m.chatId, userId: m.userId, label: `${m.name || m.userId} @ ${m.chatId}`, sid: m.sid, session: mc.userSessionId || null, allowSensitive: true });
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
const allHits = [];
|
|
969
|
+
for (const t of targets) {
|
|
970
|
+
if (!store.exists(t.sid)) continue;
|
|
971
|
+
const r = typeof embedFn === 'function'
|
|
972
|
+
? await store.searchHybrid(t.sid, { query: String(query || ''), limit, session: t.session, embed: embedFn })
|
|
973
|
+
: store.searchRanked(t.sid, { query: String(query || ''), limit, session: t.session });
|
|
974
|
+
for (const h of r.hits || []) {
|
|
975
|
+
if (h.sensitive && !t.allowSensitive) continue;
|
|
976
|
+
allHits.push({ ...h, axis: t.axis, chatId: t.chatId || null, userId: t.userId || null, scopeLabel: t.label });
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
allHits.sort((a, b) => (b.score - a.score) || String(b.ts).localeCompare(String(a.ts)));
|
|
980
|
+
return { hits: allHits.slice(0, Math.min(25, Math.max(1, Number(limit || 8)))) };
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
function inspectSummary({ chatId = null, userId = null, mode = 'owner_dm' } = {}) {
|
|
984
|
+
const normChat = chatId ? normId(chatId) : null;
|
|
985
|
+
const normUser = userId ? normId(userId) : null;
|
|
986
|
+
|
|
987
|
+
if (mode === 'user_dm') {
|
|
988
|
+
if (!normUser) return { users: [] };
|
|
989
|
+
const u = registry.users[normUser];
|
|
990
|
+
return {
|
|
991
|
+
users: u ? [{
|
|
992
|
+
userId: u.userId,
|
|
993
|
+
name: u.name,
|
|
994
|
+
turns: u.turns || 0,
|
|
995
|
+
facts: store.exists(u.sid) ? store.state(u.sid).facts.map((f) => ({ id: f.id, key: f.key, value: f.value })) : [],
|
|
996
|
+
}] : [],
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
if (mode === 'group') {
|
|
1001
|
+
if (!normChat) return { groups: [], members: [] };
|
|
1002
|
+
const g = registry.groups[normChat];
|
|
1003
|
+
const groups = g ? [{
|
|
1004
|
+
chatId: g.chatId,
|
|
1005
|
+
title: g.title,
|
|
1006
|
+
memberCount: (g.memberIds || []).length,
|
|
1007
|
+
turns: g.turns || 0,
|
|
1008
|
+
facts: store.exists(g.sid)
|
|
1009
|
+
? store.state(g.sid).facts.filter((f) => f.sensitivity !== 'sensitive').map((f) => ({ id: f.id, key: f.key, value: f.value }))
|
|
1010
|
+
: [],
|
|
1011
|
+
}] : [];
|
|
1012
|
+
const members = Object.values(registry.members)
|
|
1013
|
+
.filter((m) => m.chatId === normChat && (!normUser || m.userId === normUser))
|
|
1014
|
+
.map((m) => ({
|
|
1015
|
+
chatId: m.chatId,
|
|
1016
|
+
userId: m.userId,
|
|
1017
|
+
name: m.name,
|
|
1018
|
+
turns: m.turns || 0,
|
|
1019
|
+
facts: store.exists(m.sid)
|
|
1020
|
+
? store.state(m.sid).facts.filter((f) => f.sensitivity !== 'sensitive').map((f) => ({ id: f.id, key: f.key, value: f.value }))
|
|
1021
|
+
: [],
|
|
1022
|
+
}));
|
|
1023
|
+
return { groups, members };
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
const users = Object.values(registry.users)
|
|
1027
|
+
.filter((u) => !normUser || u.userId === normUser)
|
|
1028
|
+
.map((u) => ({
|
|
1029
|
+
userId: u.userId,
|
|
1030
|
+
name: u.name,
|
|
1031
|
+
turns: u.turns || 0,
|
|
1032
|
+
facts: store.exists(u.sid) ? store.state(u.sid).facts.map((f) => ({ id: f.id, key: f.key, value: f.value })) : [],
|
|
1033
|
+
}));
|
|
1034
|
+
const groups = Object.values(registry.groups)
|
|
1035
|
+
.filter((g) => !normChat || g.chatId === normChat)
|
|
1036
|
+
.map((g) => ({
|
|
1037
|
+
chatId: g.chatId,
|
|
1038
|
+
title: g.title,
|
|
1039
|
+
memberCount: (g.memberIds || []).length,
|
|
1040
|
+
turns: g.turns || 0,
|
|
1041
|
+
facts: store.exists(g.sid) ? store.state(g.sid).facts.map((f) => ({ id: f.id, key: f.key, value: f.value })) : [],
|
|
1042
|
+
}));
|
|
1043
|
+
const members = Object.values(registry.members)
|
|
1044
|
+
.filter((m) => (!normChat || m.chatId === normChat) && (!normUser || m.userId === normUser))
|
|
1045
|
+
.map((m) => ({
|
|
1046
|
+
chatId: m.chatId,
|
|
1047
|
+
userId: m.userId,
|
|
1048
|
+
name: m.name,
|
|
1049
|
+
turns: m.turns || 0,
|
|
1050
|
+
facts: store.exists(m.sid) ? store.state(m.sid).facts.map((f) => ({ id: f.id, key: f.key, value: f.value })) : [],
|
|
1051
|
+
}));
|
|
1052
|
+
return { users, groups, members };
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
function listAllSubjects() {
|
|
1056
|
+
return [
|
|
1057
|
+
...Object.values(registry.users).map((x) => ({ sid: x.sid, axis: 'user', label: x.name || x.userId, userId: x.userId })),
|
|
1058
|
+
...Object.values(registry.groups).map((x) => ({ sid: x.sid, axis: 'group', label: x.title || x.chatId, chatId: x.chatId })),
|
|
1059
|
+
...Object.values(registry.members).map((x) => ({ sid: x.sid, axis: 'member', label: `${x.name || x.userId} @ ${x.chatId}`, chatId: x.chatId, userId: x.userId })),
|
|
1060
|
+
].filter((x) => x.sid && store.exists(x.sid));
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
function listPendingReviews() {
|
|
1064
|
+
const items = [];
|
|
1065
|
+
for (const s of listAllSubjects()) {
|
|
1066
|
+
for (const rv of store.listReview(s.sid)) {
|
|
1067
|
+
items.push({ ...rv, sid: s.sid, axis: s.axis, subjectLabel: s.label, chatId: s.chatId || null, userId: s.userId || null });
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
return items.sort((a, b) => String(a.ts || '').localeCompare(String(b.ts || '')));
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
function resolveReviewItem({ sid, reviewId, decision, by = 'owner' } = {}) {
|
|
1074
|
+
if (!sid || !reviewId || !store.exists(sid)) return { ok: false, reason: 'not_found' };
|
|
1075
|
+
const p = path.join(store.subjectDir(sid), 'review', `${reviewId}.json`);
|
|
1076
|
+
if (!fs.existsSync(p)) return { ok: false, reason: 'not_found' };
|
|
1077
|
+
const item = JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
1078
|
+
if (item.kind === 'lesson') {
|
|
1079
|
+
if (decision === 'accept') {
|
|
1080
|
+
const lr = recordLesson({
|
|
1081
|
+
lesson: item.lesson,
|
|
1082
|
+
trigger: item.trigger,
|
|
1083
|
+
scope: item.scope,
|
|
1084
|
+
source: item.source || 'owner-approved',
|
|
1085
|
+
approved: true,
|
|
1086
|
+
ctx: { sender: { id: [...ownerSet][0] || '' } },
|
|
1087
|
+
});
|
|
1088
|
+
if (!lr.ok) return { ...lr, kept: true };
|
|
1089
|
+
} else if (decision !== 'reject') {
|
|
1090
|
+
return { ok: false, reason: 'decision must be accept|reject' };
|
|
1091
|
+
}
|
|
1092
|
+
fs.rmSync(p, { force: true });
|
|
1093
|
+
return { ok: true, decision, kind: 'lesson' };
|
|
1094
|
+
}
|
|
1095
|
+
const r = store.resolveReview(sid, reviewId, decision, { by });
|
|
1096
|
+
if (r.ok) invalidateFrozen(null);
|
|
1097
|
+
return r;
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
function listFailedDreams() {
|
|
1101
|
+
const failed = [];
|
|
1102
|
+
for (const s of listAllSubjects()) {
|
|
1103
|
+
const df = path.join(store.subjectDir(s.sid), 'journal', 'DREAM');
|
|
1104
|
+
if (!fs.existsSync(df)) continue;
|
|
1105
|
+
try {
|
|
1106
|
+
const d = JSON.parse(fs.readFileSync(df, 'utf8'));
|
|
1107
|
+
if (d.status === 'failed') failed.push({ ...s, ts: d.ts, error: d.error });
|
|
1108
|
+
} catch { /* ignore */ }
|
|
1109
|
+
}
|
|
1110
|
+
return failed;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
function getStats() {
|
|
1114
|
+
const full = inspectSummary({ mode: 'owner_dm' });
|
|
1115
|
+
const userFacts = full.users.reduce((n, u) => n + u.facts.length, 0);
|
|
1116
|
+
const groupFacts = full.groups.reduce((n, g) => n + g.facts.length, 0);
|
|
1117
|
+
const memberFacts = full.members.reduce((n, m) => n + m.facts.length, 0);
|
|
1118
|
+
const totalTurns = full.users.reduce((n, u) => n + u.turns, 0) + full.groups.reduce((n, g) => n + g.turns, 0);
|
|
1119
|
+
const pendingReviews = listPendingReviews();
|
|
1120
|
+
const failedDreams = listFailedDreams();
|
|
1121
|
+
return {
|
|
1122
|
+
usersCount: full.users.length,
|
|
1123
|
+
groupsCount: full.groups.length,
|
|
1124
|
+
membersCount: full.members.length,
|
|
1125
|
+
userFacts,
|
|
1126
|
+
groupFacts,
|
|
1127
|
+
memberFacts,
|
|
1128
|
+
totalFacts: userFacts + groupFacts + memberFacts,
|
|
1129
|
+
totalTurns,
|
|
1130
|
+
totalSweeps: Number(registry.meta?.totalSweeps || 0),
|
|
1131
|
+
totalDreams: Number(registry.meta?.totalDreams || 0),
|
|
1132
|
+
pendingSweepsCount: Object.keys(registry.pendingSweeps || {}).length,
|
|
1133
|
+
pendingReviewsCount: pendingReviews.length,
|
|
1134
|
+
failedDreamsCount: failedDreams.length,
|
|
1135
|
+
users: full.users.map((u) => ({ userId: u.userId, name: u.name, turns: u.turns, factsCount: u.facts.length })),
|
|
1136
|
+
groups: full.groups.map((g) => ({ chatId: g.chatId, title: g.title, memberCount: g.memberCount, turns: g.turns, factsCount: g.facts.length })),
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
function consolidateAll() {
|
|
1141
|
+
let consolidated = 0;
|
|
1142
|
+
for (const s of listAllSubjects()) {
|
|
1143
|
+
store.consolidate(s.sid);
|
|
1144
|
+
consolidated++;
|
|
1145
|
+
}
|
|
1146
|
+
invalidateFrozen(null);
|
|
1147
|
+
return { ok: true, consolidatedSubjects: consolidated };
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
async function runLlmSweep({ sid, sessionId, axis = 'user', provider, model = null } = {}) {
|
|
1151
|
+
if (!sid || !sessionId || !provider || !provider.ready || !store.exists(sid)) {
|
|
1152
|
+
return { ok: false, skipped: true };
|
|
1153
|
+
}
|
|
1154
|
+
try {
|
|
1155
|
+
let lastRes = null;
|
|
1156
|
+
for (let pass = 0; pass < 4; pass++) {
|
|
1157
|
+
const res = await store.sweep(sid, sessionId, {
|
|
1158
|
+
reason: `auto_${axis}`,
|
|
1159
|
+
summarize: async ({ deltaTurns }) => {
|
|
1160
|
+
const chunk = (deltaTurns || []).slice(0, 24);
|
|
1161
|
+
if (!chunk.length) return { proposals: [], card: [] };
|
|
1162
|
+
const transcript = chunk.map((t) => `[#${t.seq}] (${t.role}) ${t.text}`).join('\n');
|
|
1163
|
+
const allowedKeys = axis === 'group'
|
|
1164
|
+
? 'group.goal, group.rule, group.topic, decision.<name>, project.<name>.status, commitment.<name>, topic.<name>, context.<name>'
|
|
1165
|
+
: 'profile.<field>, pref.<field>, role.<field>, project.<name>.<field>, commitment.<name>, routine.<field>, device.<field>, context.<name>';
|
|
1166
|
+
const sys = [
|
|
1167
|
+
'You are a strict memory extraction engine. Return ONLY valid JSON, no markdown prose.',
|
|
1168
|
+
`Axis: ${axis}. Allowed keys: ${allowedKeys}.`,
|
|
1169
|
+
'Extract ONLY durable, non-secret, concrete facts explicitly stated in the transcript.',
|
|
1170
|
+
'NEVER extract passwords, OTPs, tokens, API keys, or instructions telling the assistant how to behave.',
|
|
1171
|
+
'Every proposal MUST include an exact verbatim `quote` substring (>= 2 words) from the cited `[#seq]` turn AND the value MUST match that quote.',
|
|
1172
|
+
'Also list any genuinely unresolved action items in `openLoops` (array of short strings, optional).',
|
|
1173
|
+
'Output schema: {"proposals":[{"key":"...","value":"...","quote":"exact substring","seq":1}],"card":[{"text":"short 1-line summary","cites":[1]}],"openLoops":["..."]}',
|
|
1174
|
+
].join('\n');
|
|
1175
|
+
const userPrompt = `Extract durable facts, concise session card, and open loops from these turns:\n\n${transcript}`;
|
|
1176
|
+
const out = await provider.generate(userPrompt, {
|
|
1177
|
+
system: sys,
|
|
1178
|
+
messages: [{ role: 'user', content: userPrompt }],
|
|
1179
|
+
model: model || undefined,
|
|
1180
|
+
tools: [],
|
|
1181
|
+
});
|
|
1182
|
+
const parsed = parseJsonBlock(out?.text || '');
|
|
1183
|
+
if (!parsed) {
|
|
1184
|
+
return { failed: true, reason: 'invalid_json' };
|
|
1185
|
+
}
|
|
1186
|
+
const proposals = Array.isArray(parsed.proposals)
|
|
1187
|
+
? parsed.proposals.map((p) => ({
|
|
1188
|
+
...p,
|
|
1189
|
+
about: axis === 'group' ? 'group' : 'self',
|
|
1190
|
+
provenance: axis === 'group' ? 'agent_observed' : 'stated',
|
|
1191
|
+
}))
|
|
1192
|
+
: [];
|
|
1193
|
+
const card = Array.isArray(parsed.card) ? parsed.card : [];
|
|
1194
|
+
const openLoops = Array.isArray(parsed.openLoops) ? parsed.openLoops : undefined;
|
|
1195
|
+
return { proposals, card, openLoops, upto: chunk[chunk.length - 1].seq };
|
|
1196
|
+
},
|
|
1197
|
+
});
|
|
1198
|
+
lastRes = res;
|
|
1199
|
+
if (!res?.ok || res.skipped) break;
|
|
1200
|
+
registry.meta.totalSweeps = Number(registry.meta.totalSweeps || 0) + 1;
|
|
1201
|
+
markDirty();
|
|
1202
|
+
const remaining = store.readSession(sid, sessionId).filter((l) => l.op === 'turn' && l.seq > (res.upto || 0));
|
|
1203
|
+
if (!remaining.length) break;
|
|
1204
|
+
}
|
|
1205
|
+
flushRegistry();
|
|
1206
|
+
return lastRes || { ok: true, skipped: true };
|
|
1207
|
+
} catch (err) {
|
|
1208
|
+
return { ok: false, error: err?.message || String(err) };
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
async function runDreamSubject({ sid, axis = 'user', provider, model = null, force = false, ack = false } = {}) {
|
|
1213
|
+
if (!sid || !provider || !provider.ready || !store.exists(sid)) {
|
|
1214
|
+
return { ok: false, skipped: true, reason: 'provider_or_subject_unavailable' };
|
|
1215
|
+
}
|
|
1216
|
+
return serializeSidJob(sid, async () => {
|
|
1217
|
+
try {
|
|
1218
|
+
const res = await store.dream(sid, {
|
|
1219
|
+
force,
|
|
1220
|
+
ack,
|
|
1221
|
+
propose: async ({ facts, cards }) => {
|
|
1222
|
+
if (!facts.length && !cards.length) return { ops: [] };
|
|
1223
|
+
const sys = [
|
|
1224
|
+
'You are a strict Memory Dream consolidation engine. Return ONLY valid JSON.',
|
|
1225
|
+
`Subject axis: ${axis}.`,
|
|
1226
|
+
'Your job: merge duplicate/overlapping facts into cleaner derived facts (citing exact source fact IDs in `derived_from`), or expire obsolete/contradicted facts (citing exact IDs in `ids`).',
|
|
1227
|
+
'NEVER invent facts unsupported by existing facts. NEVER drop important constraints. If nothing needs consolidation, return {"ops":[]}.',
|
|
1228
|
+
'Output schema: {"ops":[{"action":"merge","key":"...","value":"...","about":"self|group","derived_from":["f_..."]},{"action":"expire","ids":["f_..."]}]}',
|
|
1229
|
+
].join('\n');
|
|
1230
|
+
const userPrompt = `Current active facts:\n${JSON.stringify(facts, null, 2)}\n\nRecent swept session cards:\n${cards.map((c) => `--- ${c.session} ---\n${c.card}`).join('\n')}`;
|
|
1231
|
+
const out = await provider.generate(userPrompt, {
|
|
1232
|
+
system: sys,
|
|
1233
|
+
messages: [{ role: 'user', content: userPrompt }],
|
|
1234
|
+
model: model || undefined,
|
|
1235
|
+
tools: [],
|
|
1236
|
+
});
|
|
1237
|
+
const parsed = parseJsonBlock(out?.text || '');
|
|
1238
|
+
if (!parsed || !Array.isArray(parsed.ops)) {
|
|
1239
|
+
throw new Error('dream_invalid_json');
|
|
1240
|
+
}
|
|
1241
|
+
return { ops: parsed.ops };
|
|
1242
|
+
},
|
|
1243
|
+
});
|
|
1244
|
+
if (res?.ok) {
|
|
1245
|
+
registry.meta.totalDreams = Number(registry.meta.totalDreams || 0) + 1;
|
|
1246
|
+
invalidateFrozen(null);
|
|
1247
|
+
markDirty({ immediate: true });
|
|
1248
|
+
}
|
|
1249
|
+
return res;
|
|
1250
|
+
} catch (err) {
|
|
1251
|
+
return { ok: false, reason: 'dream_exception', error: err?.message || String(err) };
|
|
1252
|
+
}
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
async function runDreamAll({ provider, model = null, force = false, ack = false } = {}) {
|
|
1257
|
+
const summary = { dreamed: 0, skippedGate: 0, failed: [], opsApplied: 0, queuedReviews: 0 };
|
|
1258
|
+
for (const s of listAllSubjects()) {
|
|
1259
|
+
const r = await runDreamSubject({ sid: s.sid, axis: s.axis, provider, model, force, ack });
|
|
1260
|
+
if (r.ok) {
|
|
1261
|
+
summary.dreamed++;
|
|
1262
|
+
for (const op of r.results || []) {
|
|
1263
|
+
if (op.ok) summary.opsApplied++;
|
|
1264
|
+
if (op.queued) summary.queuedReviews++;
|
|
1265
|
+
}
|
|
1266
|
+
} else if (r.reason === 'gate' || r.skipped) {
|
|
1267
|
+
summary.skippedGate++;
|
|
1268
|
+
} else {
|
|
1269
|
+
summary.failed.push({ sid: s.sid, axis: s.axis, label: s.label, reason: r.reason, error: r.error || null });
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
return { ok: summary.failed.length === 0, ...summary };
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
function registerTools(tools) {
|
|
1276
|
+
if (!tools) return;
|
|
1277
|
+
|
|
1278
|
+
tools.register({
|
|
1279
|
+
name: 'memory_search',
|
|
1280
|
+
description: 'Search 3-axis subject memory using BM25 + bigram + temporal decay (or hybrid semantic RRF). Strictly isolated per group/room; Owner DM can query all scopes.',
|
|
1281
|
+
risk: 'read_only',
|
|
1282
|
+
parameters: {
|
|
1283
|
+
type: 'object',
|
|
1284
|
+
properties: {
|
|
1285
|
+
query: { type: 'string' },
|
|
1286
|
+
axis: { type: 'string', enum: ['all', 'user', 'group', 'member'] },
|
|
1287
|
+
chatId: { type: 'string', description: 'Optional group/room id (Owner DM only)' },
|
|
1288
|
+
userId: { type: 'string', description: 'Optional user id filter' },
|
|
1289
|
+
limit: { type: 'number' },
|
|
1290
|
+
},
|
|
1291
|
+
required: ['query'],
|
|
1292
|
+
},
|
|
1293
|
+
async execute(args, ctx) {
|
|
1294
|
+
return searchScoped({
|
|
1295
|
+
query: args.query,
|
|
1296
|
+
axis: args.axis || 'all',
|
|
1297
|
+
chatId: args.chatId || null,
|
|
1298
|
+
userId: args.userId || null,
|
|
1299
|
+
limit: args.limit || 8,
|
|
1300
|
+
ctx,
|
|
1301
|
+
});
|
|
1302
|
+
},
|
|
1303
|
+
});
|
|
1304
|
+
|
|
1305
|
+
tools.register({
|
|
1306
|
+
name: 'memory_remember',
|
|
1307
|
+
description: 'Save a verified fact into 3-axis subject memory (scope: user [DM only], group [shared room fact/decision], or member [specific user inside current room]). MUST include a verbatim quote (>= 2 words) from the speaker turn.',
|
|
1308
|
+
risk: 'reversible_write',
|
|
1309
|
+
parameters: {
|
|
1310
|
+
type: 'object',
|
|
1311
|
+
properties: {
|
|
1312
|
+
scope: { type: 'string', enum: ['auto', 'user', 'group', 'member'] },
|
|
1313
|
+
key: { type: 'string', description: 'Taxonomy key e.g. pref.style, role.job, project.name.status, decision.meeting, commitment.task, group.goal' },
|
|
1314
|
+
value: { type: 'string' },
|
|
1315
|
+
quote: { type: 'string', description: 'REQUIRED verbatim quote (>= 2 words) from the speaker turn supporting this fact' },
|
|
1316
|
+
targetChatId: { type: 'string', description: 'Owner DM only: target group/room id' },
|
|
1317
|
+
targetUserId: { type: 'string', description: 'Owner DM only: target user id' },
|
|
1318
|
+
explicitOwnerEdit: { type: 'boolean', description: 'Owner DM only: set true ONLY when Owner explicitly instructs a manual memory edit' },
|
|
1319
|
+
},
|
|
1320
|
+
required: ['key', 'value', 'quote'],
|
|
1321
|
+
},
|
|
1322
|
+
async execute(args, ctx) {
|
|
1323
|
+
return rememberScoped({
|
|
1324
|
+
scope: args.scope || 'auto',
|
|
1325
|
+
key: args.key,
|
|
1326
|
+
value: args.value,
|
|
1327
|
+
quote: args.quote || null,
|
|
1328
|
+
targetChatId: args.targetChatId || null,
|
|
1329
|
+
targetUserId: args.targetUserId || null,
|
|
1330
|
+
explicitOwnerEdit: Boolean(args.explicitOwnerEdit),
|
|
1331
|
+
ctx,
|
|
1332
|
+
});
|
|
1333
|
+
},
|
|
1334
|
+
});
|
|
1335
|
+
|
|
1336
|
+
tools.register({
|
|
1337
|
+
name: 'memory_inspect',
|
|
1338
|
+
description: 'Inspect tracked 3-axis memory profiles & facts (Owner DM: inspect all scopes; Group: inspect only non-sensitive facts of current room and its members; User DM: inspect own DM profile only).',
|
|
1339
|
+
risk: 'read_only',
|
|
1340
|
+
parameters: {
|
|
1341
|
+
type: 'object',
|
|
1342
|
+
properties: {
|
|
1343
|
+
chatId: { type: 'string' },
|
|
1344
|
+
userId: { type: 'string' },
|
|
1345
|
+
},
|
|
1346
|
+
},
|
|
1347
|
+
async execute(args, ctx) {
|
|
1348
|
+
const mc = ctx.memoryContext || {};
|
|
1349
|
+
const isGroup = mc.axis === 'group' || Boolean(ctx.turnClassification?.isGroup);
|
|
1350
|
+
const callerUid = normId(ctx.sender?.id || ctx.sender?.channelId || mc.userId || '');
|
|
1351
|
+
const isOwnerDm = !isGroup && Boolean(callerUid && ownerSet.has(callerUid));
|
|
1352
|
+
if (isGroup) {
|
|
1353
|
+
return inspectSummary({ chatId: mc.chatId, userId: args.userId || null, mode: 'group' });
|
|
1354
|
+
}
|
|
1355
|
+
if (!isOwnerDm) {
|
|
1356
|
+
return inspectSummary({ userId: callerUid, mode: 'user_dm' });
|
|
1357
|
+
}
|
|
1358
|
+
return inspectSummary({ chatId: args.chatId || null, userId: args.userId || null, mode: 'owner_dm' });
|
|
1359
|
+
},
|
|
1360
|
+
});
|
|
1361
|
+
|
|
1362
|
+
tools.register({
|
|
1363
|
+
name: 'memory_forget',
|
|
1364
|
+
description: 'Permanently forget & tombstone a fact by ID across all copies (DM only; Owner DM can forget across user/group/member scopes; non-owner DM can forget own DM facts only).',
|
|
1365
|
+
risk: 'destructive',
|
|
1366
|
+
parameters: {
|
|
1367
|
+
type: 'object',
|
|
1368
|
+
properties: {
|
|
1369
|
+
scope: { type: 'string', enum: ['user', 'group', 'member'] },
|
|
1370
|
+
factId: { type: 'string' },
|
|
1371
|
+
chatId: { type: 'string' },
|
|
1372
|
+
userId: { type: 'string' },
|
|
1373
|
+
},
|
|
1374
|
+
required: ['factId'],
|
|
1375
|
+
},
|
|
1376
|
+
async execute(args, ctx) {
|
|
1377
|
+
return forgetScoped({
|
|
1378
|
+
scope: args.scope || 'user',
|
|
1379
|
+
factId: args.factId,
|
|
1380
|
+
chatId: args.chatId || null,
|
|
1381
|
+
userId: args.userId || null,
|
|
1382
|
+
ctx,
|
|
1383
|
+
});
|
|
1384
|
+
},
|
|
1385
|
+
});
|
|
1386
|
+
|
|
1387
|
+
tools.register({
|
|
1388
|
+
name: 'memory_lesson',
|
|
1389
|
+
description: 'Record a never-decay procedural lesson (L5, §7) when the Owner corrects agent behavior. In Owner DM writes to lessons.md immediately; otherwise queues for Owner approval.',
|
|
1390
|
+
risk: 'reversible_write',
|
|
1391
|
+
parameters: {
|
|
1392
|
+
type: 'object',
|
|
1393
|
+
properties: {
|
|
1394
|
+
lesson: { type: 'string', description: 'Concise actionable rule to follow permanently' },
|
|
1395
|
+
trigger: { type: 'string', description: 'What correction or mistake triggered this lesson' },
|
|
1396
|
+
scope: { type: 'string', description: 'agent | group:<id> | global' },
|
|
1397
|
+
},
|
|
1398
|
+
required: ['lesson'],
|
|
1399
|
+
},
|
|
1400
|
+
async execute(args, ctx) {
|
|
1401
|
+
const mc = ctx.memoryContext || {};
|
|
1402
|
+
const isGroup = mc.axis === 'group' || Boolean(ctx.turnClassification?.isGroup);
|
|
1403
|
+
const callerUid = normId(ctx.sender?.id || ctx.sender?.channelId || mc.userId || '');
|
|
1404
|
+
const isOwnerDm = !isGroup && Boolean(callerUid && ownerSet.has(callerUid));
|
|
1405
|
+
return recordLesson({
|
|
1406
|
+
lesson: args.lesson,
|
|
1407
|
+
trigger: args.trigger || '',
|
|
1408
|
+
scope: args.scope || 'agent',
|
|
1409
|
+
source: isOwnerDm ? 'owner-correction' : 'agent-proposal',
|
|
1410
|
+
approved: isOwnerDm,
|
|
1411
|
+
ctx,
|
|
1412
|
+
});
|
|
1413
|
+
},
|
|
1414
|
+
});
|
|
1415
|
+
|
|
1416
|
+
tools.register({
|
|
1417
|
+
name: 'memory_open_loops',
|
|
1418
|
+
description: 'Update unresolved open loops (pending tasks / follow-ups in issues.md) for current DM or group/room.',
|
|
1419
|
+
risk: 'reversible_write',
|
|
1420
|
+
parameters: {
|
|
1421
|
+
type: 'object',
|
|
1422
|
+
properties: {
|
|
1423
|
+
scope: { type: 'string', enum: ['auto', 'user', 'group', 'member'] },
|
|
1424
|
+
items: { type: 'array', items: { type: 'string' } },
|
|
1425
|
+
chatId: { type: 'string' },
|
|
1426
|
+
userId: { type: 'string' },
|
|
1427
|
+
},
|
|
1428
|
+
required: ['items'],
|
|
1429
|
+
},
|
|
1430
|
+
async execute(args, ctx) {
|
|
1431
|
+
return updateOpenLoops({
|
|
1432
|
+
scope: args.scope || 'auto',
|
|
1433
|
+
chatId: args.chatId || null,
|
|
1434
|
+
userId: args.userId || null,
|
|
1435
|
+
items: args.items || [],
|
|
1436
|
+
ctx,
|
|
1437
|
+
});
|
|
1438
|
+
},
|
|
1439
|
+
});
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
return {
|
|
1443
|
+
store,
|
|
1444
|
+
registry,
|
|
1445
|
+
observeMessage,
|
|
1446
|
+
recordAndLoad,
|
|
1447
|
+
recordAssistantTurn,
|
|
1448
|
+
onSessionReset,
|
|
1449
|
+
onBeforeCompact,
|
|
1450
|
+
flushIdleSessions,
|
|
1451
|
+
rememberScoped,
|
|
1452
|
+
forgetScoped,
|
|
1453
|
+
recordLesson,
|
|
1454
|
+
updateOpenLoops,
|
|
1455
|
+
searchScoped,
|
|
1456
|
+
inspectSummary,
|
|
1457
|
+
listPendingReviews,
|
|
1458
|
+
resolveReviewItem,
|
|
1459
|
+
listFailedDreams,
|
|
1460
|
+
getStats,
|
|
1461
|
+
consolidateAll,
|
|
1462
|
+
runLlmSweep,
|
|
1463
|
+
runDreamSubject,
|
|
1464
|
+
runDreamAll,
|
|
1465
|
+
registerTools,
|
|
1466
|
+
flushRegistry,
|
|
1467
|
+
invalidateFrozen,
|
|
1468
|
+
ensureUser,
|
|
1469
|
+
ensureGroup,
|
|
1470
|
+
ensureMemberInGroup,
|
|
1471
|
+
};
|
|
1472
|
+
}
|