@agent-relay/trajectory 0.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.
@@ -0,0 +1,987 @@
1
+ /**
2
+ * Trajectory Integration Module
3
+ *
4
+ * Integrates with the agent-trajectories package to provide
5
+ * PDERO paradigm tracking within agent-relay.
6
+ *
7
+ * This module provides a bridge between agent-relay and the
8
+ * external `trail` CLI / agent-trajectories library.
9
+ *
10
+ * Key integration points:
11
+ * - Auto-starts trajectory when agent is instantiated with a task
12
+ * - Records all inter-agent messages
13
+ * - Auto-detects PDERO phase transitions from output
14
+ * - Provides hooks for key agent lifecycle events
15
+ */
16
+ import { spawn, execSync } from 'node:child_process';
17
+ import { readFileSync, existsSync, readdirSync } from 'node:fs';
18
+ import { join } from 'node:path';
19
+ import { getProjectPaths } from '@agent-relay/config/project-namespace';
20
+ import { getPrimaryTrajectoriesDir, getAllTrajectoriesDirs, getTrajectoryEnvVars, } from '@agent-relay/config/trajectory-config';
21
+ /**
22
+ * Read a single trajectory index file from a directory
23
+ */
24
+ function resolveIndexEntryPath(trajectoriesDir, entryPath) {
25
+ if (!entryPath) {
26
+ return entryPath;
27
+ }
28
+ if (existsSync(entryPath)) {
29
+ return entryPath;
30
+ }
31
+ const normalized = entryPath.replace(/\\/g, '/');
32
+ const marker = '/.trajectories/';
33
+ const markerIndex = normalized.indexOf(marker);
34
+ if (markerIndex >= 0) {
35
+ const relative = normalized.slice(markerIndex + marker.length);
36
+ const candidate = join(trajectoriesDir, relative);
37
+ if (existsSync(candidate)) {
38
+ return candidate;
39
+ }
40
+ }
41
+ const subdirMatch = normalized.match(/\/(active|completed)\/.+$/);
42
+ if (subdirMatch) {
43
+ const relative = subdirMatch[0].slice(1);
44
+ const candidate = join(trajectoriesDir, relative);
45
+ if (existsSync(candidate)) {
46
+ return candidate;
47
+ }
48
+ }
49
+ return entryPath;
50
+ }
51
+ function readSingleTrajectoryIndex(trajectoriesDir) {
52
+ try {
53
+ const indexPath = join(trajectoriesDir, 'index.json');
54
+ if (!existsSync(indexPath)) {
55
+ return null;
56
+ }
57
+ const content = readFileSync(indexPath, 'utf-8');
58
+ const index = JSON.parse(content);
59
+ const trajectories = index.trajectories ?? {};
60
+ for (const [id, entry] of Object.entries(trajectories)) {
61
+ trajectories[id] = {
62
+ ...entry,
63
+ path: resolveIndexEntryPath(trajectoriesDir, entry.path),
64
+ };
65
+ }
66
+ return { ...index, trajectories };
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ }
72
+ /**
73
+ * Read and merge trajectory indexes from all locations (repo + user-level)
74
+ * This allows reading trajectories from both places
75
+ */
76
+ function readTrajectoryIndex() {
77
+ const dirs = getAllTrajectoriesDirs();
78
+ if (dirs.length === 0) {
79
+ return null;
80
+ }
81
+ // Read and merge all indexes
82
+ let mergedIndex = null;
83
+ for (const dir of dirs) {
84
+ const index = readSingleTrajectoryIndex(dir);
85
+ if (!index)
86
+ continue;
87
+ if (!mergedIndex) {
88
+ mergedIndex = index;
89
+ }
90
+ else {
91
+ // Merge trajectories, preferring more recent entries
92
+ for (const [id, entry] of Object.entries(index.trajectories)) {
93
+ const existing = mergedIndex.trajectories[id];
94
+ if (!existing) {
95
+ mergedIndex.trajectories[id] = entry;
96
+ }
97
+ else {
98
+ // Keep the more recently updated one
99
+ const existingTime = new Date(existing.completedAt || existing.startedAt).getTime();
100
+ const newTime = new Date(entry.completedAt || entry.startedAt).getTime();
101
+ if (newTime > existingTime) {
102
+ mergedIndex.trajectories[id] = entry;
103
+ }
104
+ }
105
+ }
106
+ // Update lastUpdated to most recent
107
+ if (new Date(index.lastUpdated) > new Date(mergedIndex.lastUpdated)) {
108
+ mergedIndex.lastUpdated = index.lastUpdated;
109
+ }
110
+ }
111
+ }
112
+ return mergedIndex;
113
+ }
114
+ /**
115
+ * Read a specific trajectory file directly from filesystem
116
+ */
117
+ function readTrajectoryFile(trajectoryPath) {
118
+ try {
119
+ if (!existsSync(trajectoryPath)) {
120
+ return null;
121
+ }
122
+ const content = readFileSync(trajectoryPath, 'utf-8');
123
+ return JSON.parse(content);
124
+ }
125
+ catch {
126
+ return null;
127
+ }
128
+ }
129
+ function getCurrentPhaseFromTrajectory(trajectory) {
130
+ if (!trajectory?.chapters?.length) {
131
+ return undefined;
132
+ }
133
+ const lastChapter = trajectory.chapters[trajectory.chapters.length - 1];
134
+ for (const event of [...(lastChapter.events || [])].reverse()) {
135
+ if (event.type === 'phase_transition' || event.type === 'phase') {
136
+ const phaseMatch = event.content?.match(/phase[:\s]+(\w+)/i);
137
+ if (phaseMatch) {
138
+ return phaseMatch[1].toLowerCase();
139
+ }
140
+ }
141
+ }
142
+ return undefined;
143
+ }
144
+ function listActiveTrajectoryFiles(trajectoriesDir) {
145
+ const activeDir = join(trajectoriesDir, 'active');
146
+ if (!existsSync(activeDir)) {
147
+ return [];
148
+ }
149
+ return readdirSync(activeDir, { withFileTypes: true })
150
+ .filter(entry => entry.isFile() && entry.name.endsWith('.json'))
151
+ .map(entry => join(activeDir, entry.name));
152
+ }
153
+ function findActiveTrajectoryPathById(trajectoryDirs, trajectoryId) {
154
+ for (const dir of trajectoryDirs) {
155
+ const candidate = join(dir, 'active', `${trajectoryId}.json`);
156
+ if (existsSync(candidate)) {
157
+ return candidate;
158
+ }
159
+ }
160
+ return null;
161
+ }
162
+ /**
163
+ * Run a trail CLI command
164
+ * Uses config-based environment to control trajectory storage location
165
+ */
166
+ async function runTrail(args) {
167
+ return new Promise((resolve) => {
168
+ // Get trajectory env vars to set correct storage location
169
+ const trajectoryEnv = getTrajectoryEnvVars();
170
+ const proc = spawn('trail', args, {
171
+ cwd: getProjectPaths().projectRoot,
172
+ env: { ...process.env, ...trajectoryEnv },
173
+ stdio: ['pipe', 'pipe', 'pipe'],
174
+ });
175
+ let stdout = '';
176
+ let stderr = '';
177
+ proc.stdout?.on('data', (data) => {
178
+ stdout += data.toString();
179
+ });
180
+ proc.stderr?.on('data', (data) => {
181
+ stderr += data.toString();
182
+ });
183
+ proc.on('error', (err) => {
184
+ resolve({ success: false, output: '', error: `Failed to run trail: ${err.message}` });
185
+ });
186
+ proc.on('close', (code) => {
187
+ if (code === 0) {
188
+ resolve({ success: true, output: stdout.trim() });
189
+ }
190
+ else {
191
+ resolve({ success: false, output: stdout.trim(), error: stderr.trim() || `Exit code: ${code}` });
192
+ }
193
+ });
194
+ });
195
+ }
196
+ /**
197
+ * Check if trail CLI is available
198
+ */
199
+ export async function isTrailAvailable() {
200
+ const result = await runTrail(['--version']);
201
+ return result.success;
202
+ }
203
+ /**
204
+ * Start a new trajectory
205
+ */
206
+ export async function startTrajectory(options) {
207
+ const args = ['start', options.task];
208
+ if (options.taskId) {
209
+ args.push('--task-id', options.taskId);
210
+ }
211
+ if (options.source) {
212
+ args.push('--source', options.source);
213
+ }
214
+ if (options.agentName) {
215
+ args.push('--agent', options.agentName);
216
+ }
217
+ if (options.phase) {
218
+ args.push('--phase', options.phase);
219
+ }
220
+ const result = await runTrail(args);
221
+ if (result.success) {
222
+ // Parse trajectory ID from output like "✓ Trajectory started: traj_xxx"
223
+ const match = result.output.match(/traj_[a-z0-9]+/i);
224
+ return { success: true, trajectoryId: match?.[0] };
225
+ }
226
+ return { success: false, error: result.error };
227
+ }
228
+ /**
229
+ * Get current trajectory status
230
+ * Reads directly from .trajectories/index.json instead of using CLI
231
+ */
232
+ export async function getTrajectoryStatus() {
233
+ const index = readTrajectoryIndex();
234
+ const trajectoryDirs = getAllTrajectoriesDirs();
235
+ if (!index && trajectoryDirs.length === 0) {
236
+ return { active: false };
237
+ }
238
+ // Find an active trajectory
239
+ if (index) {
240
+ for (const [id, entry] of Object.entries(index.trajectories)) {
241
+ if (entry.status === 'active') {
242
+ // Read the full trajectory file to get phase info
243
+ const trajectory = readTrajectoryFile(entry.path);
244
+ const currentPhase = getCurrentPhaseFromTrajectory(trajectory);
245
+ return {
246
+ active: true,
247
+ trajectoryId: id,
248
+ phase: currentPhase,
249
+ task: entry.title,
250
+ };
251
+ }
252
+ }
253
+ }
254
+ for (const dir of trajectoryDirs) {
255
+ for (const activePath of listActiveTrajectoryFiles(dir)) {
256
+ const trajectory = readTrajectoryFile(activePath);
257
+ if (!trajectory) {
258
+ continue;
259
+ }
260
+ return {
261
+ active: true,
262
+ trajectoryId: trajectory.id,
263
+ phase: getCurrentPhaseFromTrajectory(trajectory),
264
+ task: trajectory.task?.title,
265
+ };
266
+ }
267
+ }
268
+ return { active: false };
269
+ }
270
+ /**
271
+ * Transition to a new PDERO phase
272
+ */
273
+ export async function transitionPhase(phase, reason, agentName) {
274
+ const args = ['phase', phase];
275
+ if (reason) {
276
+ args.push('--reason', reason);
277
+ }
278
+ if (agentName) {
279
+ args.push('--agent', agentName);
280
+ }
281
+ const result = await runTrail(args);
282
+ return { success: result.success, error: result.error };
283
+ }
284
+ /**
285
+ * Record a decision
286
+ */
287
+ export async function recordDecision(options) {
288
+ const args = ['decision', options.choice];
289
+ if (options.question) {
290
+ args.push('--question', options.question);
291
+ }
292
+ if (options.alternatives && options.alternatives.length > 0) {
293
+ args.push('--alternatives', options.alternatives.join(','));
294
+ }
295
+ if (options.reasoning) {
296
+ args.push('--reasoning', options.reasoning);
297
+ }
298
+ if (options.confidence !== undefined) {
299
+ args.push('--confidence', options.confidence.toString());
300
+ }
301
+ const result = await runTrail(args);
302
+ return { success: result.success, error: result.error };
303
+ }
304
+ /**
305
+ * Record an event/observation
306
+ */
307
+ export async function recordEvent(content, type = 'observation', agentName) {
308
+ const args = ['event', content, '--type', type];
309
+ if (agentName) {
310
+ args.push('--agent', agentName);
311
+ }
312
+ const result = await runTrail(args);
313
+ return { success: result.success, error: result.error };
314
+ }
315
+ /**
316
+ * Record a message (sent or received)
317
+ */
318
+ export async function recordMessage(direction, from, to, body) {
319
+ const content = `Message ${direction}: ${direction === 'sent' ? `→ ${to}` : `← ${from}`}: ${body.slice(0, 100)}${body.length > 100 ? '...' : ''}`;
320
+ return recordEvent(content, 'observation');
321
+ }
322
+ /**
323
+ * Complete the current trajectory
324
+ */
325
+ export async function completeTrajectory(options = {}) {
326
+ const args = ['complete'];
327
+ if (options.summary) {
328
+ args.push('--summary', options.summary);
329
+ }
330
+ if (options.confidence !== undefined) {
331
+ args.push('--confidence', options.confidence.toString());
332
+ }
333
+ if (options.challenges && options.challenges.length > 0) {
334
+ args.push('--challenges', options.challenges.join(','));
335
+ }
336
+ if (options.learnings && options.learnings.length > 0) {
337
+ args.push('--learnings', options.learnings.join(','));
338
+ }
339
+ const result = await runTrail(args);
340
+ return { success: result.success, error: result.error };
341
+ }
342
+ /**
343
+ * Abandon the current trajectory
344
+ */
345
+ export async function abandonTrajectory(reason) {
346
+ const args = ['abandon'];
347
+ if (reason) {
348
+ args.push('--reason', reason);
349
+ }
350
+ const result = await runTrail(args);
351
+ return { success: result.success, error: result.error };
352
+ }
353
+ /**
354
+ * List trajectory steps/events
355
+ * Returns steps for the current or specified trajectory
356
+ * Reads directly from filesystem instead of using CLI
357
+ */
358
+ export async function listTrajectorySteps(trajectoryId) {
359
+ const trajectoryDirs = getAllTrajectoriesDirs();
360
+ const index = readTrajectoryIndex();
361
+ if (!index && trajectoryDirs.length === 0) {
362
+ return { success: true, steps: [] };
363
+ }
364
+ // Collect all trajectory paths to load
365
+ const trajectoryPaths = new Set();
366
+ if (trajectoryId) {
367
+ // Use specified trajectory - try multiple lookup strategies
368
+ let foundPath = null;
369
+ // Strategy 1: Look up by index key
370
+ const entry = index?.trajectories[trajectoryId];
371
+ if (entry) {
372
+ foundPath = entry.path;
373
+ console.log('[trajectory] Found by index key:', trajectoryId, '->', foundPath);
374
+ }
375
+ // Strategy 2: If not found by key, search index entries by file's internal ID
376
+ // This handles cases where the index key differs from the file's internal ID
377
+ if (!foundPath && index) {
378
+ for (const [_key, indexEntry] of Object.entries(index.trajectories)) {
379
+ const trajectory = readTrajectoryFile(indexEntry.path);
380
+ if (trajectory && trajectory.id === trajectoryId) {
381
+ foundPath = indexEntry.path;
382
+ console.log('[trajectory] Found by file ID scan:', trajectoryId, '->', foundPath);
383
+ break;
384
+ }
385
+ }
386
+ }
387
+ // Strategy 3: Fall back to active directory filename match
388
+ if (!foundPath) {
389
+ foundPath = findActiveTrajectoryPathById(trajectoryDirs, trajectoryId);
390
+ if (foundPath) {
391
+ console.log('[trajectory] Found by active dir fallback:', trajectoryId, '->', foundPath);
392
+ }
393
+ }
394
+ if (foundPath) {
395
+ trajectoryPaths.add(foundPath);
396
+ }
397
+ else {
398
+ console.log('[trajectory] Not found:', trajectoryId);
399
+ }
400
+ }
401
+ else {
402
+ // Collect ALL active trajectories (not just the first one)
403
+ if (index) {
404
+ for (const [_id, entry] of Object.entries(index.trajectories)) {
405
+ if (entry.status === 'active') {
406
+ trajectoryPaths.add(entry.path);
407
+ }
408
+ }
409
+ }
410
+ for (const dir of trajectoryDirs) {
411
+ for (const activePath of listActiveTrajectoryFiles(dir)) {
412
+ trajectoryPaths.add(activePath);
413
+ }
414
+ }
415
+ }
416
+ if (trajectoryPaths.size === 0) {
417
+ return { success: true, steps: [] };
418
+ }
419
+ // Load all trajectories and merge their steps
420
+ const steps = [];
421
+ let stepIndex = 0;
422
+ for (const trajectoryPath of trajectoryPaths) {
423
+ const trajectory = readTrajectoryFile(trajectoryPath);
424
+ if (!trajectory) {
425
+ continue;
426
+ }
427
+ // Extract events from all chapters
428
+ // Include trajectory ID in step IDs to ensure uniqueness across trajectories
429
+ // This prevents React key collisions when switching between trajectories
430
+ const trajId = trajectory.id || 'unknown';
431
+ for (const chapter of trajectory.chapters || []) {
432
+ for (const event of chapter.events || []) {
433
+ steps.push({
434
+ id: `${trajId}-step-${stepIndex++}`,
435
+ timestamp: event.ts || Date.now(),
436
+ type: mapEventType(event.type),
437
+ title: event.content?.slice(0, 50) || event.type || 'Event',
438
+ description: event.content,
439
+ metadata: event.raw,
440
+ status: mapEventStatus(trajectory.status),
441
+ });
442
+ }
443
+ }
444
+ }
445
+ // Sort steps by timestamp to maintain chronological order across all trajectories
446
+ steps.sort((a, b) => {
447
+ const timeA = typeof a.timestamp === 'number' ? a.timestamp : new Date(a.timestamp).getTime();
448
+ const timeB = typeof b.timestamp === 'number' ? b.timestamp : new Date(b.timestamp).getTime();
449
+ return timeA - timeB;
450
+ });
451
+ return { success: true, steps };
452
+ }
453
+ /**
454
+ * Get trajectory history - list all trajectories
455
+ * Reads directly from filesystem
456
+ */
457
+ export async function getTrajectoryHistory() {
458
+ const trajectoryDirs = getAllTrajectoriesDirs();
459
+ const index = readTrajectoryIndex();
460
+ if (!index && trajectoryDirs.length === 0) {
461
+ return { success: true, trajectories: [] };
462
+ }
463
+ const trajectories = [];
464
+ const seenIds = new Set();
465
+ if (index) {
466
+ for (const [indexKey, entry] of Object.entries(index.trajectories)) {
467
+ // Read the trajectory file to get the actual internal ID
468
+ // This ensures consistency between history list IDs and file content
469
+ const trajectory = entry.path ? readTrajectoryFile(entry.path) : null;
470
+ // Use the file's internal ID if available, otherwise fall back to index key
471
+ // This fixes the mismatch where index key differs from file's internal ID
472
+ const actualId = trajectory?.id || indexKey;
473
+ // Skip if we've already seen this ID (from a previous directory's index)
474
+ if (seenIds.has(actualId)) {
475
+ continue;
476
+ }
477
+ const historyEntry = {
478
+ id: actualId,
479
+ title: trajectory?.task?.title || entry.title,
480
+ status: entry.status,
481
+ startedAt: trajectory?.startedAt || entry.startedAt,
482
+ completedAt: trajectory?.completedAt || entry.completedAt,
483
+ };
484
+ // Add additional details from trajectory file
485
+ if (trajectory) {
486
+ historyEntry.agents = trajectory.agents?.map(a => a.name);
487
+ if (trajectory.retrospective) {
488
+ historyEntry.summary = trajectory.retrospective.summary;
489
+ historyEntry.confidence = trajectory.retrospective.confidence;
490
+ }
491
+ }
492
+ trajectories.push(historyEntry);
493
+ seenIds.add(actualId);
494
+ }
495
+ }
496
+ for (const dir of trajectoryDirs) {
497
+ for (const activePath of listActiveTrajectoryFiles(dir)) {
498
+ const trajectory = readTrajectoryFile(activePath);
499
+ if (!trajectory || seenIds.has(trajectory.id)) {
500
+ continue;
501
+ }
502
+ const historyEntry = {
503
+ id: trajectory.id,
504
+ title: trajectory.task?.title || 'Untitled trajectory',
505
+ status: trajectory.status ?? 'active',
506
+ startedAt: trajectory.startedAt,
507
+ completedAt: trajectory.completedAt,
508
+ agents: trajectory.agents?.map(a => a.name),
509
+ };
510
+ if (trajectory.retrospective) {
511
+ historyEntry.summary = trajectory.retrospective.summary;
512
+ historyEntry.confidence = trajectory.retrospective.confidence;
513
+ }
514
+ trajectories.push(historyEntry);
515
+ seenIds.add(trajectory.id);
516
+ }
517
+ }
518
+ // Sort by startedAt descending (most recent first)
519
+ trajectories.sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime());
520
+ return { success: true, trajectories };
521
+ }
522
+ /**
523
+ * Map trail event type to dashboard type
524
+ */
525
+ function mapEventType(type) {
526
+ switch (type?.toLowerCase()) {
527
+ case 'tool':
528
+ case 'tool_call':
529
+ case 'tool_use':
530
+ return 'tool_call';
531
+ case 'decision':
532
+ case 'choice':
533
+ return 'decision';
534
+ case 'message':
535
+ case 'observation':
536
+ return 'message';
537
+ case 'phase':
538
+ case 'phase_change':
539
+ case 'phase_transition':
540
+ return 'phase_transition';
541
+ case 'error':
542
+ case 'failure':
543
+ return 'error';
544
+ default:
545
+ return 'state_change';
546
+ }
547
+ }
548
+ /**
549
+ * Map trail status to dashboard status
550
+ */
551
+ function mapEventStatus(status) {
552
+ switch (status?.toLowerCase()) {
553
+ case 'running':
554
+ case 'in_progress':
555
+ case 'active':
556
+ return 'running';
557
+ case 'success':
558
+ case 'completed':
559
+ case 'done':
560
+ return 'success';
561
+ case 'error':
562
+ case 'failed':
563
+ case 'abandoned':
564
+ return 'error';
565
+ case 'pending':
566
+ case 'queued':
567
+ return 'pending';
568
+ default:
569
+ return undefined;
570
+ }
571
+ }
572
+ /**
573
+ * Detect PDERO phase from content
574
+ */
575
+ export function detectPhaseFromContent(content) {
576
+ const lowerContent = content.toLowerCase();
577
+ const phasePatterns = [
578
+ { phase: 'plan', patterns: ['planning', 'analyzing requirements', 'breaking down', 'creating plan', 'task list', 'todo', 'outline'] },
579
+ { phase: 'design', patterns: ['designing', 'architecting', 'choosing pattern', 'interface design', 'schema design', 'architecture'] },
580
+ { phase: 'execute', patterns: ['implementing', 'writing', 'coding', 'building', 'creating file', 'modifying', 'editing'] },
581
+ { phase: 'review', patterns: ['testing', 'reviewing', 'validating', 'checking', 'verifying', 'running tests', 'test passed', 'test failed'] },
582
+ { phase: 'observe', patterns: ['observing', 'monitoring', 'reflecting', 'documenting', 'retrospective', 'learnings', 'summary'] },
583
+ ];
584
+ for (const { phase, patterns } of phasePatterns) {
585
+ for (const pattern of patterns) {
586
+ if (lowerContent.includes(pattern)) {
587
+ return phase;
588
+ }
589
+ }
590
+ }
591
+ return undefined;
592
+ }
593
+ /**
594
+ * All known Claude Code tool names
595
+ */
596
+ const TOOL_NAMES = [
597
+ 'Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep', 'Task', 'TaskOutput',
598
+ 'WebFetch', 'WebSearch', 'NotebookEdit', 'TodoWrite', 'AskUserQuestion',
599
+ 'KillShell', 'EnterPlanMode', 'ExitPlanMode', 'Skill', 'SlashCommand',
600
+ ];
601
+ const TOOL_NAME_PATTERN = TOOL_NAMES.join('|');
602
+ /**
603
+ * Tool call patterns for Claude Code and similar AI CLIs
604
+ */
605
+ const TOOL_PATTERNS = [
606
+ // Claude Code tool invocations (displayed in output with parenthesis/braces)
607
+ new RegExp(`(?:^|\\n)\\s*(?:${TOOL_NAME_PATTERN})\\s*[({]`, 'i'),
608
+ // Tool completion markers (checkmarks, spinners)
609
+ new RegExp(`(?:^|\\n)\\s*(?:✓|✔|⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏)\\s*(${TOOL_NAME_PATTERN})`, 'i'),
610
+ // Function call patterns (explicit mentions)
611
+ new RegExp(`(?:^|\\n)\\s*(?:Calling|Using|Invoking)\\s+(?:tool\\s+)?['"]?(${TOOL_NAME_PATTERN})['"]?`, 'i'),
612
+ // Tool result patterns
613
+ new RegExp(`(?:^|\\n)\\s*(?:Tool result|Result from)\\s*:?\\s*(${TOOL_NAME_PATTERN})`, 'i'),
614
+ ];
615
+ /**
616
+ * Error patterns for detecting failures in output
617
+ * Note: Patterns are ordered from most specific to least specific
618
+ */
619
+ const ERROR_PATTERNS = [
620
+ // JavaScript/TypeScript runtime errors (most specific)
621
+ /(?:^|\n)((?:TypeError|ReferenceError|SyntaxError|RangeError|EvalError|URIError):\s*.+)/i,
622
+ // Named Error with message (e.g., "Error: Something went wrong")
623
+ /(?:^|\n)(Error:\s+.+)/,
624
+ // Failed assertions
625
+ /(?:^|\n)\s*(AssertionError:\s*.+)/i,
626
+ // Test failures (Vitest, Jest patterns)
627
+ /(?:^|\n)\s*(FAIL\s+\S+\.(?:ts|js|tsx|jsx))/i,
628
+ /(?:^|\n)\s*(✗|✘|×)\s+(.+)/,
629
+ // Command/process failures
630
+ /(?:^|\n)\s*(Command failed[^\n]+)/i,
631
+ /(?:^|\n)\s*((?:Exit|exit)\s+code[:\s]+[1-9]\d*)/i,
632
+ /(?:^|\n)\s*(exited with (?:code\s+)?[1-9]\d*)/i,
633
+ // Node.js/system errors
634
+ /(?:^|\n)\s*(EACCES|EPERM|ENOENT|ECONNREFUSED|ETIMEDOUT|ENOTFOUND)(?::\s*.+)?/,
635
+ // Build/compile errors (webpack, tsc, etc.)
636
+ /(?:^|\n)\s*(error TS\d+:\s*.+)/i,
637
+ /(?:^|\n)\s*(error\[\S+\]:\s*.+)/i,
638
+ ];
639
+ /**
640
+ * Warning patterns for detecting potential issues
641
+ */
642
+ const WARNING_PATTERNS = [
643
+ /(?:^|\n)\s*(?:warning|WARN|⚠️?)\s*[:\[]?\s*(.+)/i,
644
+ /(?:^|\n)\s*(?:deprecated|DEPRECATED):\s*(.+)/i,
645
+ ];
646
+ /**
647
+ * Detect tool calls from agent output
648
+ *
649
+ * @example
650
+ * ```typescript
651
+ * const tools = detectToolCalls(output);
652
+ * // Returns: [{ tool: 'Read', args: 'file.ts' }, { tool: 'Bash', status: 'completed' }]
653
+ * ```
654
+ */
655
+ export function detectToolCalls(content) {
656
+ const detected = [];
657
+ const seenTools = new Set();
658
+ const toolNameExtractor = new RegExp(`\\b(${TOOL_NAME_PATTERN})\\b`, 'i');
659
+ for (const pattern of TOOL_PATTERNS) {
660
+ const matches = content.matchAll(new RegExp(pattern.source, 'gi'));
661
+ for (const match of matches) {
662
+ // Extract tool name from the match
663
+ const fullMatch = match[0];
664
+ const toolNameMatch = fullMatch.match(toolNameExtractor);
665
+ if (toolNameMatch) {
666
+ const tool = toolNameMatch[1];
667
+ // Avoid duplicates by position (same tool at same position)
668
+ const key = `${tool}:${match.index}`;
669
+ if (!seenTools.has(key)) {
670
+ seenTools.add(key);
671
+ detected.push({
672
+ tool,
673
+ status: fullMatch.includes('✓') || fullMatch.includes('✔') ? 'completed' : 'started',
674
+ });
675
+ }
676
+ }
677
+ }
678
+ }
679
+ return detected;
680
+ }
681
+ /**
682
+ * Detect errors from agent output
683
+ *
684
+ * @example
685
+ * ```typescript
686
+ * const errors = detectErrors(output);
687
+ * // Returns: [{ type: 'error', message: 'TypeError: Cannot read property...' }]
688
+ * ```
689
+ */
690
+ export function detectErrors(content) {
691
+ const detected = [];
692
+ const seenMessages = new Set();
693
+ // Check for error patterns
694
+ for (const pattern of ERROR_PATTERNS) {
695
+ const matches = content.matchAll(new RegExp(pattern, 'gi'));
696
+ for (const match of matches) {
697
+ const message = match[1] || match[0];
698
+ const cleanMessage = message.trim().slice(0, 200); // Limit length
699
+ if (!seenMessages.has(cleanMessage)) {
700
+ seenMessages.add(cleanMessage);
701
+ detected.push({
702
+ type: 'error',
703
+ message: cleanMessage,
704
+ });
705
+ }
706
+ }
707
+ }
708
+ // Check for warning patterns
709
+ for (const pattern of WARNING_PATTERNS) {
710
+ const matches = content.matchAll(new RegExp(pattern, 'gi'));
711
+ for (const match of matches) {
712
+ const message = match[1] || match[0];
713
+ const cleanMessage = message.trim().slice(0, 200);
714
+ if (!seenMessages.has(cleanMessage)) {
715
+ seenMessages.add(cleanMessage);
716
+ detected.push({
717
+ type: 'warning',
718
+ message: cleanMessage,
719
+ });
720
+ }
721
+ }
722
+ }
723
+ return detected;
724
+ }
725
+ /**
726
+ * TrajectoryIntegration class for managing trajectory state
727
+ *
728
+ * This class enforces trajectory tracking during agent lifecycle:
729
+ * - Auto-starts trajectory when agent is instantiated with a task
730
+ * - Records all inter-agent messages
731
+ * - Auto-detects PDERO phase transitions
732
+ * - Provides lifecycle hooks for tmux/pty wrappers
733
+ */
734
+ export class TrajectoryIntegration {
735
+ projectId;
736
+ agentName;
737
+ trailAvailable = null;
738
+ currentPhase = null;
739
+ trajectoryId = null;
740
+ initialized = false;
741
+ task = null;
742
+ constructor(projectId, agentName) {
743
+ this.projectId = projectId;
744
+ this.agentName = agentName;
745
+ }
746
+ /**
747
+ * Check if trail is available (cached)
748
+ */
749
+ async isAvailable() {
750
+ if (this.trailAvailable === null) {
751
+ this.trailAvailable = await isTrailAvailable();
752
+ }
753
+ return this.trailAvailable;
754
+ }
755
+ /**
756
+ * Check if trail CLI is installed synchronously
757
+ */
758
+ isTrailInstalledSync() {
759
+ try {
760
+ execSync('which trail', { stdio: 'pipe' });
761
+ return true;
762
+ }
763
+ catch {
764
+ return false;
765
+ }
766
+ }
767
+ /**
768
+ * Initialize trajectory tracking for agent lifecycle
769
+ * Called automatically when agent starts with a task
770
+ */
771
+ async initialize(task, taskId, source) {
772
+ if (this.initialized)
773
+ return true;
774
+ if (!(await this.isAvailable())) {
775
+ return false;
776
+ }
777
+ // If task provided, auto-start trajectory
778
+ if (task) {
779
+ const success = await this.start(task, taskId, source);
780
+ if (success) {
781
+ this.initialized = true;
782
+ this.task = task;
783
+ }
784
+ return success;
785
+ }
786
+ this.initialized = true;
787
+ return true;
788
+ }
789
+ /**
790
+ * Start tracking a trajectory
791
+ */
792
+ async start(task, taskId, source) {
793
+ if (!(await this.isAvailable()))
794
+ return false;
795
+ const result = await startTrajectory({
796
+ task,
797
+ taskId,
798
+ source,
799
+ agentName: this.agentName,
800
+ phase: 'plan',
801
+ });
802
+ if (result.success) {
803
+ this.currentPhase = 'plan';
804
+ this.trajectoryId = result.trajectoryId || null;
805
+ this.task = task;
806
+ }
807
+ return result.success;
808
+ }
809
+ /**
810
+ * Check if there's an active trajectory
811
+ */
812
+ hasActiveTrajectory() {
813
+ return this.currentPhase !== null;
814
+ }
815
+ /**
816
+ * Get the current task
817
+ */
818
+ getTask() {
819
+ return this.task;
820
+ }
821
+ /**
822
+ * Get trajectory ID
823
+ */
824
+ getTrajectoryId() {
825
+ return this.trajectoryId;
826
+ }
827
+ /**
828
+ * Record a message
829
+ */
830
+ async message(direction, from, to, body) {
831
+ if (!(await this.isAvailable()))
832
+ return;
833
+ await recordMessage(direction, from, to, body);
834
+ // Check for phase transition based on content
835
+ const detectedPhase = detectPhaseFromContent(body);
836
+ if (detectedPhase && detectedPhase !== this.currentPhase) {
837
+ await this.transition(detectedPhase, 'Auto-detected from message content');
838
+ }
839
+ }
840
+ /**
841
+ * Transition to a new phase
842
+ */
843
+ async transition(phase, reason) {
844
+ if (!(await this.isAvailable()))
845
+ return false;
846
+ if (phase === this.currentPhase)
847
+ return true;
848
+ const result = await transitionPhase(phase, reason, this.agentName);
849
+ if (result.success) {
850
+ this.currentPhase = phase;
851
+ }
852
+ return result.success;
853
+ }
854
+ /**
855
+ * Record a decision
856
+ */
857
+ async decision(choice, options) {
858
+ if (!(await this.isAvailable()))
859
+ return false;
860
+ const result = await recordDecision({
861
+ choice,
862
+ ...options,
863
+ });
864
+ return result.success;
865
+ }
866
+ /**
867
+ * Record an event
868
+ */
869
+ async event(content, type = 'observation') {
870
+ if (!(await this.isAvailable()))
871
+ return false;
872
+ const result = await recordEvent(content, type, this.agentName);
873
+ // Check for phase transition
874
+ const detectedPhase = detectPhaseFromContent(content);
875
+ if (detectedPhase && detectedPhase !== this.currentPhase) {
876
+ await this.transition(detectedPhase, 'Auto-detected from event content');
877
+ }
878
+ return result.success;
879
+ }
880
+ /**
881
+ * Complete the trajectory
882
+ */
883
+ async complete(options) {
884
+ if (!(await this.isAvailable()))
885
+ return false;
886
+ const result = await completeTrajectory(options);
887
+ if (result.success) {
888
+ this.currentPhase = null;
889
+ }
890
+ return result.success;
891
+ }
892
+ /**
893
+ * Abandon the trajectory
894
+ */
895
+ async abandon(reason) {
896
+ if (!(await this.isAvailable()))
897
+ return false;
898
+ const result = await abandonTrajectory(reason);
899
+ if (result.success) {
900
+ this.currentPhase = null;
901
+ }
902
+ return result.success;
903
+ }
904
+ /**
905
+ * Get current phase
906
+ */
907
+ getPhase() {
908
+ return this.currentPhase;
909
+ }
910
+ }
911
+ /**
912
+ * Global trajectory integration instances
913
+ */
914
+ const instances = new Map();
915
+ /**
916
+ * Get or create a TrajectoryIntegration instance
917
+ */
918
+ export function getTrajectoryIntegration(projectId, agentName) {
919
+ const key = `${projectId}:${agentName}`;
920
+ let instance = instances.get(key);
921
+ if (!instance) {
922
+ instance = new TrajectoryIntegration(projectId, agentName);
923
+ instances.set(key, instance);
924
+ }
925
+ return instance;
926
+ }
927
+ /**
928
+ * Generate trail usage instructions for agents
929
+ */
930
+ export function getTrailInstructions() {
931
+ return [
932
+ '📍 TRAJECTORY TRACKING (PDERO Paradigm)',
933
+ '',
934
+ 'You MUST use trail commands to track your work:',
935
+ '',
936
+ 'PHASES: plan → design → execute → review → observe',
937
+ '',
938
+ 'COMMANDS:',
939
+ ' trail start "task" Start trajectory for a task',
940
+ ' trail phase <phase> Transition to new phase',
941
+ ' trail decision "choice" Record key decisions',
942
+ ' trail event "what happened" Log significant events',
943
+ ' trail complete Complete with summary',
944
+ '',
945
+ 'WHEN TO USE:',
946
+ ' - Start: At beginning of any task',
947
+ ' - Phase: When shifting focus (planning→implementing, etc.)',
948
+ ' - Decision: For architecture/approach choices',
949
+ ' - Event: For tool calls, errors, milestones',
950
+ ' - Complete: When task is done',
951
+ '',
952
+ 'Example workflow:',
953
+ ' trail start "Implement auth feature"',
954
+ ' trail phase design',
955
+ ' trail decision "Use JWT" --reasoning "Stateless, scalable"',
956
+ ' trail phase execute',
957
+ ' trail event "Created auth middleware"',
958
+ ' trail phase review',
959
+ ' trail event "All tests passing"',
960
+ ' trail complete --summary "Auth implemented" --confidence 0.9',
961
+ ];
962
+ }
963
+ /**
964
+ * Get a compact trail instruction string for injection
965
+ */
966
+ export function getCompactTrailInstructions() {
967
+ return [
968
+ '[TRAIL] Track work with PDERO: plan→design→execute→review→observe.',
969
+ 'Commands: trail start "task" | trail phase <phase> | trail decision "choice" | trail event "log" | trail complete',
970
+ 'Use trail often to document your thought process.',
971
+ ].join(' ');
972
+ }
973
+ /**
974
+ * Get environment variables for trail CLI
975
+ * If dataDir is not provided, uses config-based storage location
976
+ */
977
+ export function getTrailEnvVars(projectId, agentName, dataDir) {
978
+ // Use config-based path if dataDir not explicitly provided
979
+ const effectiveDataDir = dataDir ?? getPrimaryTrajectoriesDir();
980
+ return {
981
+ TRAJECTORIES_PROJECT: projectId,
982
+ TRAJECTORIES_DATA_DIR: effectiveDataDir,
983
+ TRAJECTORIES_AGENT: agentName,
984
+ TRAIL_AUTO_PHASE: '1', // Enable auto phase detection
985
+ };
986
+ }
987
+ //# sourceMappingURL=integration.js.map