@gethmy/mcp 1.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +201 -36
  2. package/dist/cli.js +20938 -20249
  3. package/dist/http.js +1957 -0
  4. package/dist/index.js +17833 -17888
  5. package/dist/lib/__tests__/active-learning.test.js +386 -0
  6. package/dist/lib/__tests__/agent-performance-profiles.test.js +325 -0
  7. package/dist/lib/__tests__/auto-session.test.js +661 -0
  8. package/dist/lib/__tests__/context-assembly.test.js +362 -0
  9. package/dist/lib/__tests__/graph-expansion.test.js +150 -0
  10. package/dist/lib/__tests__/integration-memory-crud.test.js +797 -0
  11. package/dist/lib/__tests__/integration-memory-system.test.js +281 -0
  12. package/dist/lib/__tests__/lifecycle-maintenance.test.js +207 -0
  13. package/dist/lib/__tests__/pattern-detection.test.js +295 -0
  14. package/dist/lib/__tests__/prompt-builder.test.js +418 -0
  15. package/dist/lib/active-learning.js +878 -0
  16. package/dist/lib/api-client.js +548 -0
  17. package/dist/lib/auto-session.js +173 -0
  18. package/dist/lib/cli.js +127 -0
  19. package/dist/lib/config.js +205 -0
  20. package/dist/lib/consolidation.js +243 -0
  21. package/dist/lib/context-assembly.js +606 -0
  22. package/dist/lib/graph-expansion.js +163 -0
  23. package/dist/lib/http.js +174 -0
  24. package/dist/lib/index.js +7 -0
  25. package/dist/lib/lifecycle-maintenance.js +88 -0
  26. package/dist/lib/prompt-builder.js +483 -0
  27. package/dist/lib/remote.js +166 -0
  28. package/dist/lib/server.js +3132 -0
  29. package/dist/lib/tui/agents.js +116 -0
  30. package/dist/lib/tui/docs.js +558 -0
  31. package/dist/lib/tui/setup.js +1068 -0
  32. package/dist/lib/tui/theme.js +95 -0
  33. package/dist/lib/tui/writer.js +200 -0
  34. package/dist/remote.js +34534 -0
  35. package/dist/server.js +31967 -0
  36. package/package.json +20 -7
  37. package/src/__tests__/active-learning.test.ts +483 -0
  38. package/src/__tests__/agent-performance-profiles.test.ts +468 -0
  39. package/src/__tests__/auto-session.test.ts +912 -0
  40. package/src/__tests__/context-assembly.test.ts +506 -0
  41. package/src/__tests__/graph-expansion.test.ts +285 -0
  42. package/src/__tests__/integration-memory-crud.test.ts +948 -0
  43. package/src/__tests__/integration-memory-system.test.ts +321 -0
  44. package/src/__tests__/lifecycle-maintenance.test.ts +238 -0
  45. package/src/__tests__/pattern-detection.test.ts +438 -0
  46. package/src/__tests__/prompt-builder.test.ts +505 -0
  47. package/src/active-learning.ts +1227 -0
  48. package/src/api-client.ts +963 -0
  49. package/src/auto-session.ts +218 -0
  50. package/src/cli.ts +166 -0
  51. package/src/config.ts +285 -0
  52. package/src/consolidation.ts +314 -0
  53. package/src/context-assembly.ts +842 -0
  54. package/src/graph-expansion.ts +234 -0
  55. package/src/http.ts +265 -0
  56. package/src/index.ts +8 -0
  57. package/src/lifecycle-maintenance.ts +120 -0
  58. package/src/prompt-builder.ts +681 -0
  59. package/src/remote.ts +227 -0
  60. package/src/server.ts +3858 -0
  61. package/src/tui/agents.ts +154 -0
  62. package/src/tui/docs.ts +650 -0
  63. package/src/tui/setup.ts +1281 -0
  64. package/src/tui/theme.ts +114 -0
  65. package/src/tui/writer.ts +260 -0
