@gethmy/mcp 2.3.1 → 2.3.3

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 (34) hide show
  1. package/dist/lib/api-client.js +2099 -648
  2. package/dist/lib/config.js +217 -201
  3. package/package.json +9 -5
  4. package/src/memory-cleanup.ts +2 -4
  5. package/dist/lib/__tests__/active-learning.test.js +0 -386
  6. package/dist/lib/__tests__/agent-performance-profiles.test.js +0 -325
  7. package/dist/lib/__tests__/auto-session.test.js +0 -661
  8. package/dist/lib/__tests__/context-assembly.test.js +0 -362
  9. package/dist/lib/__tests__/graph-expansion.test.js +0 -150
  10. package/dist/lib/__tests__/integration-memory-crud.test.js +0 -797
  11. package/dist/lib/__tests__/integration-memory-system.test.js +0 -281
  12. package/dist/lib/__tests__/lifecycle-maintenance.test.js +0 -207
  13. package/dist/lib/__tests__/pattern-detection.test.js +0 -295
  14. package/dist/lib/__tests__/prompt-builder.test.js +0 -418
  15. package/dist/lib/active-learning.js +0 -822
  16. package/dist/lib/auto-session.js +0 -214
  17. package/dist/lib/cli.js +0 -138
  18. package/dist/lib/consolidation.js +0 -303
  19. package/dist/lib/context-assembly.js +0 -884
  20. package/dist/lib/graph-expansion.js +0 -163
  21. package/dist/lib/http.js +0 -175
  22. package/dist/lib/index.js +0 -7
  23. package/dist/lib/lifecycle-maintenance.js +0 -88
  24. package/dist/lib/memory-cleanup.js +0 -455
  25. package/dist/lib/onboard.js +0 -36
  26. package/dist/lib/prompt-builder.js +0 -488
  27. package/dist/lib/remote.js +0 -166
  28. package/dist/lib/server.js +0 -3365
  29. package/dist/lib/skills.js +0 -593
  30. package/dist/lib/tui/agents.js +0 -116
  31. package/dist/lib/tui/docs.js +0 -744
  32. package/dist/lib/tui/setup.js +0 -934
  33. package/dist/lib/tui/theme.js +0 -95
  34. package/dist/lib/tui/writer.js +0 -200
