@rubytech/create-maxy 1.0.889 → 1.0.890

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/package.json +1 -1
  2. package/payload/platform/plugins/admin/PLUGIN.md +5 -1
  3. package/payload/platform/plugins/docs/references/troubleshooting.md +4 -2
  4. package/payload/platform/scripts/log-adherence-check.sh +28 -3
  5. package/payload/server/chunk-FBTNBSB4.js +2282 -0
  6. package/payload/server/chunk-O7DTMDJM.js +759 -0
  7. package/payload/server/chunk-OD4LSAB2.js +9770 -0
  8. package/payload/server/chunk-TUCK5CI2.js +3566 -0
  9. package/payload/server/client-pool-E3OU5NYU.js +34 -0
  10. package/payload/server/cloudflare-task-tracker-KCIUQYB5.js +22 -0
  11. package/payload/server/maxy-edge.js +4 -4
  12. package/payload/server/public/assets/{Checkbox-CeujDRv0.js → Checkbox-ebZSKvw2.js} +1 -1
  13. package/payload/server/public/assets/{admin-BN_z-2Bm.js → admin-Ewxzru2U.js} +31 -31
  14. package/payload/server/public/assets/data-pOc8b2rA.js +1 -0
  15. package/payload/server/public/assets/graph-DeG4HsDI.js +1 -0
  16. package/payload/server/public/assets/{graph-labels-Co03qEv5.js → graph-labels-DHQuVOgO.js} +1 -1
  17. package/payload/server/public/assets/jsx-runtime-CqFGUuze.css +1 -0
  18. package/payload/server/public/assets/{page-DGLz4ozf.js → page-DJiTa_Y_.js} +1 -1
  19. package/payload/server/public/assets/{page-C4E0CWHe.js → page-DL8yJkUn.js} +1 -1
  20. package/payload/server/public/assets/{public-rILg7e8-.js → public-BS-tmbAu.js} +1 -1
  21. package/payload/server/public/assets/{useVoiceRecorder-D3Upd7Q3.js → useVoiceRecorder-COlUADaA.js} +1 -1
  22. package/payload/server/public/data.html +5 -5
  23. package/payload/server/public/graph.html +6 -6
  24. package/payload/server/public/index.html +8 -8
  25. package/payload/server/public/public.html +5 -5
  26. package/payload/server/server.js +450 -314
  27. package/payload/server/public/assets/data-LYciLZK9.js +0 -1
  28. package/payload/server/public/assets/graph-C-SKAbGX.js +0 -1
  29. package/payload/server/public/assets/jsx-runtime-BcZkJOEw.css +0 -1
  30. /package/payload/server/public/assets/{jsx-runtime-BWYXu1CT.js → jsx-runtime-BCHoQyWP.js} +0 -0