@@ -0,0 +1,681 @@
1
+ /**
2
+ * Prompt Builder for Harmony MCP Server
3
+ *
4
+ * Generates AI-ready prompts from Harmony cards with role-based framing,
5
+ * context extraction, and variant-specific instructions.
6
+ */
7
+
8
+ // Types
9
+ export type PromptVariant = "analysis" | "draft" | "execute";
10
+ export type LabelCategory =
11
+ | "bug"
12
+ | "feature"
13
+ | "design"
14
+ | "review"
15
+ | "onboarding"
16
+ | "epic"
17
+ | "custom";
18
+
19
+ export interface PromptContextOptions {
20
+ includeTitle: boolean;
21
+ includeDescription: boolean;
22
+ includeLabels: boolean;
23
+ includeSubtasks: boolean;
24
+ includeActivity: boolean;
25
+ includeAssignee: boolean;
26
+ includeDueDate: boolean;
27
+ includePriority: boolean;
28
+ includeLinks: boolean;
29
+ includeColumn: boolean;
30
+ }
31
+
32
+ export interface RoleFraming {
33
+ category: LabelCategory;
34
+ role: string;
35
+ perspective: string;
36
+ focus: string[];
37
+ outputSuggestions: string[];
38
+ }
39
+
40
+ export interface GeneratedPrompt {
41
+ prompt: string;
42
+ variant: PromptVariant;
43
+ category: LabelCategory;
44
+ role: string;
45
+ contextSummary: {
46
+ hasDescription: boolean;
47
+ labelCount: number;
48
+ subtaskCount: number;
49
+ completedSubtasks: number;
50
+ linkedCardCount: number;
51
+ memoryCount: number;
52
+ };
53
+ tokenEstimate: number;
54
+ assemblyId?: string;
55
+ }
56
+
57
+ // Label name to category mapping
58
+ const LABEL_CATEGORY_MAP: Record<string, LabelCategory> = {
59
+ bug: "bug",
60
+ fix: "bug",
61
+ hotfix: "bug",
62
+ defect: "bug",
63
+ issue: "bug",
64
+ error: "bug",
65
+ feature: "feature",
66
+ enhancement: "feature",
67
+ improvement: "feature",
68
+ new: "feature",
69
+ design: "design",
70
+ ui: "design",
71
+ ux: "design",
72
+ frontend: "design",
73
+ styling: "design",
74
+ review: "review",
75
+ "code review": "review",
76
+ pr: "review",
77
+ feedback: "review",
78
+ onboarding: "onboarding",
79
+ documentation: "onboarding",
80
+ docs: "onboarding",
81
+ guide: "onboarding",
82
+ tutorial: "onboarding",
83
+ epic: "epic",
84
+ initiative: "epic",
85
+ project: "epic",
86
+ milestone: "epic",
87
+ };
88
+
89
+ // Default role framings
90
+ const DEFAULT_ROLE_FRAMINGS: Record<LabelCategory, RoleFraming> = {
91
+ bug: {
92
+ category: "bug",
93
+ role: "Senior QA Engineer and Software Developer",
94
+ perspective: "You are investigating and fixing a bug report.",
95
+ focus: [
96
+ "Root cause analysis",
97
+ "Steps to reproduce",
98
+ "Impact assessment",
99
+ "Fix implementation",
100
+ "Regression prevention",
101
+ "Test cases to prevent recurrence",
102
+ ],
103
+ outputSuggestions: [
104
+ "Bug triage summary",
105
+ "Root cause explanation",
106
+ "Fix implementation plan",
107
+ "Test cases",
108
+ ],
109
+ },
110
+ feature: {
111
+ category: "feature",
112
+ role: "Product Engineer",
113
+ perspective: "You are implementing a new feature or enhancement.",
114
+ focus: [
115
+ "User requirements",
116
+ "Technical specification",
117
+ "Implementation approach",
118
+ "Edge cases",
119
+ "Acceptance criteria",
120
+ "Integration points",
121
+ ],
122
+ outputSuggestions: [
123
+ "Technical specification",
124
+ "Implementation tasks",
125
+ "Acceptance criteria checklist",
126
+ "API design",
127
+ ],
128
+ },
129
+ design: {
130
+ category: "design",
131
+ role: "UX Designer and Frontend Developer",
132
+ perspective: "You are designing and implementing a user interface.",
133
+ focus: [
134
+ "User experience flow",
135
+ "Visual design consistency",
136
+ "Accessibility (WCAG)",
137
+ "Responsive behavior",
138
+ "Component architecture",
139
+ "Interaction patterns",
140
+ ],
141
+ outputSuggestions: [
142
+ "User flow diagram",
143
+ "Component specifications",
144
+ "Accessibility checklist",
145
+ "Responsive breakpoints",
146
+ ],
147
+ },
148
+ review: {
149
+ category: "review",
150
+ role: "Code Reviewer and Technical Lead",
151
+ perspective:
152
+ "You are reviewing code for quality, correctness, and maintainability.",
153
+ focus: [
154
+ "Code correctness",
155
+ "Performance implications",
156
+ "Security considerations",
157
+ "Testing coverage",
158
+ "Documentation",
159
+ "Best practices adherence",
160
+ ],
161
+ outputSuggestions: [
162
+ "Review checklist",
163
+ "Suggested improvements",
164
+ "Test scenarios",
165
+ "Security audit",
166
+ ],
167
+ },
168
+ onboarding: {
169
+ category: "onboarding",
170
+ role: "Technical Writer and Developer Advocate",
171
+ perspective: "You are creating documentation or onboarding materials.",
172
+ focus: [
173
+ "Clear step-by-step instructions",
174
+ "Prerequisites and setup",
175
+ "Common pitfalls",
176
+ "Examples and use cases",
177
+ "Troubleshooting guide",
178
+ "Related resources",
179
+ ],
180
+ outputSuggestions: [
181
+ "Getting started guide",
182
+ "Step-by-step tutorial",
183
+ "FAQ section",
184
+ "Troubleshooting guide",
185
+ ],
186
+ },
187
+ epic: {
188
+ category: "epic",
189
+ role: "Technical Project Manager and Architect",
190
+ perspective: "You are planning and coordinating a large initiative.",
191
+ focus: [
192
+ "Scope definition",
193
+ "Task breakdown",
194
+ "Dependencies",
195
+ "Risk assessment",
196
+ "Timeline considerations",
197
+ "Success metrics",
198
+ ],
199
+ outputSuggestions: [
200
+ "Epic breakdown into stories",
201
+ "Dependency graph",
202
+ "Risk mitigation plan",
203
+ "Success criteria",
204
+ ],
205
+ },
206
+ custom: {
207
+ category: "custom",
208
+ role: "Software Engineer",
209
+ perspective: "You are working on a software task.",
210
+ focus: [
211
+ "Understanding requirements",
212
+ "Implementation approach",
213
+ "Quality considerations",
214
+ "Testing strategy",
215
+ ],
216
+ outputSuggestions: [
217
+ "Implementation plan",
218
+ "Technical notes",
219
+ "Task checklist",
220
+ ],
221
+ },
222
+ };
223
+
224
+ // Variant-specific instructions
225
+ const VARIANT_INSTRUCTIONS: Record<PromptVariant, string> = {
226
+ analysis: `ANALYSIS MODE: Analyze this task thoroughly. Identify requirements, constraints, edge cases, and potential challenges. Do NOT implement anything yet - focus on understanding and planning.`,
227
+ draft: `DRAFT MODE: Create a detailed implementation plan with code structure, key decisions, and approach. Include pseudocode or skeleton code where helpful. This is for review before full implementation.`,
228
+ execute: `EXECUTE MODE: Implement this task completely. Write production-ready code following best practices. Include necessary tests and documentation.`,
229
+ };
230
+
231
+ /**
232
+ * Infer category from labels
233
+ */
234
+ export function inferCategoryFromLabels(
235
+ labels: Array<{ name: string }>,
236
+ ): LabelCategory {
237
+ for (const label of labels) {
238
+ const normalizedName = label.name.toLowerCase().trim();
239
+ if (LABEL_CATEGORY_MAP[normalizedName]) {
240
+ return LABEL_CATEGORY_MAP[normalizedName];
241
+ }
242
+ for (const [key, category] of Object.entries(LABEL_CATEGORY_MAP)) {
243
+ if (normalizedName.includes(key) || key.includes(normalizedName)) {
244
+ return category;
245
+ }
246
+ }
247
+ }
248
+ return "custom";
249
+ }
250
+
251
+ /**
252
+ * Get role framing for a category
253
+ */
254
+ export function getRoleFraming(category: LabelCategory): RoleFraming {
255
+ return DEFAULT_ROLE_FRAMINGS[category];
256
+ }
257
+
258
+ /**
259
+ * Estimate token count (rough approximation: 1 token per 4 chars)
260
+ */
261
+ function estimateTokens(text: string): number {
262
+ return Math.ceil(text.length / 4);
263
+ }
264
+
265
+ /**
266
+ * Format subtasks for prompt
267
+ */
268
+ function formatSubtasks(
269
+ subtasks: Array<{ title: string; completed: boolean }>,
270
+ ): string {
271
+ if (subtasks.length === 0) return "";
272
+ const completed = subtasks.filter((s) => s.completed).length;
273
+ const lines = subtasks.map(
274
+ (s) => ` ${s.completed ? "[x]" : "[ ]"} ${s.title}`,
275
+ );
276
+ return `\n## Subtasks (${completed}/${subtasks.length} completed)\n${lines.join("\n")}`;
277
+ }
278
+
279
+ /**
280
+ * Format labels for prompt
281
+ */
282
+ function formatLabels(labels: Array<{ name: string }>): string {
283
+ if (labels.length === 0) return "";
284
+ return `\n**Labels:** ${labels.map((l) => l.name).join(", ")}`;
285
+ }
286
+
287
+ /**
288
+ * Format linked cards for prompt
289
+ */
290
+ function formatLinkedCards(
291
+ links: Array<{
292
+ target_card: { short_id: number; title: string };
293
+ display_type: string;
294
+ direction: "outgoing" | "incoming";
295
+ }>,
296
+ ): string {
297
+ if (!links || links.length === 0) return "";
298
+ const lines = links.map((link) => {
299
+ const prefix = link.direction === "outgoing" ? "->" : "<-";
300
+ return ` ${prefix} #${link.target_card.short_id}: ${link.target_card.title} (${link.display_type})`;
301
+ });
302
+ return `\n## Related Cards\n${lines.join("\n")}`;
303
+ }
304
+
305
+ export interface CardData {
306
+ id: string;
307
+ short_id: number;
308
+ title: string;
309
+ description?: string | null;
310
+ priority: string;
311
+ due_date?: string | null;
312
+ done: boolean;
313
+ labels?: Array<{ name: string; color: string }>;
314
+ subtasks?: Array<{ title: string; completed: boolean }>;
315
+ links?: Array<{
316
+ target_card: { short_id: number; title: string };
317
+ display_type: string;
318
+ direction: "outgoing" | "incoming";
319
+ }>;
320
+ assignee?: { full_name?: string; email: string } | null;
321
+ }
322
+
323
+ export interface ColumnData {
324
+ name: string;
325
+ }
326
+
327
+ export interface MemoryData {
328
+ id: string;
329
+ type: string;
330
+ title: string;
331
+ content: string;
332
+ confidence: number;
333
+ tags: string[];
334
+ }
335
+
336
+ export interface GeneratePromptOptions {
337
+ card: CardData;
338
+ column?: ColumnData | null;
339
+ variant: PromptVariant;
340
+ contextOptions?: Partial<PromptContextOptions>;
341
+ customConstraints?: string;
342
+ memories?: MemoryData[];
343
+ /** Pre-assembled context string from context assembly engine */
344
+ assembledContext?: string;
345
+ /** Assembly ID for manifest tracking */
346
+ assemblyId?: string;
347
+ }
348
+
349
+ /**
350
+ * Generate a prompt from a card
351
+ */
352
+ export function generatePrompt(
353
+ options: GeneratePromptOptions,
354
+ ): GeneratedPrompt {
355
+ const {
356
+ card,
357
+ column,
358
+ variant,
359
+ customConstraints,
360
+ memories,
361
+ assembledContext,
362
+ assemblyId,
363
+ } = options;
364
+
365
+ // Merge context options with defaults
366
+ const contextOpts: PromptContextOptions = {
367
+ includeTitle: true,
368
+ includeDescription: true,
369
+ includeLabels: true,
370
+ includeSubtasks: true,
371
+ includeActivity: false,
372
+ includeAssignee: true,
373
+ includeDueDate: true,
374
+ includePriority: true,
375
+ includeLinks: true,
376
+ includeColumn: true,
377
+ ...options.contextOptions,
378
+ };
379
+
380
+ const labels = card.labels || [];
381
+ const subtasks = card.subtasks || [];
382
+ const links = card.links || [];
383
+
384
+ const category = inferCategoryFromLabels(labels);
385
+ const roleFraming = getRoleFraming(category);
386
+
387
+ // Build prompt sections
388
+ const sections: string[] = [];
389
+
390
+ // Role and perspective
391
+ sections.push(`# Role: ${roleFraming.role}\n`);
392
+ sections.push(roleFraming.perspective);
393
+ sections.push("");
394
+
395
+ // Variant instruction
396
+ sections.push(VARIANT_INSTRUCTIONS[variant]);
397
+ sections.push("");
398
+
399
+ // Task header
400
+ sections.push(`# Task: ${card.title}`);
401
+ if (contextOpts.includeColumn && column) {
402
+ sections.push(`**Status:** ${column.name}`);
403
+ }
404
+ if (contextOpts.includePriority) {
405
+ sections.push(`**Priority:** ${card.priority}`);
406
+ }
407
+ if (contextOpts.includeDueDate && card.due_date) {
408
+ sections.push(`**Due:** ${card.due_date}`);
409
+ }
410
+ if (contextOpts.includeAssignee && card.assignee) {
411
+ sections.push(
412
+ `**Assignee:** ${card.assignee.full_name || card.assignee.email}`,
413
+ );
414
+ }
415
+
416
+ // Labels
417
+ if (contextOpts.includeLabels && labels.length > 0) {
418
+ sections.push(formatLabels(labels));
419
+ }
420
+
421
+ // Description
422
+ if (contextOpts.includeDescription && card.description) {
423
+ sections.push(`\n## Description\n${card.description}`);
424
+ }
425
+
426
+ // Subtasks
427
+ if (contextOpts.includeSubtasks && subtasks.length > 0) {
428
+ sections.push(formatSubtasks(subtasks));
429
+ }
430
+
431
+ // Linked cards
432
+ if (contextOpts.includeLinks && links.length > 0) {
433
+ sections.push(formatLinkedCards(links));
434
+ }
435
+
436
+ // Focus areas
437
+ sections.push(`\n## Focus Areas`);
438
+ roleFraming.focus.forEach((f) => {
439
+ sections.push(`- ${f}`);
440
+ });
441
+
442
+ // Output suggestions
443
+ sections.push(`\n## Suggested Outputs`);
444
+ roleFraming.outputSuggestions.forEach((s) => {
445
+ sections.push(`- ${s}`);
446
+ });
447
+
448
+ // Relevant memories from knowledge graph
449
+ if (assembledContext) {
450
+ // Use pre-assembled context from context assembly engine
451
+ sections.push(`\n${assembledContext}`);
452
+ } else if (memories && memories.length > 0) {
453
+ // Fallback: legacy memory format
454
+ sections.push(`\n## Relevant Memories`);
455
+ sections.push(
456
+ `*${memories.length} memories recalled from knowledge graph:*`,
457
+ );
458
+ for (const memory of memories) {
459
+ const tags = memory.tags.length > 0 ? ` [${memory.tags.join(", ")}]` : "";
460
+ sections.push(
461
+ `\n### ${memory.title} (${memory.type}, confidence: ${memory.confidence})${tags}`,
462
+ );
463
+ sections.push(memory.content);
464
+ }
465
+ }
466
+
467
+ // "One Thing" synthesis — highest-leverage next action
468
+ const oneThingLine = synthesizeOneThing(
469
+ card,
470
+ subtasks,
471
+ links,
472
+ assembledContext,
473
+ );
474
+ if (oneThingLine) {
475
+ sections.push(`\n## Recommended Next Step\n${oneThingLine}`);
476
+ }
477
+
478
+ // Progress tracking (execute variant only)
479
+ if (variant === "execute") {
480
+ sections.push(`\n## Progress Tracking
481
+ Update your progress by calling \`harmony_update_agent_progress\` with \`currentTask\` describing what you're doing now:
482
+ - After exploring the codebase and understanding requirements (~20%)
483
+ - When you start implementing changes (~50%)
484
+ - When you move to testing or verification (~80%)
485
+ - When done, before ending the session (100%)
486
+
487
+ Keep \`currentTask\` specific (e.g., "Refactoring auth middleware" not "Working on card").`);
488
+ }
489
+
490
+ // Custom constraints
491
+ if (customConstraints) {
492
+ sections.push(`\n## Additional Instructions\n${customConstraints}`);
493
+ }
494
+
495
+ // Card reference footer
496
+ sections.push(
497
+ `\n---\n*Card #${card.short_id} | Generated for ${variant} mode*`,
498
+ );
499
+
500
+ const prompt = sections.join("\n");
501
+
502
+ const memoryCount = assembledContext
503
+ ? (assembledContext.match(/^### /gm) || []).length
504
+ : memories?.length || 0;
505
+
506
+ return {
507
+ prompt,
508
+ variant,
509
+ category,
510
+ role: roleFraming.role,
511
+ contextSummary: {
512
+ hasDescription: !!card.description,
513
+ labelCount: labels.length,
514
+ subtaskCount: subtasks.length,
515
+ completedSubtasks: subtasks.filter((s) => s.completed).length,
516
+ linkedCardCount: links.length,
517
+ memoryCount,
518
+ },
519
+ tokenEstimate: estimateTokens(prompt),
520
+ ...(assemblyId && { assemblyId }),
521
+ };
522
+ }
523
+
524
+ /**
525
+ * Extract session insights from assembled context string.
526
+ * Parses session summaries, blockers, and progress data.
527
+ */
528
+ function extractSessionInsights(assembledContext: string): {
529
+ lastSessionStatus: "completed" | "paused" | null;
530
+ lastSessionTask: string | null;
531
+ lastSessionProgress: number | null;
532
+ blockers: string[];
533
+ procedureNextStep: string | null;
534
+ } {
535
+ const result = {
536
+ lastSessionStatus: null as "completed" | "paused" | null,
537
+ lastSessionTask: null as string | null,
538
+ lastSessionProgress: null as number | null,
539
+ blockers: [] as string[],
540
+ procedureNextStep: null as string | null,
541
+ };
542
+
543
+ // Find the most recent session summary with status
544
+ const sessionMatches = assembledContext.match(
545
+ /### Session:.*?\n([\s\S]*?)(?=\n###|\n## |\n---|\n\*Assembly|$)/g,
546
+ );
547
+ if (sessionMatches && sessionMatches.length > 0) {
548
+ const latest = sessionMatches[0];
549
+ if (/Completed work on/i.test(latest)) {
550
+ result.lastSessionStatus = "completed";
551
+ } else if (/Paused work on|status:\s*paused/i.test(latest)) {
552
+ result.lastSessionStatus = "paused";
553
+ }
554
+ const taskMatch = latest.match(/Final task:\s*(.+)/);
555
+ if (taskMatch) result.lastSessionTask = taskMatch[1].trim();
556
+ const progressMatch = latest.match(/Progress:\s*(\d+)%/);
557
+ if (progressMatch)
558
+ result.lastSessionProgress = parseInt(progressMatch[1], 10);
559
+ }
560
+
561
+ // Extract blockers from context
562
+ const blockerMatches = assembledContext.match(
563
+ /(?:blocker|blocked by|blocking):\s*(.+)/gi,
564
+ );
565
+ if (blockerMatches) {
566
+ result.blockers = blockerMatches.map((m) =>
567
+ m.replace(/(?:blocker|blocked by|blocking):\s*/i, "").trim(),
568
+ );
569
+ }
570
+
571
+ // Extract next procedure step (first uncompleted step)
572
+ const stepMatches = assembledContext.match(
573
+ /^\d+\.\s+(?!.*\*\*\[key step\]\*\*.*✓)(.+?)(?:\s*\*\*\[key step\]\*\*)?$/gm,
574
+ );
575
+ if (stepMatches && stepMatches.length > 0) {
576
+ result.procedureNextStep = stepMatches[0]
577
+ .replace(/^\d+\.\s+/, "")
578
+ .replace(/\s*\*\*\[key step\]\*\*.*$/, "")
579
+ .trim();
580
+ }
581
+
582
+ return result;
583
+ }
584
+
585
+ /**
586
+ * Synthesize the single highest-leverage next action from card state
587
+ * and assembled context (session history, blockers, procedures).
588
+ * Inspired by ArtemXTech's "One Thing" pattern in /recall.
589
+ */
590
+ function synthesizeOneThing(
591
+ card: CardData,
592
+ subtasks: Array<{ title: string; completed: boolean }>,
593
+ links: Array<{
594
+ target_card: { short_id: number; title: string };
595
+ display_type: string;
596
+ direction: "outgoing" | "incoming";
597
+ }>,
598
+ assembledContext?: string,
599
+ ): string | null {
600
+ // Priority 1: Card is already done
601
+ if (card.done) return null;
602
+
603
+ // Priority 2: Blocked by another card (via links)
604
+ const blockers = links.filter(
605
+ (l) => l.display_type === "is_blocked_by" && l.direction === "incoming",
606
+ );
607
+ if (blockers.length > 0) {
608
+ const blocker = blockers[0];
609
+ return `Unblock first: resolve #${blocker.target_card.short_id} "${blocker.target_card.title}" which is blocking this card.`;
610
+ }
611
+
612
+ // Extract session insights from assembled context
613
+ const session = assembledContext
614
+ ? extractSessionInsights(assembledContext)
615
+ : null;
616
+
617
+ // Priority 3: Blockers detected in session context
618
+ if (session?.blockers && session.blockers.length > 0) {
619
+ return `Resolve blocker: ${session.blockers[0]}`;
620
+ }
621
+
622
+ // Priority 4: Previous session was paused — resume where it left off
623
+ if (session?.lastSessionStatus === "paused" && session.lastSessionTask) {
624
+ const progress = session.lastSessionProgress
625
+ ? ` (was ${session.lastSessionProgress}% complete)`
626
+ : "";
627
+ return `Resume previous session${progress}: "${session.lastSessionTask}".`;
628
+ }
629
+
630
+ // Priority 5: Has subtasks — find the first incomplete one
631
+ if (subtasks.length > 0) {
632
+ const completed = subtasks.filter((s) => s.completed).length;
633
+ if (completed === subtasks.length) {
634
+ return "All subtasks completed. Review the work and mark the card as done.";
635
+ }
636
+ const nextSubtask = subtasks.find((s) => !s.completed);
637
+ if (nextSubtask) {
638
+ return `Work on next subtask: "${nextSubtask.title}" (${completed}/${subtasks.length} done).`;
639
+ }
640
+ }
641
+
642
+ // Priority 6: Procedure has a next step
643
+ if (session?.procedureNextStep) {
644
+ return `Follow procedure: ${session.procedureNextStep}`;
645
+ }
646
+
647
+ // Priority 7: Previous session completed — build on it
648
+ if (session?.lastSessionStatus === "completed" && session.lastSessionTask) {
649
+ return `Previous session completed ("${session.lastSessionTask}"). Review results and continue with remaining work.`;
650
+ }
651
+
652
+ // Priority 8: High/urgent priority with due date
653
+ if (
654
+ card.due_date &&
655
+ (card.priority === "urgent" || card.priority === "high")
656
+ ) {
657
+ return `High-priority task with deadline ${card.due_date}. Start implementation immediately.`;
658
+ }
659
+
660
+ // Priority 9: Has description — start working
661
+ if (card.description) {
662
+ return "Analyze the description, identify the approach, and begin implementation.";
663
+ }
664
+
665
+ // Fallback
666
+ return null;
667
+ }
668
+
669
+ /**
670
+ * Get all available categories
671
+ */
672
+ export function getAvailableCategories(): LabelCategory[] {
673
+ return ["bug", "feature", "design", "review", "onboarding", "epic", "custom"];
674
+ }
675
+
676
+ /**
677
+ * Get all available variants
678
+ */
679
+ export function getAvailableVariants(): PromptVariant[] {
680
+ return ["analysis", "draft", "execute"];
681
+ }