@@ -1,822 +0,0 @@
1
- /**
2
- * Active Learning Loop
3
- *
4
- * Auto-extracts memories from agent work sessions.
5
- * Triggered on harmony_end_agent_session and harmony_update_agent_progress.
6
- */
7
- import { getActiveProjectId, getActiveWorkspaceId } from "./config.js";
8
- import { autoExpandGraph, findSimilarEntities, linkCrossTypeNeighbors, } from "./graph-expansion.js";
9
- // Entity types that can participate in `contradicts` relations (per schema.ts)
10
- const CONTRADICTION_TYPES = new Set([
11
- "decision",
12
- "pattern",
13
- "preference",
14
- "lesson",
15
- ]);
16
- // --- Mid-Session Learning ---
17
- /** Track previous task per session for change detection */
18
- const sessionTaskHistory = new Map();
19
- /** Rate limit: max 1 extraction per 2 minutes per session */
20
- const MID_SESSION_RATE_LIMIT_MS = 120_000;
21
- /**
22
- * Simple Levenshtein similarity (0-1 range, 1 = identical).
23
- */
24
- function levenshteinSimilarity(a, b) {
25
- if (a === b)
26
- return 1;
27
- if (a.length === 0 || b.length === 0)
28
- return 0;
29
- // Use shorter strings for performance (truncate to 200 chars)
30
- const sa = a.slice(0, 200).toLowerCase();
31
- const sb = b.slice(0, 200).toLowerCase();
32
- const matrix = [];
33
- for (let i = 0; i <= sa.length; i++) {
34
- matrix[i] = [i];
35
- }
36
- for (let j = 0; j <= sb.length; j++) {
37
- matrix[0][j] = j;
38
- }
39
- for (let i = 1; i <= sa.length; i++) {
40
- for (let j = 1; j <= sb.length; j++) {
41
- const cost = sa[i - 1] === sb[j - 1] ? 0 : 1;
42
- matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost);
43
- }
44
- }
45
- const maxLen = Math.max(sa.length, sb.length);
46
- return 1 - matrix[sa.length][sb.length] / maxLen;
47
- }
48
- /**
49
- * Extract learnings from mid-session progress updates.
50
- * Called from harmony_update_agent_progress.
51
- */
52
- export async function extractMidSessionLearnings(_client, ctx) {
53
- const workspaceId = getActiveWorkspaceId();
54
- if (!workspaceId)
55
- return { count: 0, entityIds: [] };
56
- const _projectId = getActiveProjectId() || undefined;
57
- const now = Date.now();
58
- const _entityIds = [];
59
- const history = sessionTaskHistory.get(ctx.cardId);
60
- // Always track step history regardless of rate limit
61
- if (ctx.currentTask) {
62
- const previousTask = history?.lastTask || "";
63
- const similarity = levenshteinSimilarity(previousTask, ctx.currentTask);
64
- const existingSteps = history?.steps || [];
65
- if (existingSteps.length === 0 ||
66
- (similarity < 0.6 && previousTask.length > 0)) {
67
- const newStep = {
68
- task: ctx.currentTask,
69
- progress: ctx.progressPercent ?? 0,
70
- timestamp: now,
71
- };
72
- if (existingSteps.length === 0 && previousTask.length > 0) {
73
- existingSteps.push({
74
- task: previousTask,
75
- progress: 0,
76
- timestamp: history?.lastExtractionAt ?? now,
77
- });
78
- }
79
- existingSteps.push(newStep);
80
- sessionTaskHistory.set(ctx.cardId, {
81
- lastTask: ctx.currentTask,
82
- lastExtractionAt: history?.lastExtractionAt ?? 0,
83
- steps: existingSteps,
84
- });
85
- }
86
- }
87
- // Rate limit check (only gates memory entity creation, not step tracking)
88
- if (history && now - history.lastExtractionAt < MID_SESSION_RATE_LIMIT_MS) {
89
- // Still within rate limit, but always extract blockers immediately
90
- if (ctx.status !== "blocked" || !ctx.blockers?.length) {
91
- return { count: 0, entityIds: [] };
92
- }
93
- }
94
- // Rule 1: Status transitions to "blocked" → track but DON'T create mid-session entities.
95
- // Blockers are captured at session end with full context — mid-session entities are
96
- // low-confidence duplicates that add noise to the knowledge graph.
97
- if (ctx.status === "blocked" && ctx.blockers?.length) {
98
- sessionTaskHistory.set(ctx.cardId, {
99
- lastTask: ctx.currentTask || "",
100
- lastExtractionAt: now,
101
- steps: history?.steps || [],
102
- });
103
- return { count: 0, entityIds: [] };
104
- }
105
- // Rule 2: Task transitions are tracked in step history (above) but no longer
106
- // create separate context entities. The step history feeds procedure extraction
107
- // at session end, which is more valuable than individual transition snapshots.
108
- if (ctx.currentTask) {
109
- const currentHistory = sessionTaskHistory.get(ctx.cardId);
110
- sessionTaskHistory.set(ctx.cardId, {
111
- lastTask: ctx.currentTask,
112
- lastExtractionAt: currentHistory?.lastExtractionAt ?? 0,
113
- steps: currentHistory?.steps || [],
114
- });
115
- }
116
- return { count: 0, entityIds: [] };
117
- }
118
- /**
119
- * Clean up mid-session tracking for a card (call on session end).
120
- */
121
- export function clearMidSessionTracking(cardId) {
122
- sessionTaskHistory.delete(cardId);
123
- }
124
- /**
125
- * Enrich raw steps with progress deltas and key decision detection.
126
- * A step is a "key decision" if it represents a >20% progress jump.
127
- */
128
- function enrichSteps(steps) {
129
- return steps.map((step, i) => {
130
- const prevProgress = i > 0 ? steps[i - 1].progress : 0;
131
- const prevTimestamp = i > 0 ? steps[i - 1].timestamp : step.timestamp;
132
- const progressDelta = step.progress - prevProgress;
133
- return {
134
- task: step.task,
135
- progress: step.progress,
136
- progressDelta,
137
- durationMs: step.timestamp - prevTimestamp,
138
- isKeyDecision: progressDelta >= 20,
139
- };
140
- });
141
- }
142
- /**
143
- * Build structured procedure content from session data and enriched steps.
144
- */
145
- function buildProcedureContent(session, enrichedSteps, wikiLinksLine) {
146
- const triggerLabels = session.cardLabels.length > 0
147
- ? `Labels: ${session.cardLabels.join(", ")}`
148
- : "";
149
- const stepsMarkdown = enrichedSteps
150
- .map((s, i) => {
151
- const marker = s.isKeyDecision ? " **[key step]**" : "";
152
- const duration = s.durationMs > 0 ? ` (~${Math.round(s.durationMs / 60000)}min)` : "";
153
- return `${i + 1}. ${s.task} (${s.progress}%, +${s.progressDelta}%)${marker}${duration}`;
154
- })
155
- .join("\n");
156
- const subtaskSection = session.cardSubtasks && session.cardSubtasks.length > 0
157
- ? [
158
- "",
159
- "## Subtasks Completed",
160
- ...session.cardSubtasks.map((s) => `- [${s.done ? "x" : " "}] ${s.title}`),
161
- ].join("\n")
162
- : "";
163
- const durationInfo = session.sessionDurationMs
164
- ? `\nDuration: ${Math.round(session.sessionDurationMs / 60000)} minutes`
165
- : "";
166
- return [
167
- "## Trigger",
168
- `When working on: "${session.cardTitle}"`,
169
- triggerLabels,
170
- "",
171
- "## Steps",
172
- stepsMarkdown,
173
- subtaskSection,
174
- "",
175
- "## Outcome",
176
- `Completed at ${session.progressPercent ?? "unknown"}%`,
177
- session.currentTask ? `Final state: ${session.currentTask}` : "",
178
- `Agent: ${session.agentName}`,
179
- durationInfo,
180
- wikiLinksLine,
181
- ]
182
- .filter((line) => line !== undefined)
183
- .join("\n");
184
- }
185
- /**
186
- * Extract a new procedure or reinforce an existing similar one.
187
- *
188
- * Deduplication: searches for existing procedure entities with similar titles.
189
- * If found, merges new steps and bumps confidence. Otherwise creates a new one.
190
- */
191
- async function extractOrReinforceProcedure(client, session, steps, workspaceId, projectId, wikiLinksLine = "") {
192
- const enrichedSteps = enrichSteps(steps);
193
- const newContent = buildProcedureContent(session, enrichedSteps, wikiLinksLine);
194
- const tags = [
195
- "auto-extracted",
196
- "procedure",
197
- ...session.cardLabels.slice(0, 3),
198
- ];
199
- // Try to find an existing similar procedure to reinforce
200
- try {
201
- const similar = await findSimilarEntities(client, `Procedure: ${session.cardTitle}`, newContent, workspaceId, { projectId, limit: 5, minRrfScore: 0.03 });
202
- const matchingProcedure = similar.find((e) => e.type === "procedure" && (e.rrf_score ?? 0) >= 0.05);
203
- if (matchingProcedure) {
204
- // Fetch the full entity to get metadata and memory_tier
205
- const { entity: rawEntity } = await client.getMemoryEntity(matchingProcedure.id);
206
- const fullEntity = rawEntity;
207
- const currentMeta = fullEntity.metadata || {};
208
- const sourceCards = (currentMeta.source_cards || []).slice();
209
- if (!sourceCards.includes(session.cardId)) {
210
- sourceCards.push(session.cardId);
211
- }
212
- const reuseCount = (currentMeta.reuse_count || 0) + 1;
213
- const currentConfidence = fullEntity.confidence ?? 0.7;
214
- // Bump confidence by 0.05 per reinforcement, max 0.95
215
- const newConfidence = Math.min(0.95, currentConfidence + 0.05);
216
- // Append new steps as an additional execution record
217
- const stepsAppendix = enrichedSteps
218
- .map((s, i) => `${i + 1}. ${s.task} (${s.progress}%)`)
219
- .join("\n");
220
- const appendix = `\n\n---\n### Execution ${reuseCount + 1}: ${session.cardTitle}\n${stepsAppendix}\nAgent: ${session.agentName} | ${new Date().toISOString().split("T")[0]}`;
221
- const updatedMeta = {
222
- ...currentMeta,
223
- reuse_count: reuseCount,
224
- source_cards: sourceCards,
225
- last_reinforced_at: new Date().toISOString(),
226
- step_count: Math.max(currentMeta.step_count || 0, steps.length),
227
- };
228
- // Auto-promote to reference tier if reinforced enough (≥3 executions)
229
- const shouldPromote = reuseCount >= 2 && fullEntity.memory_tier !== "reference";
230
- await client.updateMemoryEntity(fullEntity.id, {
231
- content: (fullEntity.content || "") + appendix,
232
- confidence: newConfidence,
233
- metadata: {
234
- ...updatedMeta,
235
- ...(shouldPromote
236
- ? {
237
- promoted_reason: `Reinforced by ${reuseCount + 1} successful sessions`,
238
- promoted_at: new Date().toISOString(),
239
- }
240
- : {}),
241
- },
242
- ...(shouldPromote ? { memory_tier: "reference" } : {}),
243
- });
244
- return { mode: "reinforced", entityId: fullEntity.id };
245
- }
246
- }
247
- catch {
248
- // Similarity search failed, fall through to create new
249
- }
250
- // No existing procedure found — create a new one
251
- return {
252
- mode: "created",
253
- learning: {
254
- title: `Procedure: ${session.cardTitle}`,
255
- content: newContent,
256
- type: "procedure",
257
- tier: "episode",
258
- confidence: 0.7,
259
- tags,
260
- metadata: {
261
- source: "active_learning",
262
- card_id: session.cardId,
263
- source_cards: [session.cardId],
264
- step_count: steps.length,
265
- key_step_count: enrichedSteps.filter((s) => s.isKeyDecision).length,
266
- reuse_count: 0,
267
- },
268
- },
269
- };
270
- }
271
- // --- Same-Session Causal Linking ---
272
- /** Causal pairing rules for entities created within the same session */
273
- const SESSION_CAUSAL_RULES = [
274
- {
275
- sourceType: "error",
276
- targetType: "solution",
277
- relation: "resolved_by",
278
- confidence: 0.8,
279
- },
280
- {
281
- sourceType: "lesson",
282
- targetType: "error",
283
- relation: "learned_from",
284
- confidence: 0.75,
285
- },
286
- ];
287
- /**
288
- * Link entities created within the same session using causal relations.
289
- *
290
- * For example, if a session produces both an `error` and a `solution`,
291
- * creates an `error -[resolved_by]-> solution` relation.
292
- *
293
- * Non-fatal: all errors are caught silently.
294
- */
295
- export async function linkSessionEntities(client, createdPairs, _workspaceId, _projectId) {
296
- let relationsCreated = 0;
297
- for (const rule of SESSION_CAUSAL_RULES) {
298
- const sources = createdPairs.filter((p) => p.learning.type === rule.sourceType);
299
- const targets = createdPairs.filter((p) => p.learning.type === rule.targetType);
300
- for (const source of sources) {
301
- for (const target of targets) {
302
- try {
303
- await client.createMemoryRelation({
304
- source_id: source.id,
305
- target_id: target.id,
306
- relation_type: rule.relation,
307
- confidence: rule.confidence,
308
- });
309
- relationsCreated++;
310
- }
311
- catch {
312
- // Skip duplicate/failed relations silently
313
- }
314
- }
315
- }
316
- }
317
- return { relationsCreated };
318
- }
319
- // --- Session-End Learning ---
320
- /**
321
- * Extract learnings from a completed agent session.
322
- * Returns the number of memories created.
323
- */
324
- export async function extractLearnings(client, session) {
325
- const workspaceId = getActiveWorkspaceId();
326
- if (!workspaceId) {
327
- return { count: 0, entityIds: [] };
328
- }
329
- const projectId = getActiveProjectId() || undefined;
330
- const learnings = [];
331
- // Search for related entities to enrich summaries with wiki-links
332
- let relatedEntityTitles = [];
333
- if (workspaceId) {
334
- try {
335
- const searchQuery = [
336
- session.cardTitle,
337
- session.currentTask || "",
338
- ...session.cardLabels,
339
- ]
340
- .filter(Boolean)
341
- .join(" ");
342
- const similar = await findSimilarEntities(client, searchQuery, session.currentTask || session.cardTitle, workspaceId, { projectId, limit: 5, minRrfScore: 0.01 });
343
- relatedEntityTitles = similar.slice(0, 3).map((e) => e.title);
344
- }
345
- catch {
346
- /* non-fatal */
347
- }
348
- }
349
- const wikiLinksLine = relatedEntityTitles.length > 0
350
- ? `\nRelated: ${relatedEntityTitles.map((t) => `[[${t}]]`).join(", ")}`
351
- : "";
352
- // Rule 1: Session had blockers → create error entity (only for substantial blockers)
353
- // Skip trivial blocker strings — only store if the blocker text contains
354
- // enough detail to be useful to a future agent (>80 chars).
355
- if (session.blockers && session.blockers.length > 0) {
356
- for (const blocker of session.blockers) {
357
- if (blocker.length < 80)
358
- continue; // Skip trivial blockers like "stuck" or "waiting on API"
359
- // Dedup: check if a similar error entity already exists
360
- let isDuplicate = false;
361
- try {
362
- const similar = await findSimilarEntities(client, blocker.slice(0, 200), blocker, workspaceId, { projectId, limit: 3, minRrfScore: 0.05 });
363
- isDuplicate = similar.some((e) => e.type === "error" && (e.rrf_score ?? 0) >= 0.06);
364
- }
365
- catch {
366
- /* non-fatal */
367
- }
368
- if (!isDuplicate) {
369
- learnings.push({
370
- title: `Blocker: ${blocker.slice(0, 100)}`,
371
- content: `Encountered while working on "${session.cardTitle}":\n\n${blocker}\n\nAgent: ${session.agentName}\nSession status: ${session.status}`,
372
- type: "error",
373
- tier: "episode",
374
- confidence: 0.6,
375
- tags: [
376
- "auto-extracted",
377
- "blocker",
378
- ...session.cardLabels.slice(0, 3),
379
- ],
380
- metadata: {
381
- source: "active_learning",
382
- card_id: session.cardId,
383
- },
384
- });
385
- }
386
- }
387
- }
388
- // Rule 2: Session paused with blockers → create lesson (paused only, not clean completions).
389
- // Clean completions produce no reusable knowledge — the work is in the code/PR.
390
- // Only create a lesson when the session was interrupted (paused with blockers),
391
- // so a future agent can understand what was left unfinished and why.
392
- if (session.status === "paused" && (session.blockers?.length ?? 0) > 0) {
393
- const durationInfo = session.sessionDurationMs
394
- ? `\nDuration: ${Math.round(session.sessionDurationMs / 60000)} minutes`
395
- : "";
396
- learnings.push({
397
- title: `Paused: ${session.cardTitle}`,
398
- content: [
399
- `Paused work on "${session.cardTitle}".`,
400
- session.currentTask ? `Last task: ${session.currentTask}` : "",
401
- session.progressPercent !== undefined
402
- ? `Progress: ${session.progressPercent}%`
403
- : "",
404
- durationInfo,
405
- session.blockers?.length
406
- ? `Blockers: ${session.blockers.join("; ")}`
407
- : "",
408
- `\nAgent: ${session.agentName}`,
409
- wikiLinksLine,
410
- ]
411
- .filter(Boolean)
412
- .join("\n"),
413
- type: "lesson",
414
- tier: "draft",
415
- confidence: 0.6,
416
- tags: [
417
- "auto-extracted",
418
- "session-paused",
419
- ...session.cardLabels.slice(0, 3),
420
- ],
421
- metadata: {
422
- source: "active_learning",
423
- card_id: session.cardId,
424
- },
425
- });
426
- }
427
- // Rule 3: Bug solution — REMOVED.
428
- // Storing "Resolved bug: {card title}" with no detail about the actual fix
429
- // adds zero value. The real solution is in the code diff / PR. Agents should
430
- // use `harmony_remember` to store non-obvious root cause details manually.
431
- // Store learnings, tracking entity ID → learning for graph expansion
432
- const entityIds = [];
433
- // Rule 4: Successful session with tracked steps → create or reinforce procedure entity
434
- // Thresholds raised: require 5+ distinct steps AND 10+ minute duration to avoid
435
- // creating "procedures" from trivial tasks (e.g., a 2-step "investigate → fix" session).
436
- const stepHistory = sessionTaskHistory.get(session.cardId);
437
- const MIN_PROCEDURE_STEPS = 5;
438
- const MIN_PROCEDURE_DURATION_MS = 10 * 60 * 1000; // 10 minutes
439
- const hasEnoughSteps = stepHistory && stepHistory.steps.length >= MIN_PROCEDURE_STEPS;
440
- const hasMinDuration = (session.sessionDurationMs ?? 0) >= MIN_PROCEDURE_DURATION_MS;
441
- const isSuccessful = session.status === "completed" &&
442
- (session.progressPercent === undefined || session.progressPercent >= 85) &&
443
- !session.blockers?.length;
444
- if (isSuccessful && hasEnoughSteps && hasMinDuration) {
445
- const procedureResult = await extractOrReinforceProcedure(client, session, stepHistory.steps, workspaceId, projectId, wikiLinksLine);
446
- if (procedureResult) {
447
- if (procedureResult.mode === "created") {
448
- learnings.push(procedureResult.learning);
449
- }
450
- else {
451
- // Reinforced existing procedure — already saved via API, just track the ID
452
- entityIds.push(procedureResult.entityId);
453
- }
454
- }
455
- }
456
- const createdPairs = [];
457
- for (const learning of learnings) {
458
- try {
459
- const metadata = {
460
- ...learning.metadata,
461
- };
462
- const result = await client.createMemoryEntity({
463
- workspace_id: workspaceId,
464
- project_id: projectId,
465
- type: learning.type,
466
- scope: "project",
467
- memory_tier: learning.tier,
468
- title: learning.title,
469
- content: learning.content,
470
- confidence: learning.confidence,
471
- tags: learning.tags,
472
- metadata,
473
- agent_identifier: session.agentIdentifier,
474
- });
475
- const entity = result.entity;
476
- if (entity?.id) {
477
- entityIds.push(entity.id);
478
- createdPairs.push({ id: entity.id, learning });
479
- }
480
- }
481
- catch {
482
- // Non-fatal: individual learning extraction failure shouldn't block others
483
- }
484
- }
485
- // Auto-expand the knowledge graph and detect contradictions for each newly created entity (fire-and-forget)
486
- for (const { id, learning } of createdPairs) {
487
- autoExpandGraph(client, id, learning.title, learning.content, learning.tags, workspaceId, projectId).catch(() => { });
488
- detectContradictions(client, id, learning.type, learning.title, learning.content, learning.tags, workspaceId, projectId).catch(() => { });
489
- // Cross-type causal linking (e.g., new error → existing solutions)
490
- linkCrossTypeNeighbors(client, id, learning.type, learning.title, learning.content, workspaceId, projectId).catch(() => { });
491
- }
492
- // Same-session causal linking (e.g., error + solution in same session → resolved_by)
493
- if (createdPairs.length >= 2) {
494
- linkSessionEntities(client, createdPairs, workspaceId, projectId).catch(() => { });
495
- }
496
- // Pattern detection DISABLED — these create noise entities like
497
- // "Pattern: recurring procedure (N instances)" that are just catalogs of
498
- // entity titles, eating token budget with zero actionable content.
499
- // The consolidation tool (harmony_consolidate_memories) serves a similar
500
- // purpose and can be improved separately with LLM synthesis.
501
- // See: https://github.com/getharmony/getharmony/issues/memory-quality
502
- // Clean up mid-session tracking
503
- clearMidSessionTracking(session.cardId);
504
- return { count: entityIds.length, entityIds };
505
- }
506
- const PATTERN_THRESHOLD = 3;
507
- /**
508
- * Detect recurring patterns across sessions.
509
- *
510
- * Uses embedding-based similarity (via hybrid search) to find related entities
511
- * instead of naive tag matching. When ≥3 similar entities cluster, creates or
512
- * updates a `pattern` entity with `part_of` relations from members.
513
- */
514
- export async function detectAndCreatePatterns(client, newEntityIds, session, workspaceId, projectId) {
515
- const patternEntityIds = [];
516
- for (const newEntityId of newEntityIds) {
517
- try {
518
- // Fetch the newly created entity to get its type, title, and content
519
- const { entity: rawEntity } = await client.getMemoryEntity(newEntityId);
520
- const entity = rawEntity;
521
- if (!entity?.type)
522
- continue;
523
- // Use embedding-based search with title + content snippet as query
524
- const similar = await findSimilarEntities(client, entity.title, entity.content, workspaceId, { projectId, limit: 30, minRrfScore: 0.01 });
525
- // Exclude newly created entities
526
- const existing = similar.filter((c) => !newEntityIds.includes(c.id) && c.type === entity.type);
527
- if (existing.length < PATTERN_THRESHOLD)
528
- continue;
529
- // Build a descriptive pattern title from member entity titles
530
- const memberTitles = [
531
- entity.title,
532
- ...existing.slice(0, 4).map((e) => e.title),
533
- ];
534
- const patternTitle = `Pattern: recurring ${entity.type} (${existing.length + 1} instances)`;
535
- // Check if a pattern entity for this type already exists
536
- const { entities: existingPatterns } = await client.listMemoryEntities({
537
- workspace_id: workspaceId,
538
- project_id: projectId,
539
- type: "pattern",
540
- limit: 10,
541
- });
542
- // Find a pattern that covers this entity type
543
- const matchingPattern = existingPatterns.find((p) => p.metadata?.pattern_type === entity.type);
544
- let patternId = null;
545
- if (matchingPattern) {
546
- patternId = matchingPattern.id;
547
- await client.updateMemoryEntity(patternId, {
548
- content: `Recurring pattern: ${entity.type} entities appearing ${existing.length + 1} times.\n\nMembers:\n${memberTitles.map((t) => `- ${t}`).join("\n")}\n\nLast updated: ${new Date().toISOString()}`,
549
- metadata: {
550
- pattern_count: existing.length + 1,
551
- pattern_type: entity.type,
552
- last_updated: new Date().toISOString(),
553
- },
554
- });
555
- }
556
- else {
557
- const result = await client.createMemoryEntity({
558
- workspace_id: workspaceId,
559
- project_id: projectId,
560
- type: "pattern",
561
- scope: "project",
562
- memory_tier: "reference",
563
- title: patternTitle,
564
- content: `Recurring pattern: ${entity.type} entities detected ${existing.length + 1} times.\n\nMembers:\n${memberTitles.map((t) => `- ${t}`).join("\n")}`,
565
- confidence: 0.75,
566
- tags: ["auto-extracted", "pattern", entity.type],
567
- metadata: {
568
- source: "pattern_detection",
569
- pattern_type: entity.type,
570
- pattern_count: existing.length + 1,
571
- },
572
- agent_identifier: session.agentIdentifier,
573
- });
574
- const created = result.entity;
575
- if (created?.id) {
576
- patternId = created.id;
577
- patternEntityIds.push(patternId);
578
- }
579
- }
580
- if (!patternId)
581
- continue;
582
- // Link members → pattern using part_of relations
583
- const toLink = [newEntityId, ...existing.slice(0, 4).map((e) => e.id)];
584
- for (const sourceId of toLink) {
585
- try {
586
- await client.createMemoryRelation({
587
- source_id: sourceId,
588
- target_id: patternId,
589
- relation_type: "part_of",
590
- confidence: 0.75,
591
- });
592
- }
593
- catch {
594
- // Skip duplicate/failed relations silently
595
- }
596
- }
597
- }
598
- catch {
599
- // Non-fatal: pattern detection failure should not block anything
600
- }
601
- }
602
- return patternEntityIds;
603
- }
604
- // --- Cross-Session Causal Pattern Detection ---
605
- const CAUSAL_PATTERN_THRESHOLD = 3;
606
- /**
607
- * Detect recurring error→solution chains across sessions.
608
- *
609
- * When a session produces both error and solution entities, searches for
610
- * similar errors from other sessions that also have `resolved_by` relations.
611
- * If ≥3 such pairs exist, creates a `pattern` entity to capture the
612
- * recurring causal chain.
613
- */
614
- export async function detectCausalPatterns(client, createdPairs, session, workspaceId, projectId) {
615
- const patternIds = [];
616
- // Find error+solution pairs from this session
617
- const errors = createdPairs.filter((p) => p.learning.type === "error");
618
- const solutions = createdPairs.filter((p) => p.learning.type === "solution");
619
- if (errors.length === 0 || solutions.length === 0)
620
- return patternIds;
621
- for (const errorPair of errors) {
622
- try {
623
- // Search for similar errors from other sessions
624
- const similarErrors = await findSimilarEntities(client, errorPair.learning.title, errorPair.learning.content, workspaceId, {
625
- projectId,
626
- limit: 20,
627
- minRrfScore: 0.03,
628
- excludeIds: createdPairs.map((p) => p.id),
629
- type: "error",
630
- });
631
- // Filter to errors that have resolved_by relations
632
- const resolvedErrors = [];
633
- for (const similar of similarErrors.slice(0, 10)) {
634
- try {
635
- const { outgoing } = await client.getRelatedEntities(similar.id);
636
- const resolvedByRel = outgoing.find((r) => r.relation_type === "resolved_by");
637
- if (resolvedByRel) {
638
- resolvedErrors.push({
639
- errorId: similar.id,
640
- errorTitle: similar.title,
641
- solutionTitle: resolvedByRel.target_title ||
642
- "unknown",
643
- });
644
- }
645
- }
646
- catch {
647
- // Non-fatal: skip entities where relation lookup fails
648
- }
649
- }
650
- // Need at least CAUSAL_PATTERN_THRESHOLD similar resolved errors (including current)
651
- if (resolvedErrors.length + 1 < CAUSAL_PATTERN_THRESHOLD)
652
- continue;
653
- // Check if a causal pattern already exists for this domain
654
- const { entities: existingPatterns } = await client.listMemoryEntities({
655
- workspace_id: workspaceId,
656
- project_id: projectId,
657
- type: "pattern",
658
- limit: 10,
659
- });
660
- const matchingPattern = existingPatterns.find((p) => p.metadata?.pattern_chain_type === "error_resolved_by_solution");
661
- if (matchingPattern) {
662
- // Update existing causal pattern
663
- await client.updateMemoryEntity(matchingPattern.id, {
664
- content: [
665
- `Recurring error→solution chain detected (${resolvedErrors.length + 1} instances).`,
666
- "",
667
- "## Error→Solution Pairs",
668
- `- ${errorPair.learning.title} → ${solutions[0].learning.title}`,
669
- ...resolvedErrors
670
- .slice(0, 5)
671
- .map((r) => `- ${r.errorTitle} → ${r.solutionTitle}`),
672
- "",
673
- `Last updated: ${new Date().toISOString()}`,
674
- ].join("\n"),
675
- metadata: {
676
- pattern_chain_type: "error_resolved_by_solution",
677
- pattern_count: resolvedErrors.length + 1,
678
- last_updated: new Date().toISOString(),
679
- },
680
- });
681
- // Link current error+solution to the pattern
682
- for (const pair of [errorPair, solutions[0]]) {
683
- try {
684
- await client.createMemoryRelation({
685
- source_id: pair.id,
686
- target_id: matchingPattern.id,
687
- relation_type: "part_of",
688
- confidence: 0.75,
689
- });
690
- }
691
- catch {
692
- // Skip duplicate relations
693
- }
694
- }
695
- }
696
- else {
697
- // Create new causal pattern
698
- const result = await client.createMemoryEntity({
699
- workspace_id: workspaceId,
700
- project_id: projectId,
701
- type: "pattern",
702
- scope: "project",
703
- memory_tier: "reference",
704
- title: `Pattern: recurring error→solution chain (${resolvedErrors.length + 1} instances)`,
705
- content: [
706
- `Recurring error→solution chain detected across ${resolvedErrors.length + 1} sessions.`,
707
- "",
708
- "## Error→Solution Pairs",
709
- `- ${errorPair.learning.title} → ${solutions[0].learning.title}`,
710
- ...resolvedErrors
711
- .slice(0, 5)
712
- .map((r) => `- ${r.errorTitle} → ${r.solutionTitle}`),
713
- ].join("\n"),
714
- confidence: 0.8,
715
- tags: ["auto-extracted", "pattern", "causal-chain"],
716
- metadata: {
717
- source: "causal_pattern_detection",
718
- pattern_chain_type: "error_resolved_by_solution",
719
- pattern_count: resolvedErrors.length + 1,
720
- },
721
- agent_identifier: session.agentIdentifier,
722
- });
723
- const created = result.entity;
724
- if (created?.id) {
725
- patternIds.push(created.id);
726
- // Link members to the pattern
727
- const memberIds = [
728
- errorPair.id,
729
- solutions[0].id,
730
- ...resolvedErrors.slice(0, 4).map((r) => r.errorId),
731
- ];
732
- for (const memberId of memberIds) {
733
- try {
734
- await client.createMemoryRelation({
735
- source_id: memberId,
736
- target_id: created.id,
737
- relation_type: "part_of",
738
- confidence: 0.75,
739
- });
740
- }
741
- catch {
742
- // Skip duplicate relations
743
- }
744
- }
745
- }
746
- }
747
- }
748
- catch {
749
- // Non-fatal: causal pattern detection failure should not block anything
750
- }
751
- }
752
- return patternIds;
753
- }
754
- /**
755
- * Detect potential contradictions for a newly created entity using semantic search.
756
- *
757
- * Uses hybrid FTS+vector search to find same-type entities with similar content,
758
- * then creates `contradicts` relations. Only applies to entity types allowed by
759
- * the schema: decision, pattern, preference, lesson.
760
- *
761
- * Returns the list of contradicting entities found (for inclusion in tool response).
762
- */
763
- export async function detectContradictions(client, entityId, entityType, title, content, tags, workspaceId, projectId) {
764
- // Only types that can participate in contradicts relations
765
- if (!CONTRADICTION_TYPES.has(entityType))
766
- return [];
767
- // Need at least a title to search
768
- if (!title.trim())
769
- return [];
770
- try {
771
- const similar = await findSimilarEntities(client, title, content, workspaceId, {
772
- projectId,
773
- limit: 10,
774
- excludeIds: [entityId],
775
- });
776
- // Filter to same type only (contradictions are within the same type)
777
- const candidates = similar.filter((e) => e.type === entityType && CONTRADICTION_TYPES.has(e.type));
778
- if (candidates.length === 0)
779
- return [];
780
- // Check for actual content divergence: similar topic but different stance.
781
- // Entities that are very similar (high RRF) are likely supporting, not contradicting.
782
- // We want entities that share topic keywords but have meaningful differences.
783
- const contradictions = [];
784
- for (const candidate of candidates) {
785
- // Skip entities with very high similarity — they're duplicates/supporting, not contradictions
786
- if ((candidate.rrf_score ?? 0) > 0.8)
787
- continue;
788
- // Skip entities with very low similarity — they're unrelated
789
- if ((candidate.rrf_score ?? 0) < 0.02)
790
- continue;
791
- // Check tag overlap: need at least 1 shared tag to indicate same domain
792
- const sharedTags = tags.filter((t) => candidate.tags?.includes(t));
793
- if (tags.length > 0 && sharedTags.length === 0)
794
- continue;
795
- contradictions.push({
796
- entityId: candidate.id,
797
- title: candidate.title,
798
- type: candidate.type,
799
- tags: candidate.tags || [],
800
- });
801
- }
802
- // Create contradicts relations (fire-and-forget style, but await for response)
803
- for (const c of contradictions) {
804
- try {
805
- await client.createMemoryRelation({
806
- source_id: entityId,
807
- target_id: c.entityId,
808
- relation_type: "contradicts",
809
- confidence: 0.5,
810
- });
811
- }
812
- catch {
813
- // Skip duplicate/failed relations silently (409 Conflict is expected)
814
- }
815
- }
816
- return contradictions;
817
- }
818
- catch {
819
- // Non-fatal: contradiction detection should never block entity creation
820
- return [];
821
- }
822
- }