@@ -0,0 +1,2282 @@
1
+ // app/lib/neo4j-store.ts
2
+ import neo4j from "neo4j-driver";
3
+ import { randomUUID } from "crypto";
4
+ import { spawn } from "child_process";
5
+ import { readFileSync, readdirSync, existsSync, openSync, readSync, closeSync, statSync, rmSync } from "fs";
6
+ import { resolve } from "path";
7
+
8
+ // ../lib/models/src/index.ts
9
+ var OPUS_MODEL = "claude-opus-4-7";
10
+ var SONNET_MODEL = "claude-sonnet-4-6";
11
+ var HAIKU_MODEL = "claude-haiku-4-5";
12
+ var MODEL_CONTEXT_WINDOW = {
13
+ [OPUS_MODEL]: 2e5,
14
+ [SONNET_MODEL]: 2e5,
15
+ [HAIKU_MODEL]: 2e5
16
+ };
17
+ function contextWindow(model) {
18
+ return MODEL_CONTEXT_WINDOW[model] ?? 2e5;
19
+ }
20
+
21
+ // app/lib/neo4j-store.ts
22
+ var PLATFORM_ROOT = process.env.MAXY_PLATFORM_ROOT ?? resolve(process.cwd(), "..");
23
+ var driver = null;
24
+ function readPassword() {
25
+ if (process.env.NEO4J_PASSWORD) return process.env.NEO4J_PASSWORD;
26
+ const passwordFile = resolve(PLATFORM_ROOT, "config/.neo4j-password");
27
+ try {
28
+ return readFileSync(passwordFile, "utf-8").trim();
29
+ } catch {
30
+ throw new Error(
31
+ `Neo4j password not found. Expected at ${passwordFile} or in NEO4J_PASSWORD env var.`
32
+ );
33
+ }
34
+ }
35
+ function getDriver() {
36
+ if (!driver) {
37
+ const uri = process.env.NEO4J_URI;
38
+ if (!uri) {
39
+ throw new Error(
40
+ "[ui/neo4j-store] NEO4J_URI unset \u2014 refusing to default to bolt://localhost:7687"
41
+ );
42
+ }
43
+ const user = process.env.NEO4J_USER ?? "neo4j";
44
+ const password = readPassword();
45
+ console.error(`[ui/neo4j-store] resolved neo4j_uri=${uri}`);
46
+ driver = neo4j.driver(uri, neo4j.auth.basic(user, password), {
47
+ maxConnectionPoolSize: 5
48
+ });
49
+ }
50
+ return driver;
51
+ }
52
+ function getSession() {
53
+ return getDriver().session();
54
+ }
55
+ async function runAdminUserSelfHeal(args) {
56
+ const { selfHealAdminUser } = await import("./adminuser-self-heal-QAWOZ3JV.js");
57
+ return selfHealAdminUser({ driver: getDriver(), ...args });
58
+ }
59
+ process.on("SIGINT", async () => {
60
+ if (driver) {
61
+ await driver.close();
62
+ driver = null;
63
+ }
64
+ });
65
+ var OLLAMA_URL = process.env.OLLAMA_URL ?? "http://localhost:11434";
66
+ var EMBED_MODEL = process.env.EMBED_MODEL ?? "nomic-embed-text";
67
+ async function embed(text) {
68
+ const res = await fetch(`${OLLAMA_URL}/api/embed`, {
69
+ method: "POST",
70
+ headers: { "Content-Type": "application/json" },
71
+ body: JSON.stringify({ model: EMBED_MODEL, input: text }),
72
+ signal: AbortSignal.timeout(5e3)
73
+ });
74
+ if (!res.ok) {
75
+ const body = await res.text();
76
+ throw new Error(`Ollama embedding failed (${res.status}): ${body}`);
77
+ }
78
+ const data = await res.json();
79
+ return data.embeddings[0];
80
+ }
81
+ var sessionStoreRef = null;
82
+ function setSessionStoreRef(ref) {
83
+ sessionStoreRef = ref;
84
+ }
85
+ function getCachedConversationId(cacheKey) {
86
+ return sessionStoreRef?.get(cacheKey)?.conversationId;
87
+ }
88
+ function cacheConversationId(cacheKey, conversationId) {
89
+ const session = sessionStoreRef?.get(cacheKey);
90
+ if (session) {
91
+ session.conversationId = conversationId;
92
+ }
93
+ }
94
+ var GREETING_DIRECTIVE = "[New session. Greet the visitor.]";
95
+ var DIRECTIVE_PREFIX = "[New session.";
96
+ async function ensureConversation(accountId, agentType, cacheKey, visitorId, agentSlug, userId, channelOverride, channelAddressOverride) {
97
+ const cached = getCachedConversationId(cacheKey);
98
+ if (cached) return { conversationId: cached, created: false };
99
+ const conversationId = randomUUID();
100
+ const channel = channelOverride ?? (cacheKey.startsWith("whatsapp:") ? "whatsapp" : cacheKey.startsWith("telegram:") ? "telegram" : "webchat");
101
+ const channelAddress = channelAddressOverride ?? (cacheKey.startsWith("whatsapp:") ? cacheKey.slice("whatsapp:".length) : cacheKey.startsWith("telegram:") ? cacheKey.slice("telegram:".length) : conversationId);
102
+ const conversationSublabel = agentType === "admin" ? "AdminConversation" : "PublicConversation";
103
+ const handlerSlug = agentSlug ?? (agentType === "admin" ? "admin" : null);
104
+ const wantsHandledByEdge = !!handlerSlug;
105
+ const handledByClause = wantsHandledByEdge ? `WITH c, created
106
+ OPTIONAL MATCH (a:Agent {accountId: $accountId, slug: $handlerSlug})
107
+ FOREACH (_ IN CASE WHEN a IS NULL THEN [] ELSE [1] END | MERGE (c)-[:HANDLED_BY]->(a))
108
+ RETURN c.conversationId AS conversationId, created AS created, a IS NOT NULL AS handledBy` : `RETURN c.conversationId AS conversationId, created AS created, false AS handledBy`;
109
+ const session = getSession();
110
+ try {
111
+ const result = await session.run(
112
+ `OPTIONAL MATCH (prior:Conversation {accountId: $accountId, channel: $channel, channelAddress: $channelAddress})
113
+ WITH prior, coalesce(prior.conversationId, $conversationId) AS finalConvId, prior IS NULL AS created
114
+ MERGE (c:Conversation {conversationId: finalConvId})
115
+ ON CREATE SET
116
+ c:${conversationSublabel},
117
+ c.accountId = $accountId,
118
+ c.agentType = $agentType,
119
+ c.channel = $channel,
120
+ c.channelAddress = $channelAddress,
121
+ ${visitorId ? "c.visitorId = $visitorId," : ""}
122
+ ${agentSlug ? "c.agentSlug = $agentSlug," : ""}
123
+ ${userId ? "c.userId = $userId," : ""}
124
+ c.createdAt = datetime(),
125
+ c.updatedAt = datetime()
126
+ ON MATCH SET
127
+ c.updatedAt = datetime()
128
+ ${handledByClause}`,
129
+ {
130
+ conversationId,
131
+ accountId,
132
+ agentType,
133
+ channel,
134
+ channelAddress,
135
+ ...visitorId ? { visitorId } : {},
136
+ ...agentSlug ? { agentSlug } : {},
137
+ ...handlerSlug ? { handlerSlug } : {},
138
+ ...userId ? { userId } : {}
139
+ }
140
+ );
141
+ const id = result.records[0]?.get("conversationId");
142
+ const created = result.records[0]?.get("created") === true;
143
+ if (id) {
144
+ cacheConversationId(cacheKey, id);
145
+ console.error(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} conversation attributed: conversationId=${id.slice(0, 8)}\u2026 userId=${userId ?? "none"} ${agentType}/${accountId.slice(0, 8)}\u2026 sublabel=${conversationSublabel}`);
146
+ if (wantsHandledByEdge) {
147
+ const handled = result.records[0]?.get("handledBy");
148
+ const id8 = id.slice(0, 8);
149
+ if (handled === true) {
150
+ console.error(`[agent-graph] handled-by-write conversationId=${id8} slug=${handlerSlug}`);
151
+ } else {
152
+ console.error(`[agent-graph] handled-by-skip reason=no-agent-node conversationId=${id8} slug=${handlerSlug}`);
153
+ }
154
+ }
155
+ }
156
+ return { conversationId: id ?? null, created };
157
+ } catch (err) {
158
+ console.error(`[persist] ensureConversation failed: ${err instanceof Error ? err.message : String(err)}`);
159
+ return { conversationId: null, created: false };
160
+ } finally {
161
+ await session.close();
162
+ }
163
+ }
164
+ async function findRecentConversation(visitorId, accountId, agentSlug, maxAgeHours = 24) {
165
+ const session = getSession();
166
+ try {
167
+ const result = await session.run(
168
+ `MATCH (c:Conversation {visitorId: $visitorId, accountId: $accountId, agentType: 'public'})
169
+ WHERE c.agentSlug = $agentSlug
170
+ AND c.updatedAt > datetime() - duration({hours: $maxAgeHours})
171
+ AND NOT c:Trashed
172
+ RETURN c.conversationId AS conversationId
173
+ ORDER BY c.updatedAt DESC
174
+ LIMIT 1`,
175
+ { visitorId, accountId, agentSlug, maxAgeHours: neo4j.int(maxAgeHours) },
176
+ { timeout: 2e3 }
177
+ );
178
+ const record = result.records[0];
179
+ if (!record) return null;
180
+ const conversationId = record.get("conversationId");
181
+ if (!conversationId) return null;
182
+ console.log(`[persist] found recent conversation ${conversationId.slice(0, 8)}\u2026 for visitor ${visitorId.slice(0, 8)}\u2026`);
183
+ return { conversationId };
184
+ } catch (err) {
185
+ console.error(`[persist] findRecentConversation failed: ${err instanceof Error ? err.message : String(err)}`);
186
+ return null;
187
+ } finally {
188
+ await session.close();
189
+ }
190
+ }
191
+ async function readIntentGateState(conversationId) {
192
+ const session = getSession();
193
+ try {
194
+ const result = await session.run(
195
+ `MATCH (c:Conversation {conversationId: $conversationId})
196
+ OPTIONAL MATCH (c)-[:HAS_FAILURE]->(f:TurnFailure)
197
+ WITH c, f ORDER BY f.at DESC
198
+ WITH c, head(collect(f)) AS recentFailure
199
+ RETURN size([(m:Message)-[:PART_OF]->(c) | m]) AS chainLen,
200
+ coalesce(recentFailure.mode, 'none') AS recentFailureMode`,
201
+ { conversationId },
202
+ { timeout: 2e3 }
203
+ );
204
+ if (result.records.length === 0) {
205
+ return { chainLen: 0, recentFailureMode: "none" };
206
+ }
207
+ const record = result.records[0];
208
+ const chainLenRaw = record.get("chainLen");
209
+ const chainLen = typeof chainLenRaw === "bigint" ? Number(chainLenRaw) : typeof chainLenRaw?.toNumber === "function" ? chainLenRaw.toNumber() : Number(chainLenRaw ?? 0);
210
+ const recentFailureMode = String(record.get("recentFailureMode") ?? "none");
211
+ return { chainLen, recentFailureMode };
212
+ } catch (err) {
213
+ console.error(`[persist] readIntentGateState failed: ${err instanceof Error ? err.message : String(err)}`);
214
+ return { chainLen: 0, recentFailureMode: "none" };
215
+ } finally {
216
+ await session.close();
217
+ }
218
+ }
219
+ async function findGroupBySlug(groupSlug, accountId) {
220
+ const session = getSession();
221
+ try {
222
+ const result = await session.run(
223
+ `MATCH (c:Conversation {groupSlug: $groupSlug, accountId: $accountId, type: 'group'})
224
+ WHERE NOT c:Trashed
225
+ RETURN c.conversationId AS conversationId, c.groupName AS groupName, c.agentSlug AS agentSlug`,
226
+ { groupSlug, accountId },
227
+ { timeout: 2e3 }
228
+ );
229
+ const record = result.records[0];
230
+ if (!record) return null;
231
+ return {
232
+ conversationId: record.get("conversationId"),
233
+ groupName: record.get("groupName"),
234
+ agentSlug: record.get("agentSlug")
235
+ };
236
+ } catch (err) {
237
+ console.error(`[group] findGroupBySlug failed: ${err instanceof Error ? err.message : String(err)}`);
238
+ return null;
239
+ } finally {
240
+ await session.close();
241
+ }
242
+ }
243
+ async function getGroupParticipants(conversationId) {
244
+ const session = getSession();
245
+ try {
246
+ const result = await session.run(
247
+ `MATCH (p:Person)-[r:PARTICIPATES_IN]->(c:Conversation {conversationId: $conversationId})
248
+ RETURN p.givenName AS givenName, p.familyName AS familyName,
249
+ r.displayName AS displayName, r.joinedAt AS joinedAt, r.visitorId AS visitorId`,
250
+ { conversationId }
251
+ );
252
+ return result.records.map((r) => ({
253
+ displayName: r.get("displayName") || r.get("givenName"),
254
+ givenName: r.get("givenName"),
255
+ familyName: r.get("familyName"),
256
+ joinedAt: String(r.get("joinedAt")),
257
+ visitorId: r.get("visitorId")
258
+ }));
259
+ } catch (err) {
260
+ console.error(`[group] getGroupParticipants failed: ${err instanceof Error ? err.message : String(err)}`);
261
+ return [];
262
+ } finally {
263
+ await session.close();
264
+ }
265
+ }
266
+ async function checkGroupMembership(conversationId, visitorId) {
267
+ const session = getSession();
268
+ try {
269
+ const result = await session.run(
270
+ `MATCH (p:Person)-[r:PARTICIPATES_IN]->(c:Conversation {conversationId: $conversationId})
271
+ WHERE r.visitorId = $visitorId
272
+ RETURN r.displayName AS displayName
273
+ LIMIT 1`,
274
+ { conversationId, visitorId }
275
+ );
276
+ return result.records[0]?.get("displayName") ?? null;
277
+ } catch (err) {
278
+ console.error(`[group] checkGroupMembership failed: ${err instanceof Error ? err.message : String(err)}`);
279
+ return null;
280
+ } finally {
281
+ await session.close();
282
+ }
283
+ }
284
+ async function bindVisitorToGroup(conversationId, visitorId, personEmail, personPhone) {
285
+ const session = getSession();
286
+ try {
287
+ const result = await session.run(
288
+ `MATCH (p:Person)-[r:PARTICIPATES_IN]->(c:Conversation {conversationId: $conversationId})
289
+ WHERE ($email IS NOT NULL AND p.email = $email)
290
+ OR ($phone IS NOT NULL AND p.telephone = $phone)
291
+ SET r.visitorId = $visitorId
292
+ RETURN r.displayName AS displayName
293
+ LIMIT 1`,
294
+ {
295
+ conversationId,
296
+ visitorId,
297
+ email: personEmail ?? null,
298
+ phone: personPhone ?? null
299
+ }
300
+ );
301
+ const name = result.records[0]?.get("displayName");
302
+ if (name) {
303
+ console.error(`[group] joined id=${conversationId.slice(0, 8)}\u2026 visitor=${visitorId.slice(0, 8)}\u2026`);
304
+ } else {
305
+ console.error(`[group] auth-denied id=${conversationId.slice(0, 8)}\u2026 visitor=${visitorId.slice(0, 8)}\u2026`);
306
+ }
307
+ return name ? { displayName: name } : null;
308
+ } catch (err) {
309
+ console.error(`[group] bindVisitorToGroup failed: ${err instanceof Error ? err.message : String(err)}`);
310
+ return null;
311
+ } finally {
312
+ await session.close();
313
+ }
314
+ }
315
+ async function getMessagesSince(conversationId, since, limit = 100) {
316
+ const session = getSession();
317
+ try {
318
+ const result = await session.run(
319
+ `MATCH (m:Message)-[:PART_OF]->(c:Conversation {conversationId: $conversationId})
320
+ WHERE m.createdAt > datetime($since)
321
+ RETURN m.messageId AS messageId, m.role AS role, m.content AS content,
322
+ m.senderName AS senderName, m.senderVisitorId AS senderVisitorId,
323
+ m.createdAt AS createdAt
324
+ ORDER BY m.createdAt ASC
325
+ LIMIT $limit`,
326
+ { conversationId, since, limit: neo4j.int(limit) },
327
+ { timeout: 3e3 }
328
+ );
329
+ return result.records.map((r) => ({
330
+ messageId: r.get("messageId"),
331
+ role: r.get("role"),
332
+ content: r.get("content"),
333
+ senderName: r.get("senderName"),
334
+ senderVisitorId: r.get("senderVisitorId"),
335
+ createdAt: String(r.get("createdAt"))
336
+ }));
337
+ } catch (err) {
338
+ console.error(`[group] getMessagesSince failed: ${err instanceof Error ? err.message : String(err)}`);
339
+ return [];
340
+ } finally {
341
+ await session.close();
342
+ }
343
+ }
344
+ async function getGroupMessagesForContext(conversationId, limit = 50) {
345
+ const session = getSession();
346
+ try {
347
+ const result = await session.run(
348
+ `MATCH (m:Message)-[:PART_OF]->(c:Conversation {conversationId: $conversationId})
349
+ WITH m ORDER BY m.createdAt DESC LIMIT $limit
350
+ RETURN m.role AS role, m.content AS content, m.senderName AS senderName
351
+ ORDER BY m.createdAt ASC`,
352
+ { conversationId, limit: neo4j.int(limit) }
353
+ );
354
+ return result.records.map((r) => ({
355
+ role: r.get("role"),
356
+ content: r.get("content"),
357
+ senderName: r.get("senderName")
358
+ }));
359
+ } catch (err) {
360
+ console.error(`[group] getGroupMessagesForContext failed: ${err instanceof Error ? err.message : String(err)}`);
361
+ return [];
362
+ } finally {
363
+ await session.close();
364
+ }
365
+ }
366
+ async function backfillConversationChannelAddress() {
367
+ const session = getSession();
368
+ try {
369
+ const LEGACY_PROP = "cacheKey";
370
+ const result = await session.run(
371
+ `MATCH (c:Conversation)
372
+ WHERE c.channelAddress IS NULL
373
+ SET c.channel = coalesce(c.channel, CASE
374
+ WHEN c.${LEGACY_PROP} STARTS WITH 'whatsapp:' THEN 'whatsapp'
375
+ WHEN c.${LEGACY_PROP} STARTS WITH 'telegram:' THEN 'telegram'
376
+ ELSE 'webchat'
377
+ END),
378
+ c.channelAddress = CASE
379
+ WHEN c.${LEGACY_PROP} STARTS WITH 'whatsapp:' THEN substring(c.${LEGACY_PROP}, 9)
380
+ WHEN c.${LEGACY_PROP} STARTS WITH 'telegram:' THEN substring(c.${LEGACY_PROP}, 9)
381
+ ELSE coalesce(c.conversationId, c.${LEGACY_PROP})
382
+ END
383
+ RETURN count(c) AS updated`
384
+ );
385
+ const updatedRaw = result.records[0]?.get("updated")?.toNumber?.() ?? result.records[0]?.get("updated") ?? 0;
386
+ const updated = typeof updatedRaw === "number" ? updatedRaw : 0;
387
+ if (updated > 0) {
388
+ console.log(`[session-985] backfill channelAddress: updated ${updated} legacy Conversation rows`);
389
+ } else {
390
+ console.log(`[session-985] backfill channelAddress: no legacy rows needed migration`);
391
+ }
392
+ const dropRes = await session.run(
393
+ `MATCH (c:Conversation)
394
+ WHERE c.${LEGACY_PROP} IS NOT NULL AND c.channelAddress IS NOT NULL
395
+ REMOVE c.${LEGACY_PROP}
396
+ RETURN count(c) AS dropped`
397
+ );
398
+ const droppedRaw = dropRes.records[0]?.get("dropped")?.toNumber?.() ?? dropRes.records[0]?.get("dropped") ?? 0;
399
+ const legacyPropDropped = typeof droppedRaw === "number" ? droppedRaw : 0;
400
+ console.log(`[session-985] cacheKey-property-drop count=${legacyPropDropped}`);
401
+ return { updated, legacyPropDropped };
402
+ } catch (err) {
403
+ console.error(`[session-985] backfillConversationChannelAddress failed: ${err instanceof Error ? err.message : String(err)}`);
404
+ return { updated: 0, legacyPropDropped: 0 };
405
+ } finally {
406
+ await session.close();
407
+ }
408
+ }
409
+ async function backfillNullUserIdConversations(userId) {
410
+ if (!userId) {
411
+ console.warn(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} backfill: skipped \u2014 no userId provided (no Owner in users.json?)`);
412
+ return 0;
413
+ }
414
+ const session = getSession();
415
+ try {
416
+ const result = await session.run(
417
+ `MATCH (c:Conversation {agentType: 'admin'})
418
+ WHERE c.userId IS NULL
419
+ SET c.userId = $userId
420
+ RETURN count(c) AS updated`,
421
+ { userId }
422
+ );
423
+ const updated = result.records[0]?.get("updated")?.toNumber?.() ?? result.records[0]?.get("updated") ?? 0;
424
+ if (updated > 0) {
425
+ console.log(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} backfill: set userId on ${updated} admin conversations`);
426
+ } else {
427
+ console.log(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} backfill: no orphaned admin conversations found`);
428
+ }
429
+ return typeof updated === "number" ? updated : 0;
430
+ } catch (err) {
431
+ console.error(`[session] backfillNullUserIdConversations failed: ${err instanceof Error ? err.message : String(err)}`);
432
+ return 0;
433
+ } finally {
434
+ await session.close();
435
+ }
436
+ }
437
+ async function createNewAdminConversation(userId, accountId, cacheKey, adminName, preMintedConversationId) {
438
+ if (!userId || !cacheKey || !accountId) {
439
+ console.error(`[admin/conversation-write] schema-violation userId=${userId ? "set" : "EMPTY"} cacheKey=${cacheKey ? "set" : "EMPTY"} accountId=${accountId ? "set" : "EMPTY"}`);
440
+ return null;
441
+ }
442
+ const conversationId = preMintedConversationId ?? randomUUID();
443
+ const session = getSession();
444
+ try {
445
+ const result = await session.run(
446
+ `OPTIONAL MATCH (existing:AdminUser {userId: $userId})
447
+ WITH existing IS NULL AS adminUserCreated
448
+ MERGE (au:AdminUser {userId: $userId})
449
+ ON CREATE SET au.accountId = $accountId,
450
+ au.name = COALESCE($adminName, 'Admin'),
451
+ au.createdAt = datetime(),
452
+ au.scope = 'admin'
453
+ CREATE (c:Conversation:AdminConversation {
454
+ conversationId: $conversationId,
455
+ accountId: $accountId,
456
+ agentType: 'admin',
457
+ channel: 'webchat',
458
+ channelAddress: $conversationId,
459
+ userId: $userId,
460
+ createdBySource: 'admin-conversation',
461
+ createdAt: datetime(),
462
+ updatedAt: datetime()
463
+ })-[:STARTED_BY]->(au)
464
+ RETURN adminUserCreated`,
465
+ { conversationId, accountId, userId, adminName: adminName ?? null }
466
+ );
467
+ const adminUserCreated = result.records[0]?.get("adminUserCreated") === true;
468
+ cacheConversationId(cacheKey, conversationId);
469
+ console.log(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} conversation created: conversationId=${conversationId.slice(0, 8)}\u2026 cacheKey=${cacheKey.slice(0, 8)}\u2026 accountId=${accountId.slice(0, 8)}\u2026 userId=${userId} agentType=admin createdBySource=admin-conversation createdAt=set updatedAt=set sublabel=AdminConversation adminUserCreated=${adminUserCreated}`);
470
+ return conversationId;
471
+ } catch (err) {
472
+ console.error(`[session] createNewAdminConversation failed: ${err instanceof Error ? err.message : String(err)}`);
473
+ return null;
474
+ } finally {
475
+ await session.close();
476
+ }
477
+ }
478
+ var HEX_COLOR_RE = /^#[0-9a-fA-F]{3,8}$/;
479
+ async function fetchBranding(accountId) {
480
+ const session = getSession();
481
+ try {
482
+ const result = await session.run(
483
+ `MATCH (b:LocalBusiness {accountId: $accountId})
484
+ OPTIONAL MATCH (b)-[:HAS_BRAND_ASSET]->(logo:ImageObject {purpose: "logo"})
485
+ OPTIONAL MATCH (b)-[:HAS_BRAND_ASSET]->(icon:ImageObject {purpose: "icon"})
486
+ RETURN b.name AS name,
487
+ b.primaryColor AS primaryColor,
488
+ b.accentColor AS accentColor,
489
+ b.backgroundColor AS backgroundColor,
490
+ b.tagline AS tagline,
491
+ logo.contentUrl AS logoUrl,
492
+ icon.contentUrl AS faviconUrl`,
493
+ { accountId },
494
+ { timeout: 2e3 }
495
+ );
496
+ const record = result.records[0];
497
+ if (!record) return null;
498
+ const name = record.get("name");
499
+ if (!name) return null;
500
+ const primaryColor = record.get("primaryColor");
501
+ const accentColor = record.get("accentColor");
502
+ const backgroundColor = record.get("backgroundColor");
503
+ const tagline = record.get("tagline");
504
+ const logoUrl = record.get("logoUrl");
505
+ const faviconUrl = record.get("faviconUrl");
506
+ const hasBranding = primaryColor || accentColor || backgroundColor || tagline || logoUrl || faviconUrl;
507
+ if (!hasBranding) return null;
508
+ const branding = { name };
509
+ if (primaryColor && HEX_COLOR_RE.test(primaryColor)) branding.primaryColor = primaryColor;
510
+ if (accentColor && HEX_COLOR_RE.test(accentColor)) branding.accentColor = accentColor;
511
+ if (backgroundColor && HEX_COLOR_RE.test(backgroundColor)) branding.backgroundColor = backgroundColor;
512
+ if (tagline) branding.tagline = tagline;
513
+ if (logoUrl) branding.logoUrl = logoUrl;
514
+ if (faviconUrl) branding.faviconUrl = faviconUrl;
515
+ console.error(`[branding] resolved for accountId=${accountId.slice(0, 8)}\u2026: primary=${branding.primaryColor ?? "\u2013"} logo=${branding.logoUrl ? "yes" : "no"}`);
516
+ return branding;
517
+ } catch (err) {
518
+ console.error(`[branding] fetchBranding failed for accountId=${accountId.slice(0, 8)}\u2026: ${err instanceof Error ? err.message : String(err)}`);
519
+ return null;
520
+ } finally {
521
+ await session.close();
522
+ }
523
+ }
524
+ async function persistToolCall(record) {
525
+ const session = getSession();
526
+ try {
527
+ const optionalFields = [
528
+ record.pluginName != null ? ", pluginName: $pluginName" : "",
529
+ record.error != null ? ", error: $error" : "",
530
+ record.subagentType != null ? ", subagentType: $subagentType" : "",
531
+ record.subagentDescription != null ? ", subagentDescription: $subagentDescription" : "",
532
+ record.approvalState != null ? ", approvalState: $approvalState" : "",
533
+ record.originalInput != null ? ", originalInput: $originalInput" : ""
534
+ ].join("");
535
+ const res = await session.run(
536
+ `MATCH (c:Conversation {conversationId: $conversationId})
537
+ CREATE (c)-[:HAS_TOOL_CALL]->(tc:ToolCall {
538
+ callId: $callId,
539
+ toolName: $toolName,
540
+ input: $input,
541
+ output: $output,
542
+ isError: $isError,
543
+ agentType: $agentType,
544
+ accountId: $accountId,
545
+ conversationId: $conversationId,
546
+ createdBySource: 'persist-tool-call',
547
+ createdBySession: $conversationId,
548
+ startedAt: datetime($startedAt),
549
+ completedAt: datetime($completedAt)
550
+ ${optionalFields}
551
+ })`,
552
+ {
553
+ callId: record.callId,
554
+ toolName: record.toolName,
555
+ input: record.input,
556
+ output: record.output,
557
+ isError: record.isError,
558
+ agentType: record.agentType,
559
+ accountId: record.accountId,
560
+ conversationId: record.conversationId,
561
+ startedAt: record.startedAt,
562
+ completedAt: record.completedAt,
563
+ ...record.pluginName != null ? { pluginName: record.pluginName } : {},
564
+ ...record.error != null ? { error: record.error } : {},
565
+ ...record.subagentType != null ? { subagentType: record.subagentType } : {},
566
+ ...record.subagentDescription != null ? { subagentDescription: record.subagentDescription } : {},
567
+ ...record.approvalState != null ? { approvalState: record.approvalState } : {},
568
+ ...record.originalInput != null ? { originalInput: record.originalInput } : {}
569
+ }
570
+ );
571
+ if (res.summary.counters.updates().nodesCreated === 0) {
572
+ console.error(
573
+ `[persist] tool-call skipped: conversation ${record.conversationId.slice(0, 8)}\u2026 not found for tool=${record.toolName}`
574
+ );
575
+ return;
576
+ }
577
+ console.error(`[persist] tool-call persisted: name=${record.toolName} conversation=${record.conversationId.slice(0, 8)}\u2026${record.approvalState ? ` approval=${record.approvalState}` : ""}`);
578
+ } catch (err) {
579
+ console.error(`[persist] tool-call write failed: name=${record.toolName} error=${err instanceof Error ? err.message : String(err)}`);
580
+ } finally {
581
+ await session.close();
582
+ }
583
+ }
584
+ var SUMMARY_MAX_LEN = 200;
585
+ var persistMessageLocks = /* @__PURE__ */ new Map();
586
+ async function persistMessage(conversationId, role, content, accountId, tokens, createdAt, sender, components, attachments) {
587
+ if (!content) return null;
588
+ const messageId = randomUUID();
589
+ const summary = role === "user" ? content.slice(0, SUMMARY_MAX_LEN).trim() : "";
590
+ let embedding = null;
591
+ try {
592
+ embedding = await embed(content);
593
+ } catch (err) {
594
+ console.error(`[persist] Embedding failed, storing without: ${err instanceof Error ? err.message : String(err)}`);
595
+ }
596
+ const prev = persistMessageLocks.get(conversationId);
597
+ const waited = prev !== void 0;
598
+ let release;
599
+ const mine = new Promise((resolve2) => {
600
+ release = resolve2;
601
+ });
602
+ const chained = (prev ?? Promise.resolve()).then(() => mine);
603
+ persistMessageLocks.set(conversationId, chained);
604
+ await prev;
605
+ const session = getSession();
606
+ try {
607
+ const result = await session.run(
608
+ `MATCH (c:Conversation {conversationId: $conversationId})
609
+ OPTIONAL MATCH (tail:Message)-[:PART_OF]->(c)
610
+ WHERE NOT (tail)-[:NEXT]->(:Message)
611
+ AND (tail:UserMessage OR tail:AssistantMessage)
612
+ // Task 857 \u2014 sublabel-scope the tail to the agent-path's own sublabels.
613
+ // Without this, a Task-857 :WhatsAppMessage row (no outgoing :NEXT)
614
+ // would be picked as tail and the agent-path would chain
615
+ // :WhatsAppMessage\u2192:UserMessage, crossing the live-channel chain.
616
+ // The live writer's tail predicate is sublabel-scoped to
617
+ // :WhatsAppMessage; this clause is the matching defence on the
618
+ // agent side. Backward-compatible \u2014 pre-Task-857 graphs only carry
619
+ // UserMessage/AssistantMessage sublabels under :Message.
620
+ // Capture whether THIS write's guard will fire. Read c.summary
621
+ // before the SET so the boolean reflects the pre-state, not the
622
+ // post-state \u2014 a false positive otherwise when a new user message
623
+ // happens to equal an already-set summary (verbatim retry, short
624
+ // catchphrase) and fooled a post-state equality check.
625
+ WITH c, tail, (c.summary IS NULL AND $role = 'user' AND $summary <> '') AS summarySetThisWrite
626
+ CREATE (m:Message:${role === "user" ? "UserMessage" : "AssistantMessage"} {
627
+ messageId: $messageId,
628
+ conversationId: $conversationId,
629
+ accountId: $accountId,
630
+ role: $role,
631
+ content: $content,
632
+ createdAt: ${createdAt ? "datetime($createdAt)" : "datetime()"}
633
+ ${embedding ? ", embedding: $embedding" : ""}
634
+ ${sender ? ", senderVisitorId: $senderVisitorId, senderName: $senderName" : ""}
635
+ ${tokens?.inputTokens != null ? ", inputTokens: $inputTokens" : ""}
636
+ ${tokens?.outputTokens != null ? ", outputTokens: $outputTokens" : ""}
637
+ ${tokens?.cacheReadTokens != null ? ", cacheReadTokens: $cacheReadTokens" : ""}
638
+ ${tokens?.cacheCreationTokens != null ? ", cacheCreationTokens: $cacheCreationTokens" : ""}
639
+ })
640
+ SET c.updatedAt = datetime()
641
+ CREATE (m)-[:PART_OF]->(c)
642
+ FOREACH (prev IN CASE WHEN tail IS NULL THEN [] ELSE [tail] END |
643
+ CREATE (prev)-[:NEXT]->(m)
644
+ )
645
+ FOREACH (_ IN CASE WHEN summarySetThisWrite THEN [1] ELSE [] END |
646
+ SET c.summary = $summary
647
+ )
648
+ FOREACH (comp IN $components |
649
+ CREATE (m)-[:HAS_COMPONENT]->(:Component {
650
+ componentId: comp.componentId,
651
+ conversationId: $conversationId,
652
+ accountId: $accountId,
653
+ messageId: $messageId,
654
+ name: comp.name,
655
+ data: comp.data,
656
+ ordinal: comp.ordinal,
657
+ textOffset: comp.textOffset,
658
+ submitted: false,
659
+ createdAt: datetime(),
660
+ // Task 942 \u2014 store the artefact attachmentId on the :Component
661
+ // itself when this is a PERSISTENT_COMPONENTS write whose disk
662
+ // write succeeded. Field is null for non-persistent / mime-skip
663
+ // / disk-fail components. Lets the audit + backfill scripts
664
+ // read the attachmentId directly off the :Component row instead
665
+ // of re-deriving (the live + heal paths use different sources \u2014
666
+ // sha256(block.id) live, componentId-fallback backfill \u2014 and
667
+ // the audit must match either).
668
+ attachmentId: comp.artefactAttachmentId
669
+ })
670
+ )
671
+ // Task 942 \u2014 for PERSISTENT_COMPONENTS whose disk write succeeded
672
+ // (artefactAttachmentId is non-null), MERGE the sibling
673
+ // :KnowledgeDocument projection AND a :HAS_KNOWLEDGE_DOCUMENT edge
674
+ // from the parent :Message in the same Cypher tx. ON CREATE stamps
675
+ // name+encodingFormat from the live render; ON MATCH only bumps
676
+ // updatedAt so a heal-on-resume re-run cannot clobber an operator's
677
+ // subsequent rename via the knowledge-documents API (eng-review \xA72).
678
+ // The edge makes the projection graph-discoverable from the
679
+ // conversation timeline so file-delete-cascade and conversation
680
+ // cleanup can reach it. FOREACH on the filtered list collapses to a
681
+ // no-op when no component has an attachmentId, preserving the
682
+ // text-only-turn fast path.
683
+ FOREACH (kd IN $knowledgeDocs |
684
+ MERGE (k:KnowledgeDocument {accountId: $accountId, attachmentId: kd.attachmentId})
685
+ ON CREATE SET k.name = kd.title,
686
+ k.encodingFormat = kd.mimeType,
687
+ k.createdAt = datetime(),
688
+ k.updatedAt = datetime()
689
+ ON MATCH SET k.updatedAt = datetime()
690
+ MERGE (m)-[:HAS_KNOWLEDGE_DOCUMENT]->(k)
691
+ )
692
+ FOREACH (att IN $attachments |
693
+ CREATE (m)-[:HAS_ATTACHMENT]->(:Attachment {
694
+ attachmentId: att.attachmentId,
695
+ conversationId: $conversationId,
696
+ accountId: $accountId,
697
+ messageId: $messageId,
698
+ filename: att.filename,
699
+ mimeType: att.mimeType,
700
+ sizeBytes: att.sizeBytes,
701
+ storagePath: att.storagePath,
702
+ ordinal: att.ordinal,
703
+ createdAt: datetime()
704
+ })
705
+ )
706
+ RETURN tail.messageId AS prevMessageId,
707
+ summarySetThisWrite,
708
+ size([(m2:Message)-[:PART_OF]->(c) | m2]) AS chainLen`,
709
+ {
710
+ messageId,
711
+ conversationId,
712
+ accountId,
713
+ role,
714
+ content,
715
+ summary,
716
+ ...createdAt ? { createdAt } : {},
717
+ ...embedding ? { embedding } : {},
718
+ ...sender ? { senderVisitorId: sender.visitorId, senderName: sender.displayName } : {},
719
+ ...tokens?.inputTokens != null ? { inputTokens: neo4j.int(tokens.inputTokens) } : {},
720
+ ...tokens?.outputTokens != null ? { outputTokens: neo4j.int(tokens.outputTokens) } : {},
721
+ ...tokens?.cacheReadTokens != null ? { cacheReadTokens: neo4j.int(tokens.cacheReadTokens) } : {},
722
+ ...tokens?.cacheCreationTokens != null ? { cacheCreationTokens: neo4j.int(tokens.cacheCreationTokens) } : {},
723
+ components: (components ?? []).map((comp) => ({
724
+ componentId: comp.componentId,
725
+ name: comp.name,
726
+ data: comp.data,
727
+ ordinal: neo4j.int(comp.ordinal),
728
+ textOffset: neo4j.int(comp.textOffset),
729
+ // Task 942 — null for non-persistent / mime-skip / disk-fail
730
+ // components; the FOREACH stamps this directly onto the
731
+ // :Component row so audit + backfill read attachmentId without
732
+ // re-deriving from componentId.
733
+ artefactAttachmentId: comp.artefactAttachmentId ?? null
734
+ })),
735
+ // Task 942 — :KnowledgeDocument MERGE list. One row per
736
+ // PERSISTENT_COMPONENTS component whose disk write succeeded;
737
+ // text-only / mime-skip / disk-fail components are absent so
738
+ // the FOREACH no-ops on them. attachmentId here matches the
739
+ // value the stream-parser stamped after writeAttachment.
740
+ knowledgeDocs: (components ?? []).filter((comp) => typeof comp.artefactAttachmentId === "string").map((comp) => ({
741
+ attachmentId: comp.artefactAttachmentId,
742
+ title: comp.artefactTitle ?? "",
743
+ mimeType: comp.artefactMimeType ?? ""
744
+ })),
745
+ attachments: (attachments ?? []).map((att) => ({
746
+ attachmentId: att.attachmentId,
747
+ filename: att.filename,
748
+ mimeType: att.mimeType,
749
+ sizeBytes: neo4j.int(att.sizeBytes),
750
+ storagePath: att.storagePath,
751
+ ordinal: neo4j.int(att.ordinal)
752
+ }))
753
+ }
754
+ );
755
+ if (result.records.length === 0) {
756
+ console.error(`[persist] Neo4j write skipped \u2014 conversation not found: ${conversationId.slice(0, 8)}\u2026`);
757
+ return null;
758
+ }
759
+ const record = result.records[0];
760
+ const prevMessageId = record.get("prevMessageId") ?? null;
761
+ const summarySetThisWrite = record.get("summarySetThisWrite") === true;
762
+ const chainLenRaw = record.get("chainLen");
763
+ const chainLen = typeof chainLenRaw === "bigint" ? Number(chainLenRaw) : typeof chainLenRaw?.toNumber === "function" ? chainLenRaw.toNumber() : Number(chainLenRaw ?? 0);
764
+ const messageSublabel = role === "user" ? "UserMessage" : "AssistantMessage";
765
+ console.error(`[neo4j-store] append-message conversationId=${conversationId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 prev=${prevMessageId ? prevMessageId.slice(0, 8) + "\u2026" : "null"} chainLen=${chainLen} waited=${waited} sublabel=${messageSublabel}`);
766
+ if (summarySetThisWrite) {
767
+ console.error(`[neo4j-store] conversation-summary-set conversationId=${conversationId.slice(0, 8)}\u2026 len=${summary.length}`);
768
+ }
769
+ const componentList = components ?? [];
770
+ if (componentList.length > 0) {
771
+ const relsCreated = result.summary.counters.updates().relationshipsCreated;
772
+ const expectedComponentEdges = componentList.length;
773
+ const baseEdges = relsCreated - expectedComponentEdges;
774
+ if (baseEdges < 1) {
775
+ console.error(`[neo4j-store] persist-component WARN conversationId=${conversationId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 relsCreated=${relsCreated} expected\u2265${1 + expectedComponentEdges} \u2014 component edges may not have been created`);
776
+ }
777
+ for (const comp of componentList) {
778
+ console.error(`[neo4j-store] persist-component conversationId=${conversationId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 componentId=${comp.componentId.slice(0, 8)}\u2026 name=${comp.name} dataLen=${comp.data.length} ordinal=${comp.ordinal} textOffset=${comp.textOffset}`);
779
+ }
780
+ }
781
+ const attachmentList = attachments ?? [];
782
+ if (attachmentList.length > 0) {
783
+ const relsCreated = result.summary.counters.updates().relationshipsCreated;
784
+ const expectedAttachmentEdges = attachmentList.length;
785
+ const expectedComponentEdges = (components ?? []).length;
786
+ const baseEdges = relsCreated - expectedComponentEdges - expectedAttachmentEdges;
787
+ if (baseEdges < 1) {
788
+ console.error(`[neo4j-store] persist-attachment WARN conversationId=${conversationId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 relsCreated=${relsCreated} expected\u2265${1 + expectedComponentEdges + expectedAttachmentEdges} \u2014 attachment edges may not have been created`);
789
+ }
790
+ for (const att of attachmentList) {
791
+ console.error(`[neo4j-store] persist-attachment conversationId=${conversationId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 attachmentId=${att.attachmentId.slice(0, 8)}\u2026 filename=${att.filename} mimeType=${att.mimeType} sizeBytes=${att.sizeBytes} ordinal=${att.ordinal}`);
792
+ }
793
+ }
794
+ console.error(`[persist] ${(/* @__PURE__ */ new Date()).toISOString()} conversationId=${conversationId.slice(0, 8)}\u2026 role=${role} len=${content.length}${sender ? ` sender=${sender.displayName}` : ""}`);
795
+ return messageId;
796
+ } catch (err) {
797
+ console.error(`[persist] Neo4j write failed: ${err instanceof Error ? err.message : String(err)}`);
798
+ return null;
799
+ } finally {
800
+ release();
801
+ if (persistMessageLocks.get(conversationId) === chained) {
802
+ persistMessageLocks.delete(conversationId);
803
+ }
804
+ await session.close();
805
+ }
806
+ }
807
+ async function setConversationAgentSessionId(conversationId, agentSessionId) {
808
+ const prev = persistMessageLocks.get(conversationId);
809
+ let release;
810
+ const mine = new Promise((resolve2) => {
811
+ release = resolve2;
812
+ });
813
+ const chained = (prev ?? Promise.resolve()).then(() => mine);
814
+ persistMessageLocks.set(conversationId, chained);
815
+ await prev;
816
+ const session = getSession();
817
+ try {
818
+ const result = await session.run(
819
+ `MATCH (c:Conversation {conversationId: $conversationId})
820
+ SET c.agentSessionId = $agentSessionId
821
+ RETURN c.conversationId AS conversationId`,
822
+ { conversationId, agentSessionId }
823
+ );
824
+ if (result.records.length === 0) {
825
+ console.error(`[persist] agent-session-id convId=${conversationId.slice(0, 8)}\u2026 status=skipped reason=conversation-not-found`);
826
+ return false;
827
+ }
828
+ console.log(`[persist] agent-session-id convId=${conversationId.slice(0, 8)}\u2026 status=ok agentSessionId=${agentSessionId ? agentSessionId.slice(0, 8) + "\u2026" : "null"}`);
829
+ return true;
830
+ } catch (err) {
831
+ console.error(`[persist] agent-session-id convId=${conversationId.slice(0, 8)}\u2026 status=failed error=${err instanceof Error ? err.message : String(err)}`);
832
+ return false;
833
+ } finally {
834
+ release();
835
+ if (persistMessageLocks.get(conversationId) === chained) {
836
+ persistMessageLocks.delete(conversationId);
837
+ }
838
+ await session.close();
839
+ }
840
+ }
841
+ async function writeTurnFailure(args) {
842
+ const session = getSession();
843
+ try {
844
+ const result = await session.run(
845
+ `MATCH (c:Conversation {conversationId: $conversationId, accountId: $accountId})
846
+ MERGE (c)-[:HAS_FAILURE]->(f:TurnFailure {conversationId: $conversationId, at: datetime($at)})
847
+ ON CREATE SET
848
+ f.mode = $mode,
849
+ f.cacheKey = $cacheKey,
850
+ f.prior_event_count = $priorEventCount,
851
+ f.accountId = $accountId,
852
+ f.receivedAt = datetime()
853
+ RETURN toString(f.at) AS at`,
854
+ {
855
+ conversationId: args.conversationId,
856
+ accountId: args.accountId,
857
+ mode: args.mode,
858
+ at: args.at,
859
+ cacheKey: args.cacheKey,
860
+ priorEventCount: args.priorEventCount
861
+ }
862
+ );
863
+ if (result.records.length === 0) {
864
+ return { ok: false, reason: "cid-not-found" };
865
+ }
866
+ return { ok: true, at: result.records[0].get("at") };
867
+ } catch (err) {
868
+ console.error(`[persist] turn-failure convId=${args.conversationId.slice(0, 8)}\u2026 error=${err instanceof Error ? err.message : String(err)}`);
869
+ return { ok: false, reason: "neo4j" };
870
+ } finally {
871
+ await session.close();
872
+ }
873
+ }
874
+ async function getAgentSessionIdForConversation(conversationId) {
875
+ const session = getSession();
876
+ try {
877
+ const result = await session.run(
878
+ `MATCH (c:Conversation {conversationId: $conversationId})
879
+ RETURN c.agentSessionId AS agentSessionId`,
880
+ { conversationId }
881
+ );
882
+ const value = result.records[0]?.get("agentSessionId");
883
+ return typeof value === "string" && value.length > 0 ? value : null;
884
+ } catch (err) {
885
+ console.error(`[persist] agent-session-id read failed convId=${conversationId.slice(0, 8)}\u2026 error=${err instanceof Error ? err.message : String(err)}`);
886
+ return null;
887
+ } finally {
888
+ await session.close();
889
+ }
890
+ }
891
+ async function getMostRecentAdminConversationForUser(accountId, userId) {
892
+ const session = getSession();
893
+ try {
894
+ const result = await session.run(
895
+ `MATCH (c:Conversation {accountId: $accountId, userId: $userId, agentType: 'admin'})
896
+ WHERE c.agentSessionId IS NOT NULL
897
+ RETURN c.conversationId AS conversationId, c.agentSessionId AS agentSessionId, c.createdAt AS createdAt
898
+ ORDER BY c.createdAt DESC
899
+ LIMIT 1`,
900
+ { accountId, userId }
901
+ );
902
+ const record = result.records[0];
903
+ if (!record) return null;
904
+ const conversationId = record.get("conversationId");
905
+ const agentSessionId = record.get("agentSessionId");
906
+ if (typeof conversationId !== "string" || !conversationId) return null;
907
+ if (typeof agentSessionId !== "string" || !agentSessionId) return null;
908
+ return { conversationId, agentSessionId };
909
+ } catch (err) {
910
+ console.error(`[persist] prior-admin-conversation read failed accountId=${accountId.slice(0, 8)}\u2026 userId=${userId.slice(0, 8)}\u2026 error=${err instanceof Error ? err.message : String(err)}`);
911
+ return null;
912
+ } finally {
913
+ await session.close();
914
+ }
915
+ }
916
+ async function getRecentMessages(conversationId, limit = 50) {
917
+ const session = getSession();
918
+ try {
919
+ const result = await session.run(
920
+ `MATCH (tail:Message {conversationId: $conversationId})
921
+ WHERE NOT (tail)-[:NEXT]->(:Message)
922
+ WITH tail ORDER BY tail.createdAt DESC LIMIT 1
923
+ MATCH path = (m:Message)-[:NEXT*0..]->(tail)
924
+ WHERE m.conversationId = $conversationId
925
+ AND length(path) < $limit
926
+ WITH m, length(path) AS depthFromTail
927
+ OPTIONAL MATCH (m)-[:HAS_COMPONENT]->(c:Component)
928
+ WITH m, depthFromTail, c ORDER BY c.ordinal ASC
929
+ WITH m, depthFromTail,
930
+ [comp IN collect(c) WHERE comp IS NOT NULL | comp {.*}] AS components
931
+ OPTIONAL MATCH (m)-[:HAS_ATTACHMENT]->(a:Attachment)
932
+ WITH m, depthFromTail, components, a ORDER BY a.ordinal ASC
933
+ WITH m, depthFromTail, components,
934
+ [att IN collect(a) WHERE att IS NOT NULL | att {.*}] AS attachments
935
+ RETURN m.messageId AS messageId, m.role AS role, m.content AS content,
936
+ m.createdAt AS createdAt, components, attachments
937
+ ORDER BY depthFromTail DESC`,
938
+ { conversationId, limit: neo4j.int(limit) }
939
+ );
940
+ return result.records.map((r) => {
941
+ const rawComponents = r.get("components") ?? [];
942
+ const components = rawComponents.map((c) => {
943
+ const rawAttachmentId = c.attachmentId;
944
+ const attachmentId = typeof rawAttachmentId === "string" && rawAttachmentId.length > 0 ? rawAttachmentId : void 0;
945
+ return {
946
+ componentId: String(c.componentId ?? ""),
947
+ name: String(c.name ?? ""),
948
+ data: String(c.data ?? ""),
949
+ ordinal: typeof c.ordinal?.toNumber === "function" ? c.ordinal.toNumber() : Number(c.ordinal ?? 0),
950
+ textOffset: typeof c.textOffset?.toNumber === "function" ? c.textOffset.toNumber() : Number(c.textOffset ?? 0),
951
+ submitted: c.submitted === true,
952
+ ...attachmentId ? { attachmentId } : {}
953
+ };
954
+ });
955
+ const rawAttachments = r.get("attachments") ?? [];
956
+ const attachments = rawAttachments.map((a) => ({
957
+ attachmentId: String(a.attachmentId ?? ""),
958
+ filename: String(a.filename ?? ""),
959
+ mimeType: String(a.mimeType ?? ""),
960
+ sizeBytes: typeof a.sizeBytes?.toNumber === "function" ? a.sizeBytes.toNumber() : Number(a.sizeBytes ?? 0),
961
+ storagePath: String(a.storagePath ?? ""),
962
+ ordinal: typeof a.ordinal?.toNumber === "function" ? a.ordinal.toNumber() : Number(a.ordinal ?? 0),
963
+ accountId: String(a.accountId ?? "")
964
+ }));
965
+ return {
966
+ messageId: r.get("messageId"),
967
+ role: r.get("role"),
968
+ content: r.get("content"),
969
+ createdAt: String(r.get("createdAt")),
970
+ components,
971
+ attachments
972
+ };
973
+ });
974
+ } catch (err) {
975
+ console.error(`[persist] getRecentMessages failed: ${err instanceof Error ? err.message : String(err)}`);
976
+ return [];
977
+ } finally {
978
+ await session.close();
979
+ }
980
+ }
981
+ async function markComponentSubmitted(conversationId, componentName, accountId) {
982
+ const session = getSession();
983
+ try {
984
+ const result = await session.run(
985
+ `MATCH (conv:Conversation {conversationId: $conversationId, accountId: $accountId})
986
+ MATCH (m:Message)-[:PART_OF]->(conv)
987
+ MATCH (m)-[:HAS_COMPONENT]->(c:Component {name: $componentName, accountId: $accountId})
988
+ WHERE c.submitted = false OR c.submitted IS NULL
989
+ WITH c, m ORDER BY m.createdAt DESC, c.ordinal DESC
990
+ LIMIT 1
991
+ SET c.submitted = true, c.submittedAt = datetime()
992
+ RETURN c.componentId AS componentId`,
993
+ { conversationId, componentName, accountId }
994
+ );
995
+ const componentId = result.records[0]?.get("componentId");
996
+ if (componentId) {
997
+ console.error(`[neo4j-store] component-submitted conversationId=${conversationId.slice(0, 8)}\u2026 name=${componentName} componentId=${componentId.slice(0, 8)}\u2026`);
998
+ return componentId;
999
+ }
1000
+ console.error(`[neo4j-store] component-submit-skipped conversationId=${conversationId.slice(0, 8)}\u2026 name=${componentName} reason=no-unsubmitted-match`);
1001
+ return null;
1002
+ } catch (err) {
1003
+ console.error(`[neo4j-store] component-submit-failed conversationId=${conversationId.slice(0, 8)}\u2026 name=${componentName} error=${err instanceof Error ? err.message : String(err)}`);
1004
+ return null;
1005
+ } finally {
1006
+ await session.close();
1007
+ }
1008
+ }
1009
+ async function verifyConversationOwnership(conversationId, accountId) {
1010
+ const session = getSession();
1011
+ try {
1012
+ const result = await session.run(
1013
+ `MATCH (c:Conversation {conversationId: $conversationId, accountId: $accountId})
1014
+ RETURN c.conversationId AS id LIMIT 1`,
1015
+ { conversationId, accountId }
1016
+ );
1017
+ return result.records.length > 0;
1018
+ } catch (err) {
1019
+ console.error(`[persist] verifyConversationOwnership failed: ${err instanceof Error ? err.message : String(err)}`);
1020
+ return false;
1021
+ } finally {
1022
+ await session.close();
1023
+ }
1024
+ }
1025
+ async function getConversationOwner(conversationId) {
1026
+ const session = getSession();
1027
+ try {
1028
+ const result = await session.run(
1029
+ `MATCH (c:Conversation {conversationId: $conversationId})
1030
+ RETURN c.accountId AS accountId, c.userId AS userId LIMIT 1`,
1031
+ { conversationId }
1032
+ );
1033
+ const record = result.records[0];
1034
+ if (!record) return null;
1035
+ const accountId = record.get("accountId");
1036
+ const userId = record.get("userId");
1037
+ if (!accountId) return null;
1038
+ return { accountId, userId: userId ?? null };
1039
+ } catch (err) {
1040
+ console.error(`[persist] getConversationOwner failed: ${err instanceof Error ? err.message : String(err)}`);
1041
+ return null;
1042
+ } finally {
1043
+ await session.close();
1044
+ }
1045
+ }
1046
+ async function verifyAndGetConversationUpdatedAt(conversationId, accountId) {
1047
+ const session = getSession();
1048
+ try {
1049
+ const result = await session.run(
1050
+ `MATCH (c:Conversation {conversationId: $conversationId, accountId: $accountId})
1051
+ RETURN toString(c.updatedAt) AS updatedAt LIMIT 1`,
1052
+ { conversationId, accountId }
1053
+ );
1054
+ const record = result.records[0];
1055
+ return record ? record.get("updatedAt") : null;
1056
+ } catch (err) {
1057
+ console.error(`[persist] verifyAndGetConversationUpdatedAt failed: ${err instanceof Error ? err.message : String(err)}`);
1058
+ return null;
1059
+ } finally {
1060
+ await session.close();
1061
+ }
1062
+ }
1063
+ async function searchMessages(accountId, queryEmbedding, limit = 10) {
1064
+ const session = getSession();
1065
+ try {
1066
+ const result = await session.run(
1067
+ `CALL db.index.vector.queryNodes('message_embedding', $limit, $embedding)
1068
+ YIELD node, score
1069
+ WHERE node.accountId = $accountId
1070
+ RETURN node.messageId AS messageId,
1071
+ node.role AS role,
1072
+ node.content AS content,
1073
+ node.conversationId AS conversationId,
1074
+ node.createdAt AS createdAt,
1075
+ score
1076
+ ORDER BY score DESC
1077
+ LIMIT $limit`,
1078
+ { embedding: queryEmbedding, limit: neo4j.int(limit), accountId }
1079
+ );
1080
+ return result.records.map((r) => ({
1081
+ messageId: r.get("messageId"),
1082
+ role: r.get("role"),
1083
+ content: r.get("content"),
1084
+ conversationId: r.get("conversationId"),
1085
+ createdAt: String(r.get("createdAt")),
1086
+ score: typeof r.get("score") === "number" ? r.get("score") : Number(r.get("score"))
1087
+ }));
1088
+ } catch (err) {
1089
+ console.error(`[persist] searchMessages failed: ${err instanceof Error ? err.message : String(err)}`);
1090
+ return [];
1091
+ } finally {
1092
+ await session.close();
1093
+ }
1094
+ }
1095
+ var LIST_BACKFILL_CAP = 3;
1096
+ async function listAdminSessions(accountId, userId, limit = 20) {
1097
+ const session = getSession();
1098
+ try {
1099
+ const result = await session.run(
1100
+ `MATCH (c:Conversation {accountId: $accountId, agentType: 'admin', userId: $userId})
1101
+ WHERE NOT c:Trashed
1102
+ WITH c
1103
+ ORDER BY c.updatedAt DESC
1104
+ LIMIT $limit
1105
+ CALL {
1106
+ WITH c
1107
+ OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
1108
+ WHERE m.role = 'user'
1109
+ AND c.name IS NULL
1110
+ AND NOT (m.content STARTS WITH '[New session.')
1111
+ AND NOT (m.content STARTS WITH '{"')
1112
+ AND size(m.content) >= 4
1113
+ RETURN m.content AS content, m.createdAt AS createdAt
1114
+ ORDER BY m.createdAt ASC
1115
+ LIMIT 1
1116
+ }
1117
+ RETURN c.conversationId AS conversationId,
1118
+ c.name AS name,
1119
+ c.updatedAt AS updatedAt,
1120
+ c.channel AS channel,
1121
+ content AS firstSubstantiveUserMessage`,
1122
+ { accountId, userId, limit: neo4j.int(limit) }
1123
+ );
1124
+ const rows = result.records.map((r) => ({
1125
+ conversationId: r.get("conversationId"),
1126
+ name: r.get("name"),
1127
+ updatedAt: String(r.get("updatedAt")),
1128
+ channel: r.get("channel"),
1129
+ firstSubstantiveUserMessage: r.get("firstSubstantiveUserMessage")
1130
+ }));
1131
+ let backfillsKicked = 0;
1132
+ for (const row of rows) {
1133
+ if (backfillsKicked >= LIST_BACKFILL_CAP) break;
1134
+ if (row.name !== null) continue;
1135
+ const seed = row.firstSubstantiveUserMessage;
1136
+ if (!seed || !isMessageUseful(seed)) continue;
1137
+ backfillsKicked++;
1138
+ autoLabelSession(row.conversationId, seed).catch(() => {
1139
+ });
1140
+ }
1141
+ return rows.map(({ conversationId, name, updatedAt, channel }) => ({ conversationId, name, updatedAt, channel }));
1142
+ } catch (err) {
1143
+ console.error(`[persist] listAdminSessions failed: ${err instanceof Error ? err.message : String(err)}`);
1144
+ return [];
1145
+ } finally {
1146
+ await session.close();
1147
+ }
1148
+ }
1149
+ async function deleteConversation(conversationId) {
1150
+ const session = getSession();
1151
+ try {
1152
+ const result = await session.run(
1153
+ `MATCH (c:Conversation {conversationId: $conversationId})
1154
+ OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
1155
+ OPTIONAL MATCH (m)-[:HAS_COMPONENT]->(comp:Component)
1156
+ OPTIONAL MATCH (m)-[:HAS_ATTACHMENT]->(att:Attachment)
1157
+ DETACH DELETE att, comp, m, c
1158
+ RETURN count(c) AS deleted`,
1159
+ { conversationId }
1160
+ );
1161
+ const deleted = result.records[0]?.get("deleted");
1162
+ const count = typeof deleted === "object" && deleted !== null ? Number(deleted) : Number(deleted ?? 0);
1163
+ console.error(`[persist] deleteConversation ${conversationId.slice(0, 8)}\u2026: ${count > 0 ? "deleted" : "not found"}`);
1164
+ return count > 0;
1165
+ } catch (err) {
1166
+ console.error(`[persist] deleteConversation failed: ${err instanceof Error ? err.message : String(err)}`);
1167
+ return false;
1168
+ } finally {
1169
+ await session.close();
1170
+ }
1171
+ }
1172
+ var GENERIC_MESSAGE = /^(h(i|ello|ey|owdy)|yo|sup|thanks|thank you|ok|okay|yes|no|good\s*(morning|afternoon|evening|night)|greetings|what'?s\s*up)[\s!?.,:;]*$/i;
1173
+ var SESSION_LABEL_MSG_CAP = 500;
1174
+ var SESSION_LABEL_TIMEOUT_MS = 15e3;
1175
+ var SESSION_LABEL_MODEL = HAIKU_MODEL;
1176
+ var SESSION_LABEL_MAX_WORDS = 6;
1177
+ var SESSION_LABEL_MAX_ATTEMPTS = 3;
1178
+ var SESSION_LABEL_MAX_STDERR = 2048;
1179
+ function isMessageUseful(message) {
1180
+ const trimmed = message.trim();
1181
+ if (trimmed.length < 4) return false;
1182
+ if (trimmed.startsWith('{"')) return false;
1183
+ if (GENERIC_MESSAGE.test(trimmed)) return false;
1184
+ if (trimmed.startsWith(DIRECTIVE_PREFIX)) return false;
1185
+ return true;
1186
+ }
1187
+ function totalFailures(f) {
1188
+ return f.skip + f.error;
1189
+ }
1190
+ function failureBreakdown(f) {
1191
+ return `skip:${f.skip} error:${f.error}`;
1192
+ }
1193
+ var labelAccumulator = /* @__PURE__ */ new Map();
1194
+ var _spawnOverride = null;
1195
+ var SESSION_LABEL_SYSTEM = `You are a session labeler. Given the opening messages of a conversation with an AI assistant, produce a concise topic label.
1196
+
1197
+ Rules:
1198
+ - Exactly 3 to 6 words
1199
+ - Summarize the user's intent, do not copy verbatim
1200
+ - Capitalize the first word only (sentence case)
1201
+ - No punctuation, no quotes
1202
+ - You MUST always produce a label. Vague, terse, or single-word messages still get a best-effort label (e.g. a one-word "hi" or an emoji becomes "Greeting"; an unintelligible fragment becomes "Unstructured note"). Never abstain.`;
1203
+ async function generateSessionLabel(messages) {
1204
+ const cappedMessages = messages.map((m) => m.slice(0, SESSION_LABEL_MSG_CAP));
1205
+ const userContent = cappedMessages.map((m, i) => `Message ${i + 1}: ${m}`).join("\n");
1206
+ const prompt = `${SESSION_LABEL_SYSTEM}
1207
+
1208
+ ${userContent}`;
1209
+ const args = [
1210
+ "--print",
1211
+ "--model",
1212
+ SESSION_LABEL_MODEL,
1213
+ "--max-turns",
1214
+ "1",
1215
+ "--permission-mode",
1216
+ "dontAsk",
1217
+ prompt
1218
+ ];
1219
+ return new Promise((resolve2) => {
1220
+ let stdout = "";
1221
+ let stderr = "";
1222
+ const spawnFn = _spawnOverride ?? spawn;
1223
+ const proc = spawnFn("claude", args, {
1224
+ stdio: ["ignore", "pipe", "pipe"]
1225
+ });
1226
+ proc.stdout?.on("data", (chunk) => {
1227
+ stdout += chunk.toString("utf-8");
1228
+ });
1229
+ proc.stderr?.on("data", (chunk) => {
1230
+ if (stderr.length < SESSION_LABEL_MAX_STDERR) {
1231
+ stderr += chunk.toString("utf-8").slice(0, SESSION_LABEL_MAX_STDERR - stderr.length);
1232
+ }
1233
+ });
1234
+ const timer = setTimeout(() => {
1235
+ proc.kill("SIGTERM");
1236
+ console.error("[persist] autoLabel: haiku subprocess timed out");
1237
+ resolve2(null);
1238
+ }, SESSION_LABEL_TIMEOUT_MS);
1239
+ proc.on("error", (err) => {
1240
+ clearTimeout(timer);
1241
+ console.error(`[persist] autoLabel: subprocess error \u2014 ${err.message}`);
1242
+ resolve2(null);
1243
+ });
1244
+ proc.on("close", (code) => {
1245
+ clearTimeout(timer);
1246
+ if (code !== 0) {
1247
+ console.error(`[persist] autoLabel: subprocess exited code=${code}${stderr ? ` stderr=${stderr.trim().slice(0, 200)}` : ""}`);
1248
+ resolve2(null);
1249
+ return;
1250
+ }
1251
+ const text = stdout.trim();
1252
+ if (!text) {
1253
+ console.error("[persist] autoLabel: haiku returned empty response");
1254
+ resolve2(null);
1255
+ return;
1256
+ }
1257
+ const words = text.split(/\s+/).slice(0, SESSION_LABEL_MAX_WORDS);
1258
+ const label = words.join(" ");
1259
+ console.error(`[persist] autoLabel: haiku response="${label}"`);
1260
+ resolve2(label);
1261
+ });
1262
+ });
1263
+ }
1264
+ async function autoLabelSession(conversationId, userMessage) {
1265
+ if (!conversationId) return;
1266
+ if (!isMessageUseful(userMessage)) {
1267
+ const trimmed = userMessage.trim();
1268
+ const reason = trimmed.startsWith('{"') ? "JSON envelope" : trimmed.startsWith(DIRECTIVE_PREFIX) ? "directive" : GENERIC_MESSAGE.test(trimmed) ? "greeting" : trimmed.length < 4 ? "too short" : "directive";
1269
+ console.error(`[persist] autoLabel: skipped ${conversationId.slice(0, 8)}\u2026 \u2014 ${reason}`);
1270
+ return;
1271
+ }
1272
+ try {
1273
+ const preCheck = getSession();
1274
+ try {
1275
+ const res = await preCheck.run(
1276
+ `MATCH (c:Conversation {conversationId: $conversationId})
1277
+ OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
1278
+ WHERE m.role = 'user'
1279
+ WITH c, count(m) AS userCount
1280
+ RETURN c.name AS name, userCount`,
1281
+ { conversationId }
1282
+ );
1283
+ const firstRecord = res.records[0];
1284
+ const existingName = firstRecord?.get("name");
1285
+ const userCountRaw = firstRecord?.get("userCount");
1286
+ const userCount = typeof userCountRaw === "object" && userCountRaw !== null ? Number(userCountRaw) : Number(userCountRaw ?? 0);
1287
+ if (existingName) {
1288
+ console.error(`[persist] autoLabel: already named ${conversationId.slice(0, 8)}\u2026 \u2014 skipping`);
1289
+ labelAccumulator.delete(conversationId);
1290
+ return;
1291
+ }
1292
+ if (userCount > 3) {
1293
+ console.error(`[persist] autoLabel: past autolabel window ${conversationId.slice(0, 8)}\u2026 \u2014 userCount=${userCount}, skipping`);
1294
+ labelAccumulator.delete(conversationId);
1295
+ return;
1296
+ }
1297
+ } finally {
1298
+ await preCheck.close();
1299
+ }
1300
+ } catch (err) {
1301
+ console.error(`[persist] autoLabel: pre-check read failed for ${conversationId.slice(0, 8)}\u2026 \u2014 proceeding: ${err instanceof Error ? err.message : String(err)}`);
1302
+ }
1303
+ let entry = labelAccumulator.get(conversationId);
1304
+ if (!entry) {
1305
+ entry = {
1306
+ messages: [],
1307
+ pending: false,
1308
+ failures: { skip: 0, error: 0 }
1309
+ };
1310
+ labelAccumulator.set(conversationId, entry);
1311
+ }
1312
+ if (totalFailures(entry.failures) >= SESSION_LABEL_MAX_ATTEMPTS) {
1313
+ console.error(`[persist] autoLabel: evicted ${conversationId.slice(0, 8)}\u2026 after ${SESSION_LABEL_MAX_ATTEMPTS} failed-attempts (${failureBreakdown(entry.failures)})`);
1314
+ labelAccumulator.delete(conversationId);
1315
+ return;
1316
+ }
1317
+ entry.messages.push(userMessage.trim());
1318
+ if (entry.pending) {
1319
+ console.error(`[persist] autoLabel: accumulated for ${conversationId.slice(0, 8)}\u2026 (pending, ${entry.messages.length} msgs)`);
1320
+ return;
1321
+ }
1322
+ entry.pending = true;
1323
+ try {
1324
+ const label = await generateSessionLabel(entry.messages);
1325
+ if (!label) {
1326
+ entry.failures.skip++;
1327
+ console.error(`[persist] autoLabel: generateSessionLabel returned null for ${conversationId.slice(0, 8)}\u2026 (failures ${failureBreakdown(entry.failures)}, ${entry.messages.length} msgs)`);
1328
+ entry.pending = false;
1329
+ return;
1330
+ }
1331
+ const fullLabel = `${label} \xB7 ${conversationId.slice(0, 8)}`;
1332
+ let embedding = null;
1333
+ try {
1334
+ embedding = await embed(fullLabel);
1335
+ } catch (err) {
1336
+ console.error(`[persist] Conversation embedding failed, labelling without: ${err instanceof Error ? err.message : String(err)}`);
1337
+ }
1338
+ const session = getSession();
1339
+ try {
1340
+ const result = await session.run(
1341
+ `MATCH (c:Conversation {conversationId: $conversationId})
1342
+ WHERE c.name IS NULL
1343
+ WITH c
1344
+ OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
1345
+ WHERE m.role = 'user'
1346
+ WITH c, count(m) AS userCount
1347
+ WHERE userCount <= 3
1348
+ SET c.name = $label, c.updatedAt = datetime()
1349
+ ${embedding ? ", c.embedding = $embedding" : ""}
1350
+ RETURN c.name AS name`,
1351
+ { conversationId, label: fullLabel, ...embedding ? { embedding } : {} }
1352
+ );
1353
+ if (result.records.length > 0) {
1354
+ console.error(`[persist] autoLabel: commit ${conversationId.slice(0, 8)}\u2026 name="${fullLabel}"${embedding ? " (embedded)" : ""}`);
1355
+ labelAccumulator.delete(conversationId);
1356
+ } else {
1357
+ console.error(`[persist] autoLabel: no-op commit ${conversationId.slice(0, 8)}\u2026 (name already set or userCount>3)`);
1358
+ labelAccumulator.delete(conversationId);
1359
+ }
1360
+ } catch (err) {
1361
+ entry.failures.error++;
1362
+ console.error(`[persist] autoLabelSession failed: ${err instanceof Error ? err.message : String(err)} (failures ${failureBreakdown(entry.failures)})`);
1363
+ } finally {
1364
+ await session.close();
1365
+ }
1366
+ } catch (err) {
1367
+ const currentEntry = labelAccumulator.get(conversationId);
1368
+ if (currentEntry) currentEntry.failures.error++;
1369
+ console.error(`[persist] autoLabel: unexpected error \u2014 ${err instanceof Error ? err.message : String(err)}${currentEntry ? ` (failures ${failureBreakdown(currentEntry.failures)})` : ""}`);
1370
+ } finally {
1371
+ const currentEntry = labelAccumulator.get(conversationId);
1372
+ if (currentEntry) currentEntry.pending = false;
1373
+ }
1374
+ }
1375
+ async function renameConversation(conversationId, label) {
1376
+ let embedding = null;
1377
+ try {
1378
+ embedding = await embed(label);
1379
+ } catch (err) {
1380
+ console.error(`[persist] manual-label: embedding failed, persisting without: ${err instanceof Error ? err.message : String(err)}`);
1381
+ }
1382
+ const session = getSession();
1383
+ try {
1384
+ await session.run(
1385
+ `MATCH (c:Conversation {conversationId: $conversationId})
1386
+ SET c.name = $label, c.updatedAt = datetime()
1387
+ ${embedding ? ", c.embedding = $embedding" : ""}`,
1388
+ { conversationId, label, ...embedding ? { embedding } : {} }
1389
+ );
1390
+ console.error(`[persist] manual-label: renamed ${conversationId} to "${label}"${embedding ? " (embedded)" : ""}`);
1391
+ } finally {
1392
+ await session.close();
1393
+ }
1394
+ }
1395
+ var DECAY_THRESHOLD_DAYS = 14;
1396
+ var DECAY_RATE_PER_DAY = 0.05;
1397
+ var INJECTION_THRESHOLD = 0.4;
1398
+ var MAX_SUMMARY_PREFERENCES = 30;
1399
+ async function getUserTimezone(accountId, userId) {
1400
+ const session = getSession();
1401
+ try {
1402
+ const query = userId ? `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
1403
+ RETURN up.timezone AS timezone` : `MATCH (up:UserProfile {accountId: $accountId})
1404
+ RETURN up.timezone AS timezone ORDER BY up.createdAt LIMIT 1`;
1405
+ const result = await session.run(query, { accountId, userId: userId ?? "" });
1406
+ if (result.records.length === 0) return null;
1407
+ const tz = result.records[0].get("timezone");
1408
+ return tz && tz.trim().length > 0 ? tz : null;
1409
+ } catch (err) {
1410
+ console.error(`[datetime] getUserTimezone failed: ${err instanceof Error ? err.message : String(err)}`);
1411
+ return null;
1412
+ } finally {
1413
+ await session.close();
1414
+ }
1415
+ }
1416
+ async function loadAdminUserName(accountId, userId) {
1417
+ const session = getSession();
1418
+ try {
1419
+ const result = await session.run(
1420
+ `MATCH (au:AdminUser {userId: $userId})-[:OWNS]->(p:Person {accountId: $accountId})
1421
+ RETURN p.givenName AS givenName, p.familyName AS familyName, p.avatar AS avatar
1422
+ LIMIT 1`,
1423
+ { accountId, userId }
1424
+ );
1425
+ if (result.records.length === 0) {
1426
+ return { source: "fallback", reason: "no-person-node" };
1427
+ }
1428
+ const givenName = result.records[0].get("givenName");
1429
+ const familyName = result.records[0].get("familyName");
1430
+ const avatar = result.records[0].get("avatar");
1431
+ if (!givenName || givenName.trim().length === 0) {
1432
+ return { source: "fallback", reason: "no-givenName" };
1433
+ }
1434
+ const trimmedFamily = familyName && familyName.trim().length > 0 ? familyName.trim() : null;
1435
+ const trimmedAvatar = avatar && avatar.trim().length > 0 ? avatar.trim() : null;
1436
+ const joined = trimmedFamily ? `${givenName.trim()} ${trimmedFamily}` : givenName.trim();
1437
+ return { source: "neo4j", joined, givenName: givenName.trim(), familyName: trimmedFamily, avatar: trimmedAvatar };
1438
+ } catch (err) {
1439
+ console.error(`[admin-identity] loadAdminUserName failed: ${err instanceof Error ? err.message : String(err)}`);
1440
+ return { source: "fallback", reason: "neo4j-unreachable" };
1441
+ } finally {
1442
+ await session.close();
1443
+ }
1444
+ }
1445
+ async function writeAdminUserAndPerson(params) {
1446
+ const { userId, fullName, accountId } = params;
1447
+ const trimmed = fullName.trim();
1448
+ if (!trimmed) {
1449
+ throw new Error("writeAdminUserAndPerson: fullName cannot be empty");
1450
+ }
1451
+ const firstSpace = trimmed.search(/\s/);
1452
+ const givenName = firstSpace === -1 ? trimmed : trimmed.slice(0, firstSpace).trim();
1453
+ const familyName = firstSpace === -1 ? null : trimmed.slice(firstSpace + 1).trim() || null;
1454
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1455
+ const session = getSession();
1456
+ try {
1457
+ const result = await session.run(
1458
+ `MERGE (au:AdminUser {userId: $userId})
1459
+ ON CREATE SET au.name = $fullName, au.createdAt = $now
1460
+ ON MATCH SET au.name = $fullName, au.updatedAt = $now
1461
+ WITH au
1462
+
1463
+ // Case-insensitive Person reuse: same accountId, same givenName, same familyName
1464
+ // (null/empty familyName collapsed to '' so 'Joel' does NOT match 'Joel Smalley').
1465
+ OPTIONAL MATCH (existingPerson:Person {accountId: $accountId})
1466
+ WHERE toLower(existingPerson.givenName) = toLower($givenName)
1467
+ AND coalesce(toLower(existingPerson.familyName), '') = coalesce(toLower($familyName), '')
1468
+ WITH au, existingPerson
1469
+
1470
+ CALL {
1471
+ WITH au, existingPerson
1472
+ WITH au, existingPerson WHERE existingPerson IS NOT NULL
1473
+ MERGE (au)-[:OWNS]->(existingPerson)
1474
+ RETURN existingPerson AS p, true AS reused
1475
+ UNION
1476
+ WITH au, existingPerson
1477
+ WITH au WHERE existingPerson IS NULL
1478
+ CREATE (newPerson:Person {
1479
+ accountId: $accountId,
1480
+ givenName: $givenName,
1481
+ familyName: $familyName,
1482
+ role: 'admin-personal',
1483
+ scope: 'admin',
1484
+ createdAt: $now
1485
+ })
1486
+ MERGE (au)-[:OWNS]->(newPerson)
1487
+ RETURN newPerson AS p, false AS reused
1488
+ }
1489
+ RETURN reused, elementId(p) AS personElementId,
1490
+ p.givenName AS givenName, p.familyName AS familyName`,
1491
+ { userId, fullName: trimmed, accountId, givenName, familyName, now }
1492
+ );
1493
+ if (result.records.length === 0) {
1494
+ throw new Error("writeAdminUserAndPerson: no record returned");
1495
+ }
1496
+ const record = result.records[0];
1497
+ return {
1498
+ personReused: record.get("reused"),
1499
+ personElementId: record.get("personElementId"),
1500
+ givenName: record.get("givenName"),
1501
+ familyName: record.get("familyName")
1502
+ };
1503
+ } finally {
1504
+ await session.close();
1505
+ }
1506
+ }
1507
+ var PROFILE_CATEGORIES = [
1508
+ "communication",
1509
+ "scheduling",
1510
+ "decision",
1511
+ "workflow",
1512
+ "content",
1513
+ "interaction"
1514
+ ];
1515
+ var PROFILE_FIELD_TEMPLATES = {
1516
+ communication: [
1517
+ "preferredChannel",
1518
+ "quietHours",
1519
+ "responseLatencyExpectation",
1520
+ "formalityLevel",
1521
+ "escalationPath"
1522
+ ],
1523
+ scheduling: [
1524
+ "workdayStartTime",
1525
+ "workdayEndTime",
1526
+ "weekendAvailability",
1527
+ "meetingBlockPreference",
1528
+ "focusBlockTiming"
1529
+ ],
1530
+ decision: [
1531
+ "riskTolerance",
1532
+ "autonomyBoundary",
1533
+ "evidenceThreshold",
1534
+ "reversibilityPreference",
1535
+ "stakeholderConsultation"
1536
+ ],
1537
+ workflow: [
1538
+ "batchingPreference",
1539
+ "taskGranularity",
1540
+ "deepWorkBlocks",
1541
+ "statusUpdateCadence",
1542
+ "toolingChoices"
1543
+ ],
1544
+ content: [
1545
+ "outputFormat",
1546
+ "lengthPreference",
1547
+ "citationStyle",
1548
+ "tonality"
1549
+ ],
1550
+ interaction: [
1551
+ "addressForm",
1552
+ "humourTolerance",
1553
+ "directnessLevel",
1554
+ "emotionalRegisterPreference"
1555
+ ]
1556
+ };
1557
+ var TOTAL_PROFILE_FIELDS = Object.values(PROFILE_FIELD_TEMPLATES).reduce(
1558
+ (n, fs) => n + fs.length,
1559
+ 0
1560
+ );
1561
+ function computeAbsentFields(preferences) {
1562
+ const covered = /* @__PURE__ */ new Set();
1563
+ for (const pref of preferences) {
1564
+ const isCovered = pref.notApplicable === true || pref.confidence >= INJECTION_THRESHOLD;
1565
+ if (isCovered) covered.add(`${pref.category}.${pref.key}`);
1566
+ }
1567
+ const absent = [];
1568
+ for (const [category, fields] of Object.entries(PROFILE_FIELD_TEMPLATES)) {
1569
+ for (const field of fields) {
1570
+ const dotted = `${category}.${field}`;
1571
+ if (!covered.has(dotted)) absent.push(dotted);
1572
+ }
1573
+ }
1574
+ return absent;
1575
+ }
1576
+ var sparseStateLogged = /* @__PURE__ */ new Set();
1577
+ async function loadUserProfile(accountId, userId, conversationId) {
1578
+ console.error(
1579
+ `[profile] loadUserProfile entry accountId=${accountId.slice(0, 8)}\u2026 userId=${userId} conversationId=${conversationId ? `${conversationId.slice(0, 8)}\u2026` : "<none>"}`
1580
+ );
1581
+ const session = getSession();
1582
+ try {
1583
+ const serverTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
1584
+ const mergeResult = await session.run(
1585
+ `MATCH (au:AdminUser {userId: $userId})
1586
+ MERGE (au)-[:HAS_PROFILE]->(up:UserProfile {accountId: $accountId, userId: $userId})
1587
+ ON CREATE SET
1588
+ up.createdAt = $now,
1589
+ up.updatedAt = $now,
1590
+ up.profileVersion = 0,
1591
+ up.scope = 'admin',
1592
+ up.timezone = $serverTimezone
1593
+ ON MATCH SET
1594
+ up.timezone = CASE WHEN up.timezone IS NULL OR trim(up.timezone) = '' THEN $serverTimezone ELSE up.timezone END
1595
+ RETURN up.createdAt = $now AS isNew`,
1596
+ { accountId, userId, now: (/* @__PURE__ */ new Date()).toISOString(), serverTimezone }
1597
+ );
1598
+ if (mergeResult.records.length === 0) {
1599
+ console.error(`[profile] loadUserProfile: AdminUser not found for userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 \u2014 profile not created, invariant violated`);
1600
+ return null;
1601
+ }
1602
+ const isNew = mergeResult.records[0].get("isNew");
1603
+ if (isNew) {
1604
+ console.error(`[profile] created new profile: userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 timezone=${serverTimezone}`);
1605
+ }
1606
+ const nowMs = Date.now();
1607
+ const thresholdMs = DECAY_THRESHOLD_DAYS * 24 * 60 * 60 * 1e3;
1608
+ const staleResult = await session.run(
1609
+ `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})-[:HAS_PREFERENCE]->(pref:Preference)
1610
+ WHERE pref.observedAt IS NOT NULL
1611
+ RETURN pref.preferenceId AS preferenceId,
1612
+ pref.observedAt AS observedAt,
1613
+ pref.confidence AS confidence`,
1614
+ { accountId, userId }
1615
+ );
1616
+ let decayCount = 0;
1617
+ for (const record of staleResult.records) {
1618
+ const observedAt = record.get("observedAt");
1619
+ const confidence = record.get("confidence");
1620
+ const observedMs = new Date(observedAt).getTime();
1621
+ const ageMs = nowMs - observedMs;
1622
+ if (ageMs > thresholdMs && confidence > 0) {
1623
+ const daysPastThreshold = (ageMs - thresholdMs) / (24 * 60 * 60 * 1e3);
1624
+ const decayedConfidence = Math.max(0, confidence - DECAY_RATE_PER_DAY * daysPastThreshold);
1625
+ if (decayedConfidence !== confidence) {
1626
+ await session.run(
1627
+ `MATCH (pref:Preference {preferenceId: $preferenceId, accountId: $accountId})
1628
+ SET pref.confidence = $confidence`,
1629
+ {
1630
+ preferenceId: record.get("preferenceId"),
1631
+ accountId,
1632
+ confidence: decayedConfidence
1633
+ }
1634
+ );
1635
+ decayCount++;
1636
+ }
1637
+ }
1638
+ }
1639
+ const result = await session.run(
1640
+ `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
1641
+ OPTIONAL MATCH (au:AdminUser {userId: $userId})-[:OWNS]->(p:Person {accountId: $accountId})
1642
+ OPTIONAL MATCH (up)-[:HAS_PREFERENCE]->(pref:Preference)
1643
+ WHERE pref.confidence >= $threshold OR pref.notApplicable = true
1644
+ WITH up, p, pref
1645
+ ORDER BY pref.confidence DESC
1646
+ WITH up, p, collect(pref) AS allPrefs
1647
+ WITH up, p, allPrefs[0..$limit] AS prefs
1648
+ RETURN up, p AS person, prefs`,
1649
+ { accountId, userId, threshold: INJECTION_THRESHOLD, limit: MAX_SUMMARY_PREFERENCES }
1650
+ );
1651
+ if (result.records.length === 0 || !result.records[0].get("up")) {
1652
+ return null;
1653
+ }
1654
+ const upNode = result.records[0].get("up");
1655
+ const profileProps = { ...upNode.properties };
1656
+ const personNode = result.records[0].get("person");
1657
+ if (personNode?.properties) {
1658
+ if (personNode.properties.givenName !== void 0) profileProps.givenName = personNode.properties.givenName;
1659
+ if (personNode.properties.familyName !== void 0) profileProps.familyName = personNode.properties.familyName;
1660
+ if (personNode.properties.email !== void 0) profileProps.email = personNode.properties.email;
1661
+ if (personNode.properties.telephone !== void 0) profileProps.telephone = personNode.properties.telephone;
1662
+ }
1663
+ const prefNodes = result.records[0].get("prefs");
1664
+ const preferences = prefNodes.map((p) => ({
1665
+ preferenceId: p.properties.preferenceId,
1666
+ category: p.properties.category,
1667
+ key: p.properties.key,
1668
+ value: p.properties.value,
1669
+ confidence: p.properties.confidence,
1670
+ source: p.properties.source,
1671
+ observedAt: p.properties.observedAt,
1672
+ notApplicable: p.properties.notApplicable === true
1673
+ }));
1674
+ const summary = formatProfileSummary(profileProps, preferences);
1675
+ const absentFields = computeAbsentFields(preferences);
1676
+ const fieldCoverageCount = TOTAL_PROFILE_FIELDS - absentFields.length;
1677
+ const presentCategories = new Set(
1678
+ preferences.filter((p) => p.notApplicable === true || p.confidence >= INJECTION_THRESHOLD).map((p) => p.category)
1679
+ );
1680
+ const absentCategories = PROFILE_CATEGORIES.filter((c) => !presentCategories.has(c));
1681
+ const categoryCoverage = PROFILE_CATEGORIES.length - absentCategories.length;
1682
+ console.error(
1683
+ `[profile] loaded for userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 preferences=${preferences.length} fieldCoverage=${fieldCoverageCount}/${TOTAL_PROFILE_FIELDS} categoryCoverage=${categoryCoverage}/${PROFILE_CATEGORIES.length} (decay: ${decayCount} updated)`
1684
+ );
1685
+ const identityKeys = [
1686
+ { prop: "email", token: "email" },
1687
+ // Schema-canonical name. `phone` is the synonym (rejected at tool
1688
+ // surface); the log uses `telephone` to keep grep aligned with
1689
+ // schema-base.md doctrine the brief enforces.
1690
+ { prop: "telephone", token: "telephone" },
1691
+ { prop: "givenName", token: "givenName" },
1692
+ { prop: "familyName", token: "familyName" },
1693
+ { prop: "role", token: "role" }
1694
+ ];
1695
+ const absentIdentity = identityKeys.filter((k) => {
1696
+ const v = profileProps[k.prop];
1697
+ return typeof v !== "string" || v.trim().length === 0;
1698
+ });
1699
+ const sparseFired = absentCategories.length > 0 || absentFields.length > 0 || absentIdentity.length > 0;
1700
+ if (conversationId && sparseFired) {
1701
+ const dedupeKey = `${accountId}:${userId}:${conversationId}`;
1702
+ if (!sparseStateLogged.has(dedupeKey)) {
1703
+ sparseStateLogged.add(dedupeKey);
1704
+ const FIELDS_LOG_CAP = 10;
1705
+ const absentFieldsTruncated = absentFields.length <= FIELDS_LOG_CAP ? absentFields.join(",") : `${absentFields.slice(0, FIELDS_LOG_CAP).join(",")}+${absentFields.length - FIELDS_LOG_CAP} more`;
1706
+ console.error(
1707
+ `[profile] sparse-state injected accountId=${accountId.slice(0, 8)}\u2026 userId=${userId} conversationId=${conversationId.slice(0, 8)}\u2026 absentCategories=${absentCategories.join(",")} absentFields=${absentFieldsTruncated || "none"} absentIdentity=${absentIdentity.map((k) => k.token).join(",") || "none"}`
1708
+ );
1709
+ }
1710
+ }
1711
+ return summary;
1712
+ } catch (err) {
1713
+ console.error(`[profile] loadUserProfile failed: ${err instanceof Error ? err.message : String(err)}`);
1714
+ return null;
1715
+ } finally {
1716
+ await session.close();
1717
+ }
1718
+ }
1719
+ function formatProfileSummary(profile, preferences) {
1720
+ const givenName = typeof profile.givenName === "string" ? profile.givenName.trim() : "";
1721
+ const familyName = typeof profile.familyName === "string" ? profile.familyName.trim() : "";
1722
+ const joined = familyName ? `${givenName} ${familyName}` : givenName;
1723
+ const name = joined || "Owner";
1724
+ const role = profile.role ? ` (${profile.role})` : "";
1725
+ const tz = profile.timezone ? ` \u2014 ${profile.timezone}` : "";
1726
+ const locale = profile.locale ? `, ${profile.locale}` : "";
1727
+ const expertise = profile.expertise ? `
1728
+ Expertise: ${typeof profile.expertise === "string" ? profile.expertise : JSON.stringify(profile.expertise)}` : "";
1729
+ const lines = [`## About the Owner
1730
+ `];
1731
+ lines.push(`${name}${role}${tz}${locale}${expertise}
1732
+ `);
1733
+ const categories = {};
1734
+ for (const pref of preferences) {
1735
+ if (pref.notApplicable === true) continue;
1736
+ if (!categories[pref.category]) categories[pref.category] = [];
1737
+ categories[pref.category].push(pref);
1738
+ }
1739
+ const categoryLabels = {
1740
+ communication: "Communication",
1741
+ scheduling: "Scheduling",
1742
+ decision: "Decisions",
1743
+ workflow: "Workflow",
1744
+ content: "Content",
1745
+ interaction: "Interaction patterns"
1746
+ };
1747
+ const workCategories = ["communication", "scheduling", "decision", "workflow", "content"];
1748
+ const workPrefs = workCategories.filter((c) => categories[c]);
1749
+ if (workPrefs.length > 0) {
1750
+ lines.push(`### How they work`);
1751
+ for (const cat of workPrefs) {
1752
+ const label = categoryLabels[cat] || cat;
1753
+ const items = categories[cat].map((p) => p.value).join("; ");
1754
+ lines.push(`- ${label}: ${items}`);
1755
+ }
1756
+ lines.push("");
1757
+ }
1758
+ if (categories.interaction) {
1759
+ lines.push(`### Interaction patterns`);
1760
+ for (const pref of categories.interaction) {
1761
+ lines.push(`- ${pref.value}`);
1762
+ }
1763
+ lines.push("");
1764
+ }
1765
+ const identityFields = [
1766
+ { key: "email", label: "email" },
1767
+ { key: "telephone", label: "phone" },
1768
+ { key: "givenName", label: "first name" },
1769
+ { key: "familyName", label: "last name" },
1770
+ { key: "role", label: "role" }
1771
+ ];
1772
+ const absentIdentity = identityFields.filter((f) => {
1773
+ const v = profile[f.key];
1774
+ return typeof v !== "string" || v.trim().length === 0;
1775
+ });
1776
+ if (absentIdentity.length > 0) {
1777
+ lines.push(`### Identity coverage`);
1778
+ lines.push(`Missing: ${absentIdentity.map((f) => f.label).join(", ")}`);
1779
+ lines.push("");
1780
+ }
1781
+ const absentFields = computeAbsentFields(preferences);
1782
+ if (absentFields.length > 0) {
1783
+ lines.push(`### Coverage`);
1784
+ lines.push(`Missing: ${absentFields.join(", ")}`);
1785
+ lines.push("");
1786
+ }
1787
+ return lines.join("\n");
1788
+ }
1789
+ var MAX_SESSION_TASKS = 20;
1790
+ var MAX_SESSION_PROJECTS = 5;
1791
+ var MAX_RECENT_TOOL_FAILURES = 3;
1792
+ var RECENT_FAILURES_TAIL_BYTES = 10 * 1024;
1793
+ function readRecentToolFailures(accountId, sessionKey) {
1794
+ try {
1795
+ const platformRoot = process.env.MAXY_PLATFORM_ROOT ?? resolve(process.cwd(), "..");
1796
+ const logDir = resolve(platformRoot, "..", "data/accounts", accountId, "logs");
1797
+ const logPath = resolve(logDir, `claude-agent-stream-${sessionKey}.log`);
1798
+ if (!existsSync(logPath)) {
1799
+ console.error(`[review-tail-skip] path=${logPath} reason=file-missing \u2014 first turn of conversation, subprocess not yet spawned, or log rotated`);
1800
+ return [];
1801
+ }
1802
+ const st = statSync(logPath);
1803
+ const size = st.size;
1804
+ const readBytes = Math.min(size, RECENT_FAILURES_TAIL_BYTES);
1805
+ const position = size - readBytes;
1806
+ const fd = openSync(logPath, "r");
1807
+ try {
1808
+ const buf = Buffer.alloc(readBytes);
1809
+ readSync(fd, buf, 0, readBytes, position);
1810
+ const text = buf.toString("utf-8");
1811
+ const lines = text.split("\n");
1812
+ const matches = [];
1813
+ for (let i = lines.length - 1; i >= 0 && matches.length < MAX_RECENT_TOOL_FAILURES; i--) {
1814
+ const line = lines[i];
1815
+ if (line.includes("[tool-failure-diag]")) {
1816
+ matches.push(line);
1817
+ }
1818
+ }
1819
+ return matches.reverse();
1820
+ } finally {
1821
+ closeSync(fd);
1822
+ }
1823
+ } catch (err) {
1824
+ console.error(
1825
+ `[session-context] recent-tool-failures read failed: ${err instanceof Error ? err.message : String(err)}`
1826
+ );
1827
+ return [];
1828
+ }
1829
+ }
1830
+ async function loadSessionContext(accountId, conversationId, sessionKey) {
1831
+ const session = getSession();
1832
+ try {
1833
+ const digestResult = await session.run(
1834
+ `MATCH (d:CreativeWork {accountId: $accountId})
1835
+ WHERE d.title STARTS WITH 'Chat Review'
1836
+ RETURN d.title AS title, d.createdAt AS createdAt, d.abstract AS abstract
1837
+ ORDER BY d.createdAt DESC LIMIT 1`,
1838
+ { accountId }
1839
+ );
1840
+ const tasksResult = await session.run(
1841
+ `MATCH (t:Task {accountId: $accountId})
1842
+ WHERE t.status IN ['pending', 'active']
1843
+ RETURN t.taskId AS taskId, t.name AS name, t.status AS status,
1844
+ t.priority AS priority, t.dueDate AS dueDate
1845
+ ORDER BY
1846
+ CASE t.priority
1847
+ WHEN 'urgent' THEN 0
1848
+ WHEN 'high' THEN 1
1849
+ WHEN 'normal' THEN 2
1850
+ WHEN 'low' THEN 3
1851
+ ELSE 4
1852
+ END,
1853
+ t.createdAt DESC
1854
+ LIMIT $limit`,
1855
+ { accountId, limit: neo4j.int(MAX_SESSION_TASKS) }
1856
+ );
1857
+ let projectsCount = 0;
1858
+ let projectLines = [];
1859
+ try {
1860
+ const projectsResult = await session.run(
1861
+ `MATCH (p:Project:Task {accountId: $accountId})
1862
+ WHERE p.status IN ['pending', 'active']
1863
+ OPTIONAL MATCH (p)-[:HAS_TASK]->(child:Task)
1864
+ WITH p,
1865
+ count(child) AS totalTasks,
1866
+ count(CASE WHEN child.status = 'completed' THEN 1 END) AS completedTasks,
1867
+ count(CASE WHEN child.dueDate IS NOT NULL
1868
+ AND date(child.dueDate) < date()
1869
+ AND child.status <> 'completed' THEN 1 END) AS overdueTasks,
1870
+ count(CASE WHEN child.status IN ['pending', 'active'] AND EXISTS {
1871
+ MATCH (blocker:Task)-[:BLOCKS]->(child)
1872
+ WHERE blocker.status IN ['pending', 'active']
1873
+ } THEN 1 END) AS blockedTasks
1874
+ RETURN p.name AS name, p.phase AS phase, p.tier AS tier,
1875
+ p.clientRef AS clientRef, p.status AS status,
1876
+ totalTasks, completedTasks, overdueTasks, blockedTasks
1877
+ ORDER BY p.updatedAt DESC
1878
+ LIMIT $limit`,
1879
+ { accountId, limit: neo4j.int(MAX_SESSION_PROJECTS) }
1880
+ );
1881
+ projectsCount = projectsResult.records.length;
1882
+ if (projectsCount > 0) {
1883
+ projectLines = projectsResult.records.map((r) => {
1884
+ const name = r.get("name") || "Unnamed project";
1885
+ const phase = r.get("phase") || "planning";
1886
+ const tier = r.get("tier") || "standard";
1887
+ const clientRef = r.get("clientRef");
1888
+ const total = typeof r.get("totalTasks") === "number" ? r.get("totalTasks") : r.get("totalTasks")?.toNumber?.() ?? 0;
1889
+ const completed = typeof r.get("completedTasks") === "number" ? r.get("completedTasks") : r.get("completedTasks")?.toNumber?.() ?? 0;
1890
+ const overdue = typeof r.get("overdueTasks") === "number" ? r.get("overdueTasks") : r.get("overdueTasks")?.toNumber?.() ?? 0;
1891
+ const blocked = typeof r.get("blockedTasks") === "number" ? r.get("blockedTasks") : r.get("blockedTasks")?.toNumber?.() ?? 0;
1892
+ let signal;
1893
+ const hasDueDates = overdue > 0 || total > 0;
1894
+ if (!hasDueDates && total === 0) {
1895
+ signal = "grey";
1896
+ } else if (overdue > 1 || blocked > 1) {
1897
+ signal = "red";
1898
+ } else if (overdue > 0 || blocked > 0) {
1899
+ signal = "amber";
1900
+ } else {
1901
+ signal = "green";
1902
+ }
1903
+ const client = clientRef ? ` (${clientRef})` : "";
1904
+ const health = signal !== "grey" ? ` [${signal.toUpperCase()}]` : "";
1905
+ return `- **${name}**${client} \u2014 ${tier}, ${phase}${health}, ${completed}/${total} done${overdue > 0 ? `, ${overdue} overdue` : ""}${blocked > 0 ? `, ${blocked} blocked` : ""}`;
1906
+ });
1907
+ }
1908
+ } catch (projectErr) {
1909
+ console.error(
1910
+ `[session-context] project query failed: ${projectErr instanceof Error ? projectErr.message : String(projectErr)}`
1911
+ );
1912
+ }
1913
+ const sections = [];
1914
+ if (digestResult.records.length > 0) {
1915
+ const rec = digestResult.records[0];
1916
+ const createdAt = rec.get("createdAt");
1917
+ const abstract = rec.get("abstract");
1918
+ if (abstract) {
1919
+ const dateSuffix = createdAt ? ` (${createdAt.slice(0, 10)})` : "";
1920
+ sections.push(`## Recent Public Chat Digest${dateSuffix}
1921
+ ${abstract}`);
1922
+ }
1923
+ }
1924
+ if (tasksResult.records.length > 0) {
1925
+ const taskLines = tasksResult.records.map((r) => {
1926
+ const priority = (r.get("priority") || "normal").toUpperCase();
1927
+ const status = r.get("status");
1928
+ const name = r.get("name");
1929
+ const dueDate = r.get("dueDate");
1930
+ const due = dueDate ? ` due:${dueDate.slice(0, 10)}` : "";
1931
+ const taskId = r.get("taskId");
1932
+ return `- [${priority}] ${status} \u2014 ${name}${due} (${taskId})`;
1933
+ });
1934
+ sections.push(`## Open Tasks (${tasksResult.records.length})
1935
+ ${taskLines.join("\n")}`);
1936
+ }
1937
+ let pendingCount = 0;
1938
+ let pendingLines = [];
1939
+ try {
1940
+ const platformRoot = process.env.MAXY_PLATFORM_ROOT ?? resolve(process.cwd(), "..");
1941
+ const pendingDir = resolve(platformRoot, "..", "data/accounts", accountId, "pending-actions");
1942
+ if (existsSync(pendingDir)) {
1943
+ const files = readdirSync(pendingDir).filter((f) => f.endsWith(".json") && !f.startsWith("."));
1944
+ for (const file of files) {
1945
+ try {
1946
+ const raw = readFileSync(resolve(pendingDir, file), "utf-8");
1947
+ const action = JSON.parse(raw);
1948
+ if (action.state === "pending") {
1949
+ const inputSummary = JSON.stringify(action.hookPayload?.tool_input ?? {}).slice(0, 150);
1950
+ pendingLines.push(`- **${action.toolName}** (${action.actionId.slice(0, 8)}\u2026) queued ${action.createdAt?.slice(0, 16) ?? "unknown"}
1951
+ Input: ${inputSummary}`);
1952
+ pendingCount++;
1953
+ }
1954
+ } catch {
1955
+ }
1956
+ }
1957
+ }
1958
+ } catch (pendingErr) {
1959
+ console.error(
1960
+ `[session-context] pending actions read failed: ${pendingErr instanceof Error ? pendingErr.message : String(pendingErr)}`
1961
+ );
1962
+ }
1963
+ if (pendingCount > 0) {
1964
+ sections.push(`## Pending Actions (${pendingCount})
1965
+ Actions queued for your approval. Use action-approve, action-reject, or action-edit.
1966
+ ${pendingLines.join("\n")}`);
1967
+ }
1968
+ if (projectLines.length > 0) {
1969
+ sections.push(`## Active Projects (${projectLines.length})
1970
+ ${projectLines.join("\n")}`);
1971
+ }
1972
+ let recentFailuresCount = 0;
1973
+ if (sessionKey) {
1974
+ const failureLines = readRecentToolFailures(accountId, sessionKey);
1975
+ if (failureLines.length > 0) {
1976
+ recentFailuresCount = failureLines.length;
1977
+ const guidance = "These tool calls failed in the current conversation. Inspect the diagnostic fields before retrying the same tool against the same target \u2014 if you do retry, narrate explicitly why the diagnostic suggests a retry will now succeed. A second identical failure is evidence the path is broken, not evidence another attempt is warranted.";
1978
+ sections.push(`## Recent Tool Failures (${failureLines.length})
1979
+ ${guidance}
1980
+
1981
+ ${failureLines.map((l) => `- ${l.trim()}`).join("\n")}`);
1982
+ }
1983
+ }
1984
+ if (sections.length === 0) return null;
1985
+ console.error(
1986
+ `[session-context] Loaded for ${accountId.slice(0, 8)}\u2026: digest=${digestResult.records.length > 0 ? "yes" : "no"}, tasks=${tasksResult.records.length}, projects=${projectsCount}, pendingActions=${pendingCount}, recentFailures=${recentFailuresCount}`
1987
+ );
1988
+ return `<previous-context>
1989
+ ${sections.join("\n\n")}
1990
+ </previous-context>`;
1991
+ } catch (err) {
1992
+ console.error(`[session-context] loadSessionContext failed: ${err instanceof Error ? err.message : String(err)}`);
1993
+ return null;
1994
+ } finally {
1995
+ await session.close();
1996
+ }
1997
+ }
1998
+ async function consumeStep7FlagUI(session, accountId) {
1999
+ const accountDir = resolve(PLATFORM_ROOT, "..", "data/accounts", accountId);
2000
+ const flagPath = resolve(accountDir, "onboarding", "step7-complete");
2001
+ if (!existsSync(flagPath)) return false;
2002
+ let completedAt = (/* @__PURE__ */ new Date()).toISOString();
2003
+ try {
2004
+ const raw = readFileSync(flagPath, "utf-8").trim();
2005
+ if (raw) {
2006
+ const parsed = JSON.parse(raw);
2007
+ if (typeof parsed.completedAt === "string") {
2008
+ completedAt = parsed.completedAt;
2009
+ }
2010
+ }
2011
+ } catch {
2012
+ }
2013
+ const result = await session.run(
2014
+ `MATCH (o:OnboardingState {accountId: $accountId})
2015
+ SET o.step7CompletedAt = CASE WHEN o.step7CompletedAt IS NULL THEN $completedAt ELSE o.step7CompletedAt END,
2016
+ o.currentStep = CASE WHEN 7 > o.currentStep THEN 7 ELSE o.currentStep END,
2017
+ o.updatedAt = $completedAt
2018
+ RETURN count(o) AS updated`,
2019
+ { accountId, completedAt }
2020
+ );
2021
+ const updatedRaw = result.records[0]?.get("updated");
2022
+ const updated = typeof updatedRaw === "number" ? updatedRaw : updatedRaw && typeof updatedRaw === "object" && "toNumber" in updatedRaw ? updatedRaw.toNumber() : 0;
2023
+ if (updated === 0) {
2024
+ console.log(
2025
+ `[onboarding-flag-consumed] accountId=${accountId.slice(0, 8)}\u2026 step=7 source=filesystem flagPath=${flagPath} skipped=no-node`
2026
+ );
2027
+ return false;
2028
+ }
2029
+ console.log(
2030
+ `[onboarding-flag-consumed] accountId=${accountId.slice(0, 8)}\u2026 step=7 source=filesystem flagPath=${flagPath} completedAt=${completedAt}`
2031
+ );
2032
+ try {
2033
+ rmSync(flagPath);
2034
+ } catch (err) {
2035
+ console.error(
2036
+ `[onboarding-flag-consumed] warn: failed to delete ${flagPath}: ${err instanceof Error ? err.message : String(err)}`
2037
+ );
2038
+ }
2039
+ return true;
2040
+ }
2041
+ async function loadOnboardingStep(accountId) {
2042
+ const session = getSession();
2043
+ try {
2044
+ await consumeStep7FlagUI(session, accountId);
2045
+ const result = await session.run(
2046
+ `MATCH (o:OnboardingState {accountId: $accountId})
2047
+ RETURN o.currentStep AS currentStep`,
2048
+ { accountId }
2049
+ );
2050
+ if (result.records.length === 0) {
2051
+ return -1;
2052
+ }
2053
+ const raw = result.records[0].get("currentStep");
2054
+ if (typeof raw === "number") return raw;
2055
+ if (raw && typeof raw === "object" && "toNumber" in raw) {
2056
+ return raw.toNumber();
2057
+ }
2058
+ return 0;
2059
+ } catch (err) {
2060
+ console.error(`[onboarding-inject] loadOnboardingStep failed: ${err instanceof Error ? err.message : String(err)}`);
2061
+ return null;
2062
+ } finally {
2063
+ await session.close();
2064
+ }
2065
+ }
2066
+ var AGENT_FILE_ROLES = [
2067
+ { filename: "IDENTITY.md", role: "identity" },
2068
+ { filename: "SOUL.md", role: "soul" },
2069
+ { filename: "KNOWLEDGE.md", role: "knowledge" },
2070
+ { filename: "KNOWLEDGE-SUMMARY.md", role: "knowledge-summary" }
2071
+ ];
2072
+ var ROLE_TO_EDGE = {
2073
+ identity: "HAS_IDENTITY",
2074
+ soul: "HAS_SOUL",
2075
+ knowledge: "HAS_KNOWLEDGE",
2076
+ "knowledge-summary": "HAS_KNOWLEDGE"
2077
+ };
2078
+ function assertSafeAgentSlug(slug) {
2079
+ if (!slug || slug.includes("/") || slug.includes("\\") || slug.includes("..")) {
2080
+ throw new Error(`[agent-graph] refusing unsafe slug=${JSON.stringify(slug)}`);
2081
+ }
2082
+ }
2083
+ function agentAttachmentId(accountId, slug, role) {
2084
+ return `agent:${accountId}:${slug}:${role}`;
2085
+ }
2086
+ async function projectAgent(accountId, accountDir, slug) {
2087
+ const start = Date.now();
2088
+ const account8 = accountId.slice(0, 8);
2089
+ try {
2090
+ assertSafeAgentSlug(slug);
2091
+ } catch (err) {
2092
+ const msg = err instanceof Error ? err.message : String(err);
2093
+ console.error(
2094
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
2095
+ );
2096
+ return;
2097
+ }
2098
+ const agentDir = resolve(accountDir, "agents", slug);
2099
+ const configPath = resolve(agentDir, "config.json");
2100
+ let config;
2101
+ let presentRoles = [];
2102
+ try {
2103
+ if (!existsSync(configPath)) {
2104
+ console.error(
2105
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="config.json missing at ${configPath}"`
2106
+ );
2107
+ return;
2108
+ }
2109
+ config = JSON.parse(readFileSync(configPath, "utf-8"));
2110
+ for (const { filename, role } of AGENT_FILE_ROLES) {
2111
+ const filePath = resolve(agentDir, filename);
2112
+ if (!existsSync(filePath)) continue;
2113
+ const body = readFileSync(filePath, "utf-8");
2114
+ presentRoles.push({ role, body, edge: ROLE_TO_EDGE[role] });
2115
+ }
2116
+ } catch (err) {
2117
+ const msg = err instanceof Error ? err.message : String(err);
2118
+ console.error(
2119
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
2120
+ );
2121
+ return;
2122
+ }
2123
+ const session = getSession();
2124
+ try {
2125
+ await session.run(
2126
+ `MERGE (a:Agent {accountId: $accountId, slug: $slug})
2127
+ ON CREATE SET a.createdAt = datetime()
2128
+ SET a.displayName = $displayName,
2129
+ a.status = $status,
2130
+ a.model = $model,
2131
+ a.liveMemory = $liveMemory,
2132
+ a.knowledgeKeywords = $knowledgeKeywords,
2133
+ a.role = 'agent',
2134
+ a.updatedAt = datetime()
2135
+ RETURN a.slug AS slug`,
2136
+ {
2137
+ accountId,
2138
+ slug,
2139
+ displayName: config.displayName ?? slug,
2140
+ status: config.status ?? "unknown",
2141
+ model: config.model ?? "",
2142
+ liveMemory: config.liveMemory ?? false,
2143
+ knowledgeKeywords: config.knowledgeKeywords ?? []
2144
+ }
2145
+ );
2146
+ for (const { role, body, edge } of presentRoles) {
2147
+ const attachmentId = agentAttachmentId(accountId, slug, role);
2148
+ await session.run(
2149
+ `MATCH (a:Agent {accountId: $accountId, slug: $slug})
2150
+ MERGE (k:KnowledgeDocument {attachmentId: $attachmentId})
2151
+ ON CREATE SET k.createdAt = datetime()
2152
+ SET k.accountId = $accountId,
2153
+ k.role = $role,
2154
+ k.name = $name,
2155
+ k.text = $text,
2156
+ k.scope = 'admin',
2157
+ k.updatedAt = datetime()
2158
+ MERGE (a)-[:${edge}]->(k)
2159
+ RETURN k.attachmentId AS attachmentId`,
2160
+ {
2161
+ accountId,
2162
+ slug,
2163
+ attachmentId,
2164
+ role,
2165
+ name: `${slug} ${role}`,
2166
+ text: body
2167
+ }
2168
+ );
2169
+ }
2170
+ const usesResult = await session.run(
2171
+ `MATCH (a:Agent {accountId: $accountId, slug: $slug})
2172
+ MATCH (k:KnowledgeDocument {accountId: $accountId})
2173
+ WHERE $slug IN coalesce(k.agents, [])
2174
+ AND NOT k.attachmentId STARTS WITH $namespacePrefix
2175
+ MERGE (a)-[:USES_KNOWLEDGE]->(k)
2176
+ RETURN count(k) AS uses`,
2177
+ {
2178
+ accountId,
2179
+ slug,
2180
+ namespacePrefix: `agent:${accountId}:${slug}:`
2181
+ }
2182
+ );
2183
+ const uses = usesResult.records[0]?.get("uses");
2184
+ const usesCount = typeof uses === "number" ? uses : uses && typeof uses.toNumber === "function" ? uses.toNumber() : 0;
2185
+ const ms = Date.now() - start;
2186
+ console.error(
2187
+ `[agent-graph] project slug=${slug} account=${account8} docs=${presentRoles.length} uses=${usesCount} ms=${ms}`
2188
+ );
2189
+ } catch (err) {
2190
+ const msg = err instanceof Error ? err.message : String(err);
2191
+ console.error(
2192
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
2193
+ );
2194
+ throw err;
2195
+ } finally {
2196
+ await session.close();
2197
+ }
2198
+ }
2199
+ async function deleteAgentProjection(accountId, slug) {
2200
+ const start = Date.now();
2201
+ const account8 = accountId.slice(0, 8);
2202
+ assertSafeAgentSlug(slug);
2203
+ const session = getSession();
2204
+ try {
2205
+ await session.run(
2206
+ `MATCH (a:Agent {accountId: $accountId, slug: $slug})
2207
+ DETACH DELETE a
2208
+ WITH 1 AS _
2209
+ UNWIND $attachmentIds AS aid
2210
+ OPTIONAL MATCH (k:KnowledgeDocument {accountId: $accountId, attachmentId: aid})
2211
+ WHERE k.attachmentId STARTS WITH $namespacePrefix
2212
+ DETACH DELETE k`,
2213
+ {
2214
+ accountId,
2215
+ slug,
2216
+ namespacePrefix: `agent:${accountId}:${slug}:`,
2217
+ attachmentIds: ["identity", "soul", "knowledge", "knowledge-summary"].map((role) => agentAttachmentId(accountId, slug, role))
2218
+ }
2219
+ );
2220
+ const ms = Date.now() - start;
2221
+ console.error(
2222
+ `[agent-graph] delete slug=${slug} account=${account8} ms=${ms}`
2223
+ );
2224
+ } catch (err) {
2225
+ const msg = err instanceof Error ? err.message : String(err);
2226
+ console.error(
2227
+ `[agent-graph] delete FAILED slug=${slug} account=${account8} error="${msg}"`
2228
+ );
2229
+ throw err;
2230
+ } finally {
2231
+ await session.close();
2232
+ }
2233
+ }
2234
+
2235
+ export {
2236
+ HAIKU_MODEL,
2237
+ contextWindow,
2238
+ getSession,
2239
+ runAdminUserSelfHeal,
2240
+ embed,
2241
+ setSessionStoreRef,
2242
+ GREETING_DIRECTIVE,
2243
+ ensureConversation,
2244
+ findRecentConversation,
2245
+ readIntentGateState,
2246
+ findGroupBySlug,
2247
+ getGroupParticipants,
2248
+ checkGroupMembership,
2249
+ bindVisitorToGroup,
2250
+ getMessagesSince,
2251
+ getGroupMessagesForContext,
2252
+ backfillConversationChannelAddress,
2253
+ backfillNullUserIdConversations,
2254
+ createNewAdminConversation,
2255
+ fetchBranding,
2256
+ persistToolCall,
2257
+ persistMessage,
2258
+ setConversationAgentSessionId,
2259
+ writeTurnFailure,
2260
+ getAgentSessionIdForConversation,
2261
+ getMostRecentAdminConversationForUser,
2262
+ getRecentMessages,
2263
+ markComponentSubmitted,
2264
+ verifyConversationOwnership,
2265
+ getConversationOwner,
2266
+ verifyAndGetConversationUpdatedAt,
2267
+ searchMessages,
2268
+ listAdminSessions,
2269
+ deleteConversation,
2270
+ isMessageUseful,
2271
+ generateSessionLabel,
2272
+ autoLabelSession,
2273
+ renameConversation,
2274
+ getUserTimezone,
2275
+ loadAdminUserName,
2276
+ writeAdminUserAndPerson,
2277
+ loadUserProfile,
2278
+ loadSessionContext,
2279
+ loadOnboardingStep,
2280
+ projectAgent,
2281
+ deleteAgentProjection
2282
+ };