@rubytech/create-realagent 1.0.816 → 1.0.818

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