@rubytech/create-realagent 1.0.829 → 1.0.830

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