@rubytech/create-realagent 1.0.838 → 1.0.840

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