@weavelogic/knowledge-graph-agent 0.3.0 → 0.4.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.
- package/README.md +290 -3
- package/dist/_virtual/index10.js +2 -2
- package/dist/_virtual/index6.js +2 -2
- package/dist/_virtual/index7.js +2 -2
- package/dist/_virtual/index8.js +2 -2
- package/dist/_virtual/index9.js +2 -2
- package/dist/audit/config.d.ts +150 -0
- package/dist/audit/config.d.ts.map +1 -0
- package/dist/audit/config.js +111 -0
- package/dist/audit/config.js.map +1 -0
- package/dist/audit/index.d.ts +38 -0
- package/dist/audit/index.d.ts.map +1 -0
- package/dist/audit/services/audit-chain.d.ts +276 -0
- package/dist/audit/services/audit-chain.d.ts.map +1 -0
- package/dist/audit/services/audit-chain.js +502 -0
- package/dist/audit/services/audit-chain.js.map +1 -0
- package/dist/audit/services/index.d.ts +11 -0
- package/dist/audit/services/index.d.ts.map +1 -0
- package/dist/audit/services/syndication.d.ts +334 -0
- package/dist/audit/services/syndication.d.ts.map +1 -0
- package/dist/audit/services/syndication.js +589 -0
- package/dist/audit/services/syndication.js.map +1 -0
- package/dist/audit/types.d.ts +453 -0
- package/dist/audit/types.d.ts.map +1 -0
- package/dist/cli/commands/audit.d.ts +21 -0
- package/dist/cli/commands/audit.d.ts.map +1 -0
- package/dist/cli/commands/audit.js +621 -0
- package/dist/cli/commands/audit.js.map +1 -0
- package/dist/cli/commands/vector.d.ts +14 -0
- package/dist/cli/commands/vector.d.ts.map +1 -0
- package/dist/cli/commands/vector.js +429 -0
- package/dist/cli/commands/vector.js.map +1 -0
- package/dist/cli/commands/workflow.d.ts +12 -0
- package/dist/cli/commands/workflow.d.ts.map +1 -0
- package/dist/cli/commands/workflow.js +471 -0
- package/dist/cli/commands/workflow.js.map +1 -0
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +26 -0
- package/dist/cli/index.js.map +1 -1
- package/dist/database/schemas/index.d.ts +85 -0
- package/dist/database/schemas/index.d.ts.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -1
- package/dist/mcp-server/tools/audit/checkpoint.d.ts +58 -0
- package/dist/mcp-server/tools/audit/checkpoint.d.ts.map +1 -0
- package/dist/mcp-server/tools/audit/checkpoint.js +73 -0
- package/dist/mcp-server/tools/audit/checkpoint.js.map +1 -0
- package/dist/mcp-server/tools/audit/index.d.ts +53 -0
- package/dist/mcp-server/tools/audit/index.d.ts.map +1 -0
- package/dist/mcp-server/tools/audit/index.js +12 -0
- package/dist/mcp-server/tools/audit/index.js.map +1 -0
- package/dist/mcp-server/tools/audit/query.d.ts +58 -0
- package/dist/mcp-server/tools/audit/query.d.ts.map +1 -0
- package/dist/mcp-server/tools/audit/query.js +125 -0
- package/dist/mcp-server/tools/audit/query.js.map +1 -0
- package/dist/mcp-server/tools/audit/sync.d.ts +58 -0
- package/dist/mcp-server/tools/audit/sync.d.ts.map +1 -0
- package/dist/mcp-server/tools/audit/sync.js +126 -0
- package/dist/mcp-server/tools/audit/sync.js.map +1 -0
- package/dist/mcp-server/tools/index.d.ts +3 -0
- package/dist/mcp-server/tools/index.d.ts.map +1 -1
- package/dist/mcp-server/tools/registry.js +90 -0
- package/dist/mcp-server/tools/registry.js.map +1 -1
- package/dist/mcp-server/tools/vector/index.d.ts +12 -0
- package/dist/mcp-server/tools/vector/index.d.ts.map +1 -0
- package/dist/mcp-server/tools/vector/index.js +12 -0
- package/dist/mcp-server/tools/vector/index.js.map +1 -0
- package/dist/mcp-server/tools/vector/search.d.ts +41 -0
- package/dist/mcp-server/tools/vector/search.d.ts.map +1 -0
- package/dist/mcp-server/tools/vector/search.js +224 -0
- package/dist/mcp-server/tools/vector/search.js.map +1 -0
- package/dist/mcp-server/tools/vector/trajectory.d.ts +39 -0
- package/dist/mcp-server/tools/vector/trajectory.d.ts.map +1 -0
- package/dist/mcp-server/tools/vector/trajectory.js +170 -0
- package/dist/mcp-server/tools/vector/trajectory.js.map +1 -0
- package/dist/mcp-server/tools/vector/upsert.d.ts +44 -0
- package/dist/mcp-server/tools/vector/upsert.d.ts.map +1 -0
- package/dist/mcp-server/tools/vector/upsert.js +175 -0
- package/dist/mcp-server/tools/vector/upsert.js.map +1 -0
- package/dist/mcp-server/tools/workflow/index.d.ts +29 -0
- package/dist/mcp-server/tools/workflow/index.d.ts.map +1 -0
- package/dist/mcp-server/tools/workflow/index.js +12 -0
- package/dist/mcp-server/tools/workflow/index.js.map +1 -0
- package/dist/mcp-server/tools/workflow/list.d.ts +41 -0
- package/dist/mcp-server/tools/workflow/list.d.ts.map +1 -0
- package/dist/mcp-server/tools/workflow/list.js +195 -0
- package/dist/mcp-server/tools/workflow/list.js.map +1 -0
- package/dist/mcp-server/tools/workflow/start.d.ts +40 -0
- package/dist/mcp-server/tools/workflow/start.d.ts.map +1 -0
- package/dist/mcp-server/tools/workflow/start.js +165 -0
- package/dist/mcp-server/tools/workflow/start.js.map +1 -0
- package/dist/mcp-server/tools/workflow/status.d.ts +38 -0
- package/dist/mcp-server/tools/workflow/status.d.ts.map +1 -0
- package/dist/mcp-server/tools/workflow/status.js +97 -0
- package/dist/mcp-server/tools/workflow/status.js.map +1 -0
- package/dist/node_modules/ajv/dist/compile/index.js +1 -1
- package/dist/node_modules/ajv/dist/vocabularies/applicator/index.js +1 -1
- package/dist/node_modules/ajv/dist/vocabularies/core/index.js +1 -1
- package/dist/node_modules/ajv/dist/vocabularies/format/index.js +1 -1
- package/dist/node_modules/ajv/dist/vocabularies/validation/index.js +1 -1
- package/dist/vector/config.d.ts +300 -0
- package/dist/vector/config.d.ts.map +1 -0
- package/dist/vector/config.js +124 -0
- package/dist/vector/config.js.map +1 -0
- package/dist/vector/index.d.ts +50 -0
- package/dist/vector/index.d.ts.map +1 -0
- package/dist/vector/services/index.d.ts +13 -0
- package/dist/vector/services/index.d.ts.map +1 -0
- package/dist/vector/services/trajectory-tracker.d.ts +405 -0
- package/dist/vector/services/trajectory-tracker.d.ts.map +1 -0
- package/dist/vector/services/trajectory-tracker.js +445 -0
- package/dist/vector/services/trajectory-tracker.js.map +1 -0
- package/dist/vector/services/vector-store.d.ts +339 -0
- package/dist/vector/services/vector-store.d.ts.map +1 -0
- package/dist/vector/services/vector-store.js +748 -0
- package/dist/vector/services/vector-store.js.map +1 -0
- package/dist/vector/types.d.ts +677 -0
- package/dist/vector/types.d.ts.map +1 -0
- package/dist/workflow/adapters/goap-adapter.d.ts +196 -0
- package/dist/workflow/adapters/goap-adapter.d.ts.map +1 -0
- package/dist/workflow/adapters/goap-adapter.js +706 -0
- package/dist/workflow/adapters/goap-adapter.js.map +1 -0
- package/dist/workflow/adapters/index.d.ts +10 -0
- package/dist/workflow/adapters/index.d.ts.map +1 -0
- package/dist/workflow/config.d.ts +135 -0
- package/dist/workflow/config.d.ts.map +1 -0
- package/dist/workflow/config.js +92 -0
- package/dist/workflow/config.js.map +1 -0
- package/dist/workflow/handlers/index.d.ts +9 -0
- package/dist/workflow/handlers/index.d.ts.map +1 -0
- package/dist/workflow/handlers/webhook-handlers.d.ts +397 -0
- package/dist/workflow/handlers/webhook-handlers.d.ts.map +1 -0
- package/dist/workflow/handlers/webhook-handlers.js +454 -0
- package/dist/workflow/handlers/webhook-handlers.js.map +1 -0
- package/dist/workflow/index.d.ts +42 -0
- package/dist/workflow/index.d.ts.map +1 -0
- package/dist/workflow/services/index.d.ts +9 -0
- package/dist/workflow/services/index.d.ts.map +1 -0
- package/dist/workflow/services/workflow-service.d.ts +318 -0
- package/dist/workflow/services/workflow-service.d.ts.map +1 -0
- package/dist/workflow/services/workflow-service.js +577 -0
- package/dist/workflow/services/workflow-service.js.map +1 -0
- package/dist/workflow/types.d.ts +470 -0
- package/dist/workflow/types.d.ts.map +1 -0
- package/dist/workflow/workflows/realtime-collab.d.ts +245 -0
- package/dist/workflow/workflows/realtime-collab.d.ts.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
import { createLogger } from "../../utils/logger.js";
|
|
2
|
+
const logger = createLogger("trajectory-tracker");
|
|
3
|
+
class TrajectoryTracker {
|
|
4
|
+
config;
|
|
5
|
+
activeTrajectories = /* @__PURE__ */ new Map();
|
|
6
|
+
completedTrajectories = [];
|
|
7
|
+
learningRecords = [];
|
|
8
|
+
detectedPatterns = /* @__PURE__ */ new Map();
|
|
9
|
+
/**
|
|
10
|
+
* Create a new TrajectoryTracker instance
|
|
11
|
+
*
|
|
12
|
+
* @param config - Configuration options for the tracker
|
|
13
|
+
*/
|
|
14
|
+
constructor(config = {}) {
|
|
15
|
+
this.config = {
|
|
16
|
+
maxTrajectories: config.maxTrajectories ?? 1e3,
|
|
17
|
+
maxStepsPerTrajectory: config.maxStepsPerTrajectory ?? 100,
|
|
18
|
+
enableAutoLearning: config.enableAutoLearning ?? true,
|
|
19
|
+
minSuccessRateForLearning: config.minSuccessRateForLearning ?? 0.7,
|
|
20
|
+
patternThreshold: config.patternThreshold ?? 3
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Start a new trajectory for an agent
|
|
25
|
+
*
|
|
26
|
+
* Creates a new trajectory record that will track the agent's operations.
|
|
27
|
+
* The trajectory must be finalized with `finalizeTrajectory` when complete.
|
|
28
|
+
*
|
|
29
|
+
* @param agentId - Unique identifier for the agent
|
|
30
|
+
* @param workflowId - Optional workflow this trajectory belongs to
|
|
31
|
+
* @param metadata - Optional additional metadata
|
|
32
|
+
* @returns The unique trajectory ID for tracking
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```typescript
|
|
36
|
+
* const trajectoryId = tracker.startTrajectory(
|
|
37
|
+
* 'researcher-agent-1',
|
|
38
|
+
* 'research-workflow-123',
|
|
39
|
+
* { priority: 'high', source: 'user-request' }
|
|
40
|
+
* );
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
startTrajectory(agentId, workflowId, metadata) {
|
|
44
|
+
const trajectoryId = `traj-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
45
|
+
const trajectory = {
|
|
46
|
+
id: trajectoryId,
|
|
47
|
+
agentId,
|
|
48
|
+
workflowId,
|
|
49
|
+
steps: [],
|
|
50
|
+
startedAt: /* @__PURE__ */ new Date(),
|
|
51
|
+
success: false,
|
|
52
|
+
totalDuration: 0,
|
|
53
|
+
metadata
|
|
54
|
+
};
|
|
55
|
+
this.activeTrajectories.set(trajectoryId, {
|
|
56
|
+
trajectory,
|
|
57
|
+
startTime: Date.now()
|
|
58
|
+
});
|
|
59
|
+
logger.debug("Started trajectory", { trajectoryId, agentId, workflowId });
|
|
60
|
+
return trajectoryId;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Add a step to an active trajectory
|
|
64
|
+
*
|
|
65
|
+
* Records a single operation/action taken by the agent as part of
|
|
66
|
+
* the trajectory. Steps are added in order and include timing information.
|
|
67
|
+
*
|
|
68
|
+
* @param trajectoryId - The trajectory to add the step to
|
|
69
|
+
* @param step - The step data (timestamp is auto-added)
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```typescript
|
|
73
|
+
* tracker.addStep(trajectoryId, {
|
|
74
|
+
* action: 'analyze_document',
|
|
75
|
+
* state: { documentId: 'doc-123', status: 'processing', progress: 0.5 },
|
|
76
|
+
* outcome: 'success',
|
|
77
|
+
* duration: 2500,
|
|
78
|
+
* metadata: { model: 'claude-3-opus' }
|
|
79
|
+
* });
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
addStep(trajectoryId, step) {
|
|
83
|
+
const active = this.activeTrajectories.get(trajectoryId);
|
|
84
|
+
if (!active) {
|
|
85
|
+
logger.warn("Trajectory not found", { trajectoryId });
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (active.trajectory.steps.length >= this.config.maxStepsPerTrajectory) {
|
|
89
|
+
logger.warn("Max steps reached for trajectory", { trajectoryId });
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const fullStep = {
|
|
93
|
+
...step,
|
|
94
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
95
|
+
};
|
|
96
|
+
active.trajectory.steps.push(fullStep);
|
|
97
|
+
logger.debug("Added step to trajectory", {
|
|
98
|
+
trajectoryId,
|
|
99
|
+
action: step.action,
|
|
100
|
+
outcome: step.outcome
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Finalize a trajectory
|
|
105
|
+
*
|
|
106
|
+
* Marks a trajectory as complete, calculates total duration, and
|
|
107
|
+
* optionally triggers pattern learning if auto-learning is enabled.
|
|
108
|
+
*
|
|
109
|
+
* @param trajectoryId - The trajectory to finalize
|
|
110
|
+
* @param options - Finalization options including success status
|
|
111
|
+
* @returns The finalized trajectory, or null if not found
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* ```typescript
|
|
115
|
+
* const trajectory = tracker.finalizeTrajectory(trajectoryId, {
|
|
116
|
+
* success: true,
|
|
117
|
+
* metadata: { finalScore: 0.95 }
|
|
118
|
+
* });
|
|
119
|
+
*
|
|
120
|
+
* if (trajectory) {
|
|
121
|
+
* console.log(`Completed in ${trajectory.totalDuration}ms`);
|
|
122
|
+
* }
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
finalizeTrajectory(trajectoryId, options) {
|
|
126
|
+
const active = this.activeTrajectories.get(trajectoryId);
|
|
127
|
+
if (!active) {
|
|
128
|
+
logger.warn("Trajectory not found for finalization", { trajectoryId });
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
const trajectory = active.trajectory;
|
|
132
|
+
trajectory.completedAt = /* @__PURE__ */ new Date();
|
|
133
|
+
trajectory.success = options.success;
|
|
134
|
+
trajectory.totalDuration = Date.now() - active.startTime;
|
|
135
|
+
if (options.metadata) {
|
|
136
|
+
trajectory.metadata = { ...trajectory.metadata, ...options.metadata };
|
|
137
|
+
}
|
|
138
|
+
this.activeTrajectories.delete(trajectoryId);
|
|
139
|
+
this.completedTrajectories.push(trajectory);
|
|
140
|
+
while (this.completedTrajectories.length > this.config.maxTrajectories) {
|
|
141
|
+
this.completedTrajectories.shift();
|
|
142
|
+
}
|
|
143
|
+
if (this.config.enableAutoLearning && options.success) {
|
|
144
|
+
this.learnFromTrajectory(trajectory);
|
|
145
|
+
}
|
|
146
|
+
logger.info("Finalized trajectory", {
|
|
147
|
+
trajectoryId,
|
|
148
|
+
success: options.success,
|
|
149
|
+
steps: trajectory.steps.length,
|
|
150
|
+
duration: trajectory.totalDuration
|
|
151
|
+
});
|
|
152
|
+
return trajectory;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Learn patterns from a successful trajectory
|
|
156
|
+
*
|
|
157
|
+
* Extracts action sequences from the trajectory and updates pattern
|
|
158
|
+
* frequency and confidence metrics. Creates learning records when
|
|
159
|
+
* patterns exceed the configured threshold.
|
|
160
|
+
*
|
|
161
|
+
* @param trajectory - The trajectory to learn from
|
|
162
|
+
* @internal
|
|
163
|
+
*/
|
|
164
|
+
learnFromTrajectory(trajectory) {
|
|
165
|
+
if (trajectory.steps.length < 2) return;
|
|
166
|
+
const actions = trajectory.steps.map((s) => s.action);
|
|
167
|
+
const patternId = this.generatePatternId(actions);
|
|
168
|
+
const existing = this.detectedPatterns.get(patternId);
|
|
169
|
+
if (existing) {
|
|
170
|
+
existing.frequency++;
|
|
171
|
+
existing.avgDuration = (existing.avgDuration + trajectory.totalDuration) / 2;
|
|
172
|
+
existing.successRate = trajectory.success ? (existing.successRate * (existing.frequency - 1) + 1) / existing.frequency : existing.successRate * (existing.frequency - 1) / existing.frequency;
|
|
173
|
+
existing.confidence = Math.min(1, existing.frequency / 10);
|
|
174
|
+
} else {
|
|
175
|
+
const pattern = {
|
|
176
|
+
id: patternId,
|
|
177
|
+
type: "success",
|
|
178
|
+
actions,
|
|
179
|
+
frequency: 1,
|
|
180
|
+
avgDuration: trajectory.totalDuration,
|
|
181
|
+
successRate: trajectory.success ? 1 : 0,
|
|
182
|
+
confidence: 0.1,
|
|
183
|
+
metadata: {}
|
|
184
|
+
};
|
|
185
|
+
this.detectedPatterns.set(patternId, pattern);
|
|
186
|
+
}
|
|
187
|
+
if (this.detectedPatterns.get(patternId).frequency >= this.config.patternThreshold) {
|
|
188
|
+
const record = {
|
|
189
|
+
trajectoryId: trajectory.id,
|
|
190
|
+
patternId,
|
|
191
|
+
patternType: "success",
|
|
192
|
+
confidence: this.detectedPatterns.get(patternId).confidence,
|
|
193
|
+
learnedAt: /* @__PURE__ */ new Date(),
|
|
194
|
+
appliedCount: 0
|
|
195
|
+
};
|
|
196
|
+
this.learningRecords.push(record);
|
|
197
|
+
logger.info("Learned pattern from trajectory", {
|
|
198
|
+
patternId,
|
|
199
|
+
frequency: this.detectedPatterns.get(patternId).frequency
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Generate a pattern ID from action sequence
|
|
205
|
+
*
|
|
206
|
+
* Creates a unique identifier for a pattern by joining action names.
|
|
207
|
+
*
|
|
208
|
+
* @param actions - Array of action names
|
|
209
|
+
* @returns Pattern identifier string
|
|
210
|
+
* @internal
|
|
211
|
+
*/
|
|
212
|
+
generatePatternId(actions) {
|
|
213
|
+
return actions.join("->");
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Get recommended actions based on current state
|
|
217
|
+
*
|
|
218
|
+
* Analyzes detected patterns to suggest the most likely next actions
|
|
219
|
+
* based on the current action being performed.
|
|
220
|
+
*
|
|
221
|
+
* @param currentAction - The action currently being performed
|
|
222
|
+
* @param context - Optional context for more targeted recommendations
|
|
223
|
+
* @returns Array of recommended actions sorted by confidence
|
|
224
|
+
*
|
|
225
|
+
* @example
|
|
226
|
+
* ```typescript
|
|
227
|
+
* const recommendations = tracker.getRecommendedActions('analyze_document');
|
|
228
|
+
*
|
|
229
|
+
* for (const rec of recommendations) {
|
|
230
|
+
* console.log(`Suggested: ${rec.action} (${rec.confidence.toFixed(2)} confidence)`);
|
|
231
|
+
* }
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
234
|
+
getRecommendedActions(currentAction, context) {
|
|
235
|
+
const recommendations = [];
|
|
236
|
+
for (const [patternId, pattern] of this.detectedPatterns) {
|
|
237
|
+
const actionIndex = pattern.actions.indexOf(currentAction);
|
|
238
|
+
if (actionIndex >= 0 && actionIndex < pattern.actions.length - 1) {
|
|
239
|
+
const nextAction = pattern.actions[actionIndex + 1];
|
|
240
|
+
recommendations.push({
|
|
241
|
+
action: nextAction,
|
|
242
|
+
confidence: pattern.confidence * pattern.successRate,
|
|
243
|
+
basedOn: patternId
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
recommendations.sort((a, b) => b.confidence - a.confidence);
|
|
248
|
+
return recommendations.slice(0, 5);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Get trajectory by ID
|
|
252
|
+
*
|
|
253
|
+
* Retrieves a trajectory from either active or completed trajectories.
|
|
254
|
+
*
|
|
255
|
+
* @param trajectoryId - The trajectory ID to look up
|
|
256
|
+
* @returns The trajectory if found, null otherwise
|
|
257
|
+
*/
|
|
258
|
+
getTrajectory(trajectoryId) {
|
|
259
|
+
const active = this.activeTrajectories.get(trajectoryId);
|
|
260
|
+
if (active) return active.trajectory;
|
|
261
|
+
return this.completedTrajectories.find((t) => t.id === trajectoryId) || null;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Get all trajectories for an agent
|
|
265
|
+
*
|
|
266
|
+
* Retrieves all completed trajectories that were executed by a specific agent.
|
|
267
|
+
*
|
|
268
|
+
* @param agentId - The agent ID to filter by
|
|
269
|
+
* @returns Array of trajectories for the agent
|
|
270
|
+
*/
|
|
271
|
+
getAgentTrajectories(agentId) {
|
|
272
|
+
return this.completedTrajectories.filter((t) => t.agentId === agentId);
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Get trajectories for a workflow
|
|
276
|
+
*
|
|
277
|
+
* Retrieves all completed trajectories that belong to a specific workflow.
|
|
278
|
+
*
|
|
279
|
+
* @param workflowId - The workflow ID to filter by
|
|
280
|
+
* @returns Array of trajectories for the workflow
|
|
281
|
+
*/
|
|
282
|
+
getWorkflowTrajectories(workflowId) {
|
|
283
|
+
return this.completedTrajectories.filter((t) => t.workflowId === workflowId);
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Get detected patterns
|
|
287
|
+
*
|
|
288
|
+
* Retrieves patterns that have been detected from trajectory analysis,
|
|
289
|
+
* optionally filtered by confidence level or pattern type.
|
|
290
|
+
*
|
|
291
|
+
* @param options - Filter options
|
|
292
|
+
* @returns Array of patterns sorted by confidence
|
|
293
|
+
*
|
|
294
|
+
* @example
|
|
295
|
+
* ```typescript
|
|
296
|
+
* // Get high-confidence success patterns
|
|
297
|
+
* const patterns = tracker.getPatterns({
|
|
298
|
+
* minConfidence: 0.8,
|
|
299
|
+
* type: 'success'
|
|
300
|
+
* });
|
|
301
|
+
* ```
|
|
302
|
+
*/
|
|
303
|
+
getPatterns(options) {
|
|
304
|
+
let patterns = Array.from(this.detectedPatterns.values());
|
|
305
|
+
if (options?.minConfidence !== void 0) {
|
|
306
|
+
const minConf = options.minConfidence;
|
|
307
|
+
patterns = patterns.filter((p) => p.confidence >= minConf);
|
|
308
|
+
}
|
|
309
|
+
if (options?.type) {
|
|
310
|
+
patterns = patterns.filter((p) => p.type === options.type);
|
|
311
|
+
}
|
|
312
|
+
return patterns.sort((a, b) => b.confidence - a.confidence);
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Get learning records
|
|
316
|
+
*
|
|
317
|
+
* Retrieves SONA learning records, optionally filtered by pattern ID
|
|
318
|
+
* or time range.
|
|
319
|
+
*
|
|
320
|
+
* @param options - Filter options
|
|
321
|
+
* @returns Array of learning records
|
|
322
|
+
*
|
|
323
|
+
* @example
|
|
324
|
+
* ```typescript
|
|
325
|
+
* // Get recent learning records
|
|
326
|
+
* const records = tracker.getLearningRecords({
|
|
327
|
+
* since: new Date(Date.now() - 24 * 60 * 60 * 1000) // Last 24 hours
|
|
328
|
+
* });
|
|
329
|
+
* ```
|
|
330
|
+
*/
|
|
331
|
+
getLearningRecords(options) {
|
|
332
|
+
let records = [...this.learningRecords];
|
|
333
|
+
if (options?.patternId) {
|
|
334
|
+
records = records.filter((r) => r.patternId === options.patternId);
|
|
335
|
+
}
|
|
336
|
+
if (options?.since !== void 0) {
|
|
337
|
+
const sinceDate = options.since;
|
|
338
|
+
records = records.filter((r) => r.learnedAt >= sinceDate);
|
|
339
|
+
}
|
|
340
|
+
return records;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Get statistics about trajectory tracking
|
|
344
|
+
*
|
|
345
|
+
* Provides aggregate statistics about trajectories, patterns,
|
|
346
|
+
* and learning performance.
|
|
347
|
+
*
|
|
348
|
+
* @returns Statistics object with counts and rates
|
|
349
|
+
*
|
|
350
|
+
* @example
|
|
351
|
+
* ```typescript
|
|
352
|
+
* const stats = tracker.getStats();
|
|
353
|
+
* console.log(`Success rate: ${(stats.successRate * 100).toFixed(1)}%`);
|
|
354
|
+
* console.log(`Patterns detected: ${stats.detectedPatterns}`);
|
|
355
|
+
* ```
|
|
356
|
+
*/
|
|
357
|
+
getStats() {
|
|
358
|
+
const completed = this.completedTrajectories;
|
|
359
|
+
const successCount = completed.filter((t) => t.success).length;
|
|
360
|
+
const totalDuration = completed.reduce((sum, t) => sum + t.totalDuration, 0);
|
|
361
|
+
return {
|
|
362
|
+
activeTrajectories: this.activeTrajectories.size,
|
|
363
|
+
completedTrajectories: completed.length,
|
|
364
|
+
detectedPatterns: this.detectedPatterns.size,
|
|
365
|
+
learningRecords: this.learningRecords.length,
|
|
366
|
+
successRate: completed.length > 0 ? successCount / completed.length : 0,
|
|
367
|
+
avgDuration: completed.length > 0 ? totalDuration / completed.length : 0
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Clear all trajectory data
|
|
372
|
+
*
|
|
373
|
+
* Removes all active trajectories, completed trajectories, learning records,
|
|
374
|
+
* and detected patterns. Use with caution as this is irreversible.
|
|
375
|
+
*/
|
|
376
|
+
clear() {
|
|
377
|
+
this.activeTrajectories.clear();
|
|
378
|
+
this.completedTrajectories = [];
|
|
379
|
+
this.learningRecords = [];
|
|
380
|
+
this.detectedPatterns.clear();
|
|
381
|
+
logger.info("Trajectory tracker cleared");
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Export data for persistence
|
|
385
|
+
*
|
|
386
|
+
* Serializes all trajectory data for storage or transfer.
|
|
387
|
+
* Use with `import()` to restore data.
|
|
388
|
+
*
|
|
389
|
+
* @returns Exportable data object
|
|
390
|
+
*
|
|
391
|
+
* @example
|
|
392
|
+
* ```typescript
|
|
393
|
+
* const data = tracker.export();
|
|
394
|
+
* await fs.writeFile('trajectories.json', JSON.stringify(data));
|
|
395
|
+
* ```
|
|
396
|
+
*/
|
|
397
|
+
export() {
|
|
398
|
+
return {
|
|
399
|
+
trajectories: [...this.completedTrajectories],
|
|
400
|
+
patterns: Array.from(this.detectedPatterns.values()),
|
|
401
|
+
learningRecords: [...this.learningRecords]
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Import data from persistence
|
|
406
|
+
*
|
|
407
|
+
* Restores trajectory data from a previous export.
|
|
408
|
+
*
|
|
409
|
+
* @param data - Previously exported data object
|
|
410
|
+
*
|
|
411
|
+
* @example
|
|
412
|
+
* ```typescript
|
|
413
|
+
* const data = JSON.parse(await fs.readFile('trajectories.json', 'utf-8'));
|
|
414
|
+
* tracker.import(data);
|
|
415
|
+
* ```
|
|
416
|
+
*/
|
|
417
|
+
import(data) {
|
|
418
|
+
if (data.trajectories) {
|
|
419
|
+
this.completedTrajectories = data.trajectories.slice(
|
|
420
|
+
-this.config.maxTrajectories
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
if (data.patterns) {
|
|
424
|
+
for (const pattern of data.patterns) {
|
|
425
|
+
this.detectedPatterns.set(pattern.id, pattern);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
if (data.learningRecords) {
|
|
429
|
+
this.learningRecords = data.learningRecords;
|
|
430
|
+
}
|
|
431
|
+
logger.info("Imported trajectory data", {
|
|
432
|
+
trajectories: this.completedTrajectories.length,
|
|
433
|
+
patterns: this.detectedPatterns.size,
|
|
434
|
+
learningRecords: this.learningRecords.length
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
function createTrajectoryTracker(config) {
|
|
439
|
+
return new TrajectoryTracker(config);
|
|
440
|
+
}
|
|
441
|
+
export {
|
|
442
|
+
TrajectoryTracker,
|
|
443
|
+
createTrajectoryTracker
|
|
444
|
+
};
|
|
445
|
+
//# sourceMappingURL=trajectory-tracker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trajectory-tracker.js","sources":["../../../src/vector/services/trajectory-tracker.ts"],"sourcesContent":["/**\n * Trajectory Tracker\n *\n * Records agent operation sequences for pattern learning.\n * Integrates with the SONA (Self-Optimizing Neural Architecture) engine.\n *\n * The trajectory tracker provides:\n * - Recording of agent operation trajectories\n * - Pattern detection from historical trajectories\n * - Learning records for SONA integration\n * - Success/failure analysis\n * - Recommendations based on learned patterns\n *\n * @module vector/services/trajectory-tracker\n *\n * @example\n * ```typescript\n * import { createTrajectoryTracker } from './trajectory-tracker.js';\n *\n * const tracker = createTrajectoryTracker({\n * maxTrajectories: 1000,\n * enableAutoLearning: true,\n * });\n *\n * // Start a new trajectory\n * const trajectoryId = tracker.startTrajectory('agent-1', 'workflow-1');\n *\n * // Add steps as the agent works\n * tracker.addStep(trajectoryId, {\n * action: 'analyze_document',\n * state: { documentId: 'doc-123', status: 'processing' },\n * outcome: 'success',\n * duration: 1500,\n * });\n *\n * // Finalize when done\n * tracker.finalizeTrajectory(trajectoryId, { success: true });\n *\n * // Get recommendations for future actions\n * const recommendations = tracker.getRecommendedActions('analyze_document');\n * ```\n */\n\nimport type {\n TrajectoryStep,\n AgentTrajectory,\n SonaLearningRecord,\n} from '../types.js';\nimport { createLogger } from '../../utils/index.js';\n\nconst logger = createLogger('trajectory-tracker');\n\n/**\n * Trajectory tracker configuration\n *\n * @property maxTrajectories - Maximum number of trajectories to keep in memory\n * @property maxStepsPerTrajectory - Maximum steps per trajectory\n * @property enableAutoLearning - Enable auto-learning from successful trajectories\n * @property minSuccessRateForLearning - Minimum success rate to learn from\n * @property patternThreshold - Number of occurrences before pattern is learned\n */\nexport interface TrajectoryTrackerConfig {\n /** Maximum number of trajectories to keep in memory */\n maxTrajectories?: number;\n /** Maximum steps per trajectory */\n maxStepsPerTrajectory?: number;\n /** Enable auto-learning from successful trajectories */\n enableAutoLearning?: boolean;\n /** Minimum success rate to learn from */\n minSuccessRateForLearning?: number;\n /** Pattern extraction threshold */\n patternThreshold?: number;\n}\n\n/**\n * Active trajectory being recorded\n * @internal\n */\ninterface ActiveTrajectory {\n trajectory: AgentTrajectory;\n startTime: number;\n}\n\n/**\n * Pattern detected from trajectories\n *\n * Represents a sequence of actions that has been observed multiple times\n * and can be used to predict or recommend future actions.\n */\nexport interface DetectedPattern {\n /** Unique identifier for this pattern */\n id: string;\n\n /** Type of pattern (success, failure, or optimization opportunity) */\n type: 'success' | 'failure' | 'optimization';\n\n /** Sequence of actions in this pattern */\n actions: string[];\n\n /** Number of times this pattern has been observed */\n frequency: number;\n\n /** Average duration of trajectories with this pattern */\n avgDuration: number;\n\n /** Success rate of trajectories with this pattern */\n successRate: number;\n\n /** Confidence level in this pattern (0-1) */\n confidence: number;\n\n /** Additional metadata about the pattern */\n metadata: Record<string, unknown>;\n}\n\n/**\n * Trajectory Tracker class\n *\n * Provides comprehensive tracking and learning from agent operation sequences.\n * This is a core component for the SONA (Self-Optimizing Neural Architecture)\n * system, enabling agents to learn from past experiences and improve over time.\n *\n * Key capabilities:\n * - **Recording**: Track agent operations as trajectories\n * - **Pattern Detection**: Identify recurring action sequences\n * - **Learning**: Create learning records from successful patterns\n * - **Recommendations**: Suggest next actions based on patterns\n * - **Analytics**: Provide statistics on trajectory performance\n *\n * @example\n * ```typescript\n * const tracker = new TrajectoryTracker({\n * maxTrajectories: 500,\n * enableAutoLearning: true,\n * patternThreshold: 5,\n * });\n *\n * // Use throughout agent lifecycle\n * const id = tracker.startTrajectory('my-agent');\n * tracker.addStep(id, { action: 'step1', outcome: 'success' });\n * tracker.addStep(id, { action: 'step2', outcome: 'success' });\n * const trajectory = tracker.finalizeTrajectory(id, { success: true });\n *\n * // Analyze patterns\n * const patterns = tracker.getPatterns({ minConfidence: 0.8 });\n * ```\n */\nexport class TrajectoryTracker {\n private config: Required<TrajectoryTrackerConfig>;\n private activeTrajectories: Map<string, ActiveTrajectory> = new Map();\n private completedTrajectories: AgentTrajectory[] = [];\n private learningRecords: SonaLearningRecord[] = [];\n private detectedPatterns: Map<string, DetectedPattern> = new Map();\n\n /**\n * Create a new TrajectoryTracker instance\n *\n * @param config - Configuration options for the tracker\n */\n constructor(config: TrajectoryTrackerConfig = {}) {\n this.config = {\n maxTrajectories: config.maxTrajectories ?? 1000,\n maxStepsPerTrajectory: config.maxStepsPerTrajectory ?? 100,\n enableAutoLearning: config.enableAutoLearning ?? true,\n minSuccessRateForLearning: config.minSuccessRateForLearning ?? 0.7,\n patternThreshold: config.patternThreshold ?? 3,\n };\n }\n\n /**\n * Start a new trajectory for an agent\n *\n * Creates a new trajectory record that will track the agent's operations.\n * The trajectory must be finalized with `finalizeTrajectory` when complete.\n *\n * @param agentId - Unique identifier for the agent\n * @param workflowId - Optional workflow this trajectory belongs to\n * @param metadata - Optional additional metadata\n * @returns The unique trajectory ID for tracking\n *\n * @example\n * ```typescript\n * const trajectoryId = tracker.startTrajectory(\n * 'researcher-agent-1',\n * 'research-workflow-123',\n * { priority: 'high', source: 'user-request' }\n * );\n * ```\n */\n startTrajectory(\n agentId: string,\n workflowId?: string,\n metadata?: Record<string, unknown>\n ): string {\n const trajectoryId = `traj-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n const trajectory: AgentTrajectory = {\n id: trajectoryId,\n agentId,\n workflowId,\n steps: [],\n startedAt: new Date(),\n success: false,\n totalDuration: 0,\n metadata,\n };\n\n this.activeTrajectories.set(trajectoryId, {\n trajectory,\n startTime: Date.now(),\n });\n\n logger.debug('Started trajectory', { trajectoryId, agentId, workflowId });\n return trajectoryId;\n }\n\n /**\n * Add a step to an active trajectory\n *\n * Records a single operation/action taken by the agent as part of\n * the trajectory. Steps are added in order and include timing information.\n *\n * @param trajectoryId - The trajectory to add the step to\n * @param step - The step data (timestamp is auto-added)\n *\n * @example\n * ```typescript\n * tracker.addStep(trajectoryId, {\n * action: 'analyze_document',\n * state: { documentId: 'doc-123', status: 'processing', progress: 0.5 },\n * outcome: 'success',\n * duration: 2500,\n * metadata: { model: 'claude-3-opus' }\n * });\n * ```\n */\n addStep(\n trajectoryId: string,\n step: Omit<TrajectoryStep, 'timestamp'>\n ): void {\n const active = this.activeTrajectories.get(trajectoryId);\n if (!active) {\n logger.warn('Trajectory not found', { trajectoryId });\n return;\n }\n\n if (active.trajectory.steps.length >= this.config.maxStepsPerTrajectory) {\n logger.warn('Max steps reached for trajectory', { trajectoryId });\n return;\n }\n\n const fullStep: TrajectoryStep = {\n ...step,\n timestamp: new Date(),\n };\n\n active.trajectory.steps.push(fullStep);\n logger.debug('Added step to trajectory', {\n trajectoryId,\n action: step.action,\n outcome: step.outcome,\n });\n }\n\n /**\n * Finalize a trajectory\n *\n * Marks a trajectory as complete, calculates total duration, and\n * optionally triggers pattern learning if auto-learning is enabled.\n *\n * @param trajectoryId - The trajectory to finalize\n * @param options - Finalization options including success status\n * @returns The finalized trajectory, or null if not found\n *\n * @example\n * ```typescript\n * const trajectory = tracker.finalizeTrajectory(trajectoryId, {\n * success: true,\n * metadata: { finalScore: 0.95 }\n * });\n *\n * if (trajectory) {\n * console.log(`Completed in ${trajectory.totalDuration}ms`);\n * }\n * ```\n */\n finalizeTrajectory(\n trajectoryId: string,\n options: {\n success: boolean;\n metadata?: Record<string, unknown>;\n }\n ): AgentTrajectory | null {\n const active = this.activeTrajectories.get(trajectoryId);\n if (!active) {\n logger.warn('Trajectory not found for finalization', { trajectoryId });\n return null;\n }\n\n const trajectory = active.trajectory;\n trajectory.completedAt = new Date();\n trajectory.success = options.success;\n trajectory.totalDuration = Date.now() - active.startTime;\n\n if (options.metadata) {\n trajectory.metadata = { ...trajectory.metadata, ...options.metadata };\n }\n\n // Move to completed\n this.activeTrajectories.delete(trajectoryId);\n this.completedTrajectories.push(trajectory);\n\n // Prune old trajectories\n while (this.completedTrajectories.length > this.config.maxTrajectories) {\n this.completedTrajectories.shift();\n }\n\n // Auto-learn if enabled\n if (this.config.enableAutoLearning && options.success) {\n this.learnFromTrajectory(trajectory);\n }\n\n logger.info('Finalized trajectory', {\n trajectoryId,\n success: options.success,\n steps: trajectory.steps.length,\n duration: trajectory.totalDuration,\n });\n\n return trajectory;\n }\n\n /**\n * Learn patterns from a successful trajectory\n *\n * Extracts action sequences from the trajectory and updates pattern\n * frequency and confidence metrics. Creates learning records when\n * patterns exceed the configured threshold.\n *\n * @param trajectory - The trajectory to learn from\n * @internal\n */\n private learnFromTrajectory(trajectory: AgentTrajectory): void {\n if (trajectory.steps.length < 2) return;\n\n // Extract action sequence\n const actions = trajectory.steps.map((s) => s.action);\n const patternId = this.generatePatternId(actions);\n\n // Check if pattern exists\n const existing = this.detectedPatterns.get(patternId);\n if (existing) {\n // Update existing pattern\n existing.frequency++;\n existing.avgDuration =\n (existing.avgDuration + trajectory.totalDuration) / 2;\n existing.successRate = trajectory.success\n ? (existing.successRate * (existing.frequency - 1) + 1) /\n existing.frequency\n : (existing.successRate * (existing.frequency - 1)) /\n existing.frequency;\n existing.confidence = Math.min(1, existing.frequency / 10);\n } else {\n // Create new pattern\n const pattern: DetectedPattern = {\n id: patternId,\n type: 'success',\n actions,\n frequency: 1,\n avgDuration: trajectory.totalDuration,\n successRate: trajectory.success ? 1 : 0,\n confidence: 0.1,\n metadata: {},\n };\n this.detectedPatterns.set(patternId, pattern);\n }\n\n // Create learning record when pattern exceeds threshold\n if (\n this.detectedPatterns.get(patternId)!.frequency >=\n this.config.patternThreshold\n ) {\n const record: SonaLearningRecord = {\n trajectoryId: trajectory.id,\n patternId,\n patternType: 'success',\n confidence: this.detectedPatterns.get(patternId)!.confidence,\n learnedAt: new Date(),\n appliedCount: 0,\n };\n this.learningRecords.push(record);\n\n logger.info('Learned pattern from trajectory', {\n patternId,\n frequency: this.detectedPatterns.get(patternId)!.frequency,\n });\n }\n }\n\n /**\n * Generate a pattern ID from action sequence\n *\n * Creates a unique identifier for a pattern by joining action names.\n *\n * @param actions - Array of action names\n * @returns Pattern identifier string\n * @internal\n */\n private generatePatternId(actions: string[]): string {\n return actions.join('->');\n }\n\n /**\n * Get recommended actions based on current state\n *\n * Analyzes detected patterns to suggest the most likely next actions\n * based on the current action being performed.\n *\n * @param currentAction - The action currently being performed\n * @param context - Optional context for more targeted recommendations\n * @returns Array of recommended actions sorted by confidence\n *\n * @example\n * ```typescript\n * const recommendations = tracker.getRecommendedActions('analyze_document');\n *\n * for (const rec of recommendations) {\n * console.log(`Suggested: ${rec.action} (${rec.confidence.toFixed(2)} confidence)`);\n * }\n * ```\n */\n getRecommendedActions(\n currentAction: string,\n context?: Record<string, unknown>\n ): Array<{ action: string; confidence: number; basedOn: string }> {\n const recommendations: Array<{\n action: string;\n confidence: number;\n basedOn: string;\n }> = [];\n\n for (const [patternId, pattern] of this.detectedPatterns) {\n const actionIndex = pattern.actions.indexOf(currentAction);\n if (actionIndex >= 0 && actionIndex < pattern.actions.length - 1) {\n const nextAction = pattern.actions[actionIndex + 1];\n recommendations.push({\n action: nextAction,\n confidence: pattern.confidence * pattern.successRate,\n basedOn: patternId,\n });\n }\n }\n\n // Sort by confidence (highest first)\n recommendations.sort((a, b) => b.confidence - a.confidence);\n return recommendations.slice(0, 5);\n }\n\n /**\n * Get trajectory by ID\n *\n * Retrieves a trajectory from either active or completed trajectories.\n *\n * @param trajectoryId - The trajectory ID to look up\n * @returns The trajectory if found, null otherwise\n */\n getTrajectory(trajectoryId: string): AgentTrajectory | null {\n // Check active first\n const active = this.activeTrajectories.get(trajectoryId);\n if (active) return active.trajectory;\n\n // Check completed\n return (\n this.completedTrajectories.find((t) => t.id === trajectoryId) || null\n );\n }\n\n /**\n * Get all trajectories for an agent\n *\n * Retrieves all completed trajectories that were executed by a specific agent.\n *\n * @param agentId - The agent ID to filter by\n * @returns Array of trajectories for the agent\n */\n getAgentTrajectories(agentId: string): AgentTrajectory[] {\n return this.completedTrajectories.filter((t) => t.agentId === agentId);\n }\n\n /**\n * Get trajectories for a workflow\n *\n * Retrieves all completed trajectories that belong to a specific workflow.\n *\n * @param workflowId - The workflow ID to filter by\n * @returns Array of trajectories for the workflow\n */\n getWorkflowTrajectories(workflowId: string): AgentTrajectory[] {\n return this.completedTrajectories.filter((t) => t.workflowId === workflowId);\n }\n\n /**\n * Get detected patterns\n *\n * Retrieves patterns that have been detected from trajectory analysis,\n * optionally filtered by confidence level or pattern type.\n *\n * @param options - Filter options\n * @returns Array of patterns sorted by confidence\n *\n * @example\n * ```typescript\n * // Get high-confidence success patterns\n * const patterns = tracker.getPatterns({\n * minConfidence: 0.8,\n * type: 'success'\n * });\n * ```\n */\n getPatterns(options?: {\n minConfidence?: number;\n type?: 'success' | 'failure' | 'optimization';\n }): DetectedPattern[] {\n let patterns = Array.from(this.detectedPatterns.values());\n\n if (options?.minConfidence !== undefined) {\n const minConf = options.minConfidence;\n patterns = patterns.filter((p) => p.confidence >= minConf);\n }\n\n if (options?.type) {\n patterns = patterns.filter((p) => p.type === options.type);\n }\n\n return patterns.sort((a, b) => b.confidence - a.confidence);\n }\n\n /**\n * Get learning records\n *\n * Retrieves SONA learning records, optionally filtered by pattern ID\n * or time range.\n *\n * @param options - Filter options\n * @returns Array of learning records\n *\n * @example\n * ```typescript\n * // Get recent learning records\n * const records = tracker.getLearningRecords({\n * since: new Date(Date.now() - 24 * 60 * 60 * 1000) // Last 24 hours\n * });\n * ```\n */\n getLearningRecords(options?: {\n patternId?: string;\n since?: Date;\n }): SonaLearningRecord[] {\n let records = [...this.learningRecords];\n\n if (options?.patternId) {\n records = records.filter((r) => r.patternId === options.patternId);\n }\n\n if (options?.since !== undefined) {\n const sinceDate = options.since;\n records = records.filter((r) => r.learnedAt >= sinceDate);\n }\n\n return records;\n }\n\n /**\n * Get statistics about trajectory tracking\n *\n * Provides aggregate statistics about trajectories, patterns,\n * and learning performance.\n *\n * @returns Statistics object with counts and rates\n *\n * @example\n * ```typescript\n * const stats = tracker.getStats();\n * console.log(`Success rate: ${(stats.successRate * 100).toFixed(1)}%`);\n * console.log(`Patterns detected: ${stats.detectedPatterns}`);\n * ```\n */\n getStats(): {\n activeTrajectories: number;\n completedTrajectories: number;\n detectedPatterns: number;\n learningRecords: number;\n successRate: number;\n avgDuration: number;\n } {\n const completed = this.completedTrajectories;\n const successCount = completed.filter((t) => t.success).length;\n const totalDuration = completed.reduce((sum, t) => sum + t.totalDuration, 0);\n\n return {\n activeTrajectories: this.activeTrajectories.size,\n completedTrajectories: completed.length,\n detectedPatterns: this.detectedPatterns.size,\n learningRecords: this.learningRecords.length,\n successRate: completed.length > 0 ? successCount / completed.length : 0,\n avgDuration: completed.length > 0 ? totalDuration / completed.length : 0,\n };\n }\n\n /**\n * Clear all trajectory data\n *\n * Removes all active trajectories, completed trajectories, learning records,\n * and detected patterns. Use with caution as this is irreversible.\n */\n clear(): void {\n this.activeTrajectories.clear();\n this.completedTrajectories = [];\n this.learningRecords = [];\n this.detectedPatterns.clear();\n logger.info('Trajectory tracker cleared');\n }\n\n /**\n * Export data for persistence\n *\n * Serializes all trajectory data for storage or transfer.\n * Use with `import()` to restore data.\n *\n * @returns Exportable data object\n *\n * @example\n * ```typescript\n * const data = tracker.export();\n * await fs.writeFile('trajectories.json', JSON.stringify(data));\n * ```\n */\n export(): {\n trajectories: AgentTrajectory[];\n patterns: DetectedPattern[];\n learningRecords: SonaLearningRecord[];\n } {\n return {\n trajectories: [...this.completedTrajectories],\n patterns: Array.from(this.detectedPatterns.values()),\n learningRecords: [...this.learningRecords],\n };\n }\n\n /**\n * Import data from persistence\n *\n * Restores trajectory data from a previous export.\n *\n * @param data - Previously exported data object\n *\n * @example\n * ```typescript\n * const data = JSON.parse(await fs.readFile('trajectories.json', 'utf-8'));\n * tracker.import(data);\n * ```\n */\n import(data: {\n trajectories?: AgentTrajectory[];\n patterns?: DetectedPattern[];\n learningRecords?: SonaLearningRecord[];\n }): void {\n if (data.trajectories) {\n this.completedTrajectories = data.trajectories.slice(\n -this.config.maxTrajectories\n );\n }\n if (data.patterns) {\n for (const pattern of data.patterns) {\n this.detectedPatterns.set(pattern.id, pattern);\n }\n }\n if (data.learningRecords) {\n this.learningRecords = data.learningRecords;\n }\n logger.info('Imported trajectory data', {\n trajectories: this.completedTrajectories.length,\n patterns: this.detectedPatterns.size,\n learningRecords: this.learningRecords.length,\n });\n }\n}\n\n/**\n * Create a trajectory tracker instance\n *\n * Factory function for creating a TrajectoryTracker with the specified\n * configuration.\n *\n * @param config - Optional configuration options\n * @returns New TrajectoryTracker instance\n *\n * @example\n * ```typescript\n * import { createTrajectoryTracker } from './trajectory-tracker.js';\n *\n * const tracker = createTrajectoryTracker({\n * maxTrajectories: 500,\n * enableAutoLearning: true,\n * patternThreshold: 5,\n * });\n * ```\n */\nexport function createTrajectoryTracker(\n config?: TrajectoryTrackerConfig\n): TrajectoryTracker {\n return new TrajectoryTracker(config);\n}\n"],"names":[],"mappings":";AAkDA,MAAM,SAAS,aAAa,oBAAoB;AAiGzC,MAAM,kBAAkB;AAAA,EACrB;AAAA,EACA,yCAAwD,IAAA;AAAA,EACxD,wBAA2C,CAAA;AAAA,EAC3C,kBAAwC,CAAA;AAAA,EACxC,uCAAqD,IAAA;AAAA;AAAA;AAAA;AAAA;A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