@gethmy/mcp 1.0.0 → 2.1.0

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