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