mcp-ticketer 0.3.5__py3-none-any.whl → 0.12.0__py3-none-any.whl

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.

Potentially problematic release.


This version of mcp-ticketer might be problematic. Click here for more details.

Files changed (84) hide show
  1. mcp_ticketer/__version__.py +3 -3
  2. mcp_ticketer/adapters/__init__.py +2 -0
  3. mcp_ticketer/adapters/aitrackdown.py +263 -14
  4. mcp_ticketer/adapters/asana/__init__.py +15 -0
  5. mcp_ticketer/adapters/asana/adapter.py +1308 -0
  6. mcp_ticketer/adapters/asana/client.py +292 -0
  7. mcp_ticketer/adapters/asana/mappers.py +334 -0
  8. mcp_ticketer/adapters/asana/types.py +146 -0
  9. mcp_ticketer/adapters/github.py +326 -109
  10. mcp_ticketer/adapters/hybrid.py +11 -11
  11. mcp_ticketer/adapters/jira.py +271 -25
  12. mcp_ticketer/adapters/linear/adapter.py +693 -39
  13. mcp_ticketer/adapters/linear/client.py +61 -9
  14. mcp_ticketer/adapters/linear/mappers.py +9 -3
  15. mcp_ticketer/adapters/linear/queries.py +9 -7
  16. mcp_ticketer/cache/memory.py +9 -8
  17. mcp_ticketer/cli/adapter_diagnostics.py +1 -1
  18. mcp_ticketer/cli/auggie_configure.py +104 -15
  19. mcp_ticketer/cli/codex_configure.py +188 -32
  20. mcp_ticketer/cli/configure.py +37 -48
  21. mcp_ticketer/cli/diagnostics.py +20 -18
  22. mcp_ticketer/cli/discover.py +292 -26
  23. mcp_ticketer/cli/gemini_configure.py +107 -26
  24. mcp_ticketer/cli/instruction_commands.py +429 -0
  25. mcp_ticketer/cli/linear_commands.py +105 -22
  26. mcp_ticketer/cli/main.py +1830 -435
  27. mcp_ticketer/cli/mcp_configure.py +296 -89
  28. mcp_ticketer/cli/migrate_config.py +12 -8
  29. mcp_ticketer/cli/platform_commands.py +123 -0
  30. mcp_ticketer/cli/platform_detection.py +412 -0
  31. mcp_ticketer/cli/python_detection.py +126 -0
  32. mcp_ticketer/cli/queue_commands.py +15 -15
  33. mcp_ticketer/cli/simple_health.py +1 -1
  34. mcp_ticketer/cli/ticket_commands.py +773 -0
  35. mcp_ticketer/cli/update_checker.py +313 -0
  36. mcp_ticketer/cli/utils.py +67 -62
  37. mcp_ticketer/core/__init__.py +14 -1
  38. mcp_ticketer/core/adapter.py +84 -15
  39. mcp_ticketer/core/config.py +44 -39
  40. mcp_ticketer/core/env_discovery.py +42 -12
  41. mcp_ticketer/core/env_loader.py +15 -14
  42. mcp_ticketer/core/exceptions.py +3 -3
  43. mcp_ticketer/core/http_client.py +26 -26
  44. mcp_ticketer/core/instructions.py +405 -0
  45. mcp_ticketer/core/mappers.py +11 -11
  46. mcp_ticketer/core/models.py +50 -20
  47. mcp_ticketer/core/onepassword_secrets.py +379 -0
  48. mcp_ticketer/core/project_config.py +57 -35
  49. mcp_ticketer/core/registry.py +3 -3
  50. mcp_ticketer/defaults/ticket_instructions.md +644 -0
  51. mcp_ticketer/mcp/__init__.py +29 -1
  52. mcp_ticketer/mcp/__main__.py +60 -0
  53. mcp_ticketer/mcp/server/__init__.py +25 -0
  54. mcp_ticketer/mcp/server/__main__.py +60 -0
  55. mcp_ticketer/mcp/{dto.py → server/dto.py} +32 -32
  56. mcp_ticketer/mcp/{server.py → server/main.py} +127 -74
  57. mcp_ticketer/mcp/{response_builder.py → server/response_builder.py} +2 -2
  58. mcp_ticketer/mcp/server/server_sdk.py +93 -0
  59. mcp_ticketer/mcp/server/tools/__init__.py +47 -0
  60. mcp_ticketer/mcp/server/tools/attachment_tools.py +226 -0
  61. mcp_ticketer/mcp/server/tools/bulk_tools.py +273 -0
  62. mcp_ticketer/mcp/server/tools/comment_tools.py +90 -0
  63. mcp_ticketer/mcp/server/tools/config_tools.py +381 -0
  64. mcp_ticketer/mcp/server/tools/hierarchy_tools.py +532 -0
  65. mcp_ticketer/mcp/server/tools/instruction_tools.py +293 -0
  66. mcp_ticketer/mcp/server/tools/pr_tools.py +154 -0
  67. mcp_ticketer/mcp/server/tools/search_tools.py +206 -0
  68. mcp_ticketer/mcp/server/tools/ticket_tools.py +430 -0
  69. mcp_ticketer/mcp/server/tools/user_ticket_tools.py +382 -0
  70. mcp_ticketer/queue/__init__.py +1 -0
  71. mcp_ticketer/queue/health_monitor.py +5 -4
  72. mcp_ticketer/queue/manager.py +15 -51
  73. mcp_ticketer/queue/queue.py +19 -19
  74. mcp_ticketer/queue/run_worker.py +1 -1
  75. mcp_ticketer/queue/ticket_registry.py +14 -14
  76. mcp_ticketer/queue/worker.py +16 -14
  77. {mcp_ticketer-0.3.5.dist-info → mcp_ticketer-0.12.0.dist-info}/METADATA +168 -32
  78. mcp_ticketer-0.12.0.dist-info/RECORD +91 -0
  79. mcp_ticketer-0.3.5.dist-info/RECORD +0 -62
  80. /mcp_ticketer/mcp/{constants.py → server/constants.py} +0 -0
  81. {mcp_ticketer-0.3.5.dist-info → mcp_ticketer-0.12.0.dist-info}/WHEEL +0 -0
  82. {mcp_ticketer-0.3.5.dist-info → mcp_ticketer-0.12.0.dist-info}/entry_points.txt +0 -0
  83. {mcp_ticketer-0.3.5.dist-info → mcp_ticketer-0.12.0.dist-info}/licenses/LICENSE +0 -0
  84. {mcp_ticketer-0.3.5.dist-info → mcp_ticketer-0.12.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,773 @@
1
+ """Ticket management commands."""
2
+
3
+ import asyncio
4
+ import json
5
+ import os
6
+ from enum import Enum
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import typer
11
+ from rich.console import Console
12
+ from rich.table import Table
13
+
14
+ from ..core import AdapterRegistry, Priority, TicketState
15
+ from ..core.models import Comment, SearchQuery
16
+ from ..queue import Queue, QueueStatus, WorkerManager
17
+ from ..queue.health_monitor import HealthStatus, QueueHealthMonitor
18
+ from ..queue.ticket_registry import TicketRegistry
19
+
20
+
21
+ # Moved from main.py to avoid circular import
22
+ class AdapterType(str, Enum):
23
+ """Available adapter types."""
24
+
25
+ AITRACKDOWN = "aitrackdown"
26
+ LINEAR = "linear"
27
+ JIRA = "jira"
28
+ GITHUB = "github"
29
+
30
+
31
+ app = typer.Typer(
32
+ name="ticket",
33
+ help="Ticket management operations (create, list, update, search, etc.)",
34
+ )
35
+ console = Console()
36
+
37
+
38
+ # Configuration functions (moved from main.py to avoid circular import)
39
+ def load_config(project_dir: Path | None = None) -> dict:
40
+ """Load configuration from project-local config file."""
41
+ import logging
42
+
43
+ logger = logging.getLogger(__name__)
44
+ base_dir = project_dir or Path.cwd()
45
+ project_config = base_dir / ".mcp-ticketer" / "config.json"
46
+
47
+ if project_config.exists():
48
+ try:
49
+ with open(project_config) as f:
50
+ config = json.load(f)
51
+ logger.info(f"Loaded configuration from: {project_config}")
52
+ return config
53
+ except (OSError, json.JSONDecodeError) as e:
54
+ logger.warning(f"Could not load project config: {e}, using defaults")
55
+ console.print(
56
+ f"[yellow]Warning: Could not load project config: {e}[/yellow]"
57
+ )
58
+
59
+ logger.info("No project-local config found, defaulting to aitrackdown adapter")
60
+ return {"adapter": "aitrackdown", "config": {"base_path": ".aitrackdown"}}
61
+
62
+
63
+ def save_config(config: dict) -> None:
64
+ """Save configuration to project-local config file."""
65
+ import logging
66
+
67
+ logger = logging.getLogger(__name__)
68
+ project_config = Path.cwd() / ".mcp-ticketer" / "config.json"
69
+ project_config.parent.mkdir(parents=True, exist_ok=True)
70
+ with open(project_config, "w") as f:
71
+ json.dump(config, f, indent=2)
72
+ logger.info(f"Saved configuration to: {project_config}")
73
+
74
+
75
+ def get_adapter(
76
+ override_adapter: str | None = None, override_config: dict | None = None
77
+ ) -> Any:
78
+ """Get configured adapter instance."""
79
+ config = load_config()
80
+
81
+ if override_adapter:
82
+ adapter_type = override_adapter
83
+ adapters_config = config.get("adapters", {})
84
+ adapter_config = adapters_config.get(adapter_type, {})
85
+ if override_config:
86
+ adapter_config.update(override_config)
87
+ else:
88
+ adapter_type = config.get("default_adapter", "aitrackdown")
89
+ adapters_config = config.get("adapters", {})
90
+ adapter_config = adapters_config.get(adapter_type, {})
91
+
92
+ if not adapter_config and "config" in config:
93
+ adapter_config = config["config"]
94
+
95
+ # Add environment variables for authentication
96
+ if adapter_type == "linear":
97
+ if not adapter_config.get("api_key"):
98
+ adapter_config["api_key"] = os.getenv("LINEAR_API_KEY")
99
+ elif adapter_type == "github":
100
+ if not adapter_config.get("api_key") and not adapter_config.get("token"):
101
+ adapter_config["api_key"] = os.getenv("GITHUB_TOKEN")
102
+ elif adapter_type == "jira":
103
+ if not adapter_config.get("api_token"):
104
+ adapter_config["api_token"] = os.getenv("JIRA_ACCESS_TOKEN")
105
+ if not adapter_config.get("email"):
106
+ adapter_config["email"] = os.getenv("JIRA_ACCESS_USER")
107
+
108
+ return AdapterRegistry.get_adapter(adapter_type, adapter_config)
109
+
110
+
111
+ def _discover_from_env_files() -> str | None:
112
+ """Discover adapter configuration from .env or .env.local files.
113
+
114
+ Returns:
115
+ Adapter name if discovered, None otherwise
116
+
117
+ """
118
+ import logging
119
+ from pathlib import Path
120
+
121
+ logger = logging.getLogger(__name__)
122
+
123
+ # Check .env.local first, then .env
124
+ env_files = [".env.local", ".env"]
125
+
126
+ for env_file in env_files:
127
+ env_path = Path.cwd() / env_file
128
+ if env_path.exists():
129
+ try:
130
+ # Simple .env parsing (key=value format)
131
+ env_vars = {}
132
+ with open(env_path) as f:
133
+ for line in f:
134
+ line = line.strip()
135
+ if line and not line.startswith("#") and "=" in line:
136
+ key, value = line.split("=", 1)
137
+ env_vars[key.strip()] = value.strip().strip("\"'")
138
+
139
+ # Check for adapter-specific variables
140
+ if env_vars.get("LINEAR_API_KEY"):
141
+ logger.info(f"Discovered Linear configuration in {env_file}")
142
+ return "linear"
143
+ elif env_vars.get("GITHUB_TOKEN"):
144
+ logger.info(f"Discovered GitHub configuration in {env_file}")
145
+ return "github"
146
+ elif env_vars.get("JIRA_SERVER"):
147
+ logger.info(f"Discovered JIRA configuration in {env_file}")
148
+ return "jira"
149
+
150
+ except Exception as e:
151
+ logger.warning(f"Could not read {env_file}: {e}")
152
+
153
+ return None
154
+
155
+
156
+ def _save_adapter_to_config(adapter_name: str) -> None:
157
+ """Save adapter configuration to config file.
158
+
159
+ Args:
160
+ adapter_name: Name of the adapter to save as default
161
+
162
+ """
163
+ import logging
164
+
165
+ from .main import save_config
166
+
167
+ logger = logging.getLogger(__name__)
168
+
169
+ try:
170
+ config = load_config()
171
+ config["default_adapter"] = adapter_name
172
+
173
+ # Ensure adapters section exists
174
+ if "adapters" not in config:
175
+ config["adapters"] = {}
176
+
177
+ # Add basic adapter config if not exists
178
+ if adapter_name not in config["adapters"]:
179
+ if adapter_name == "aitrackdown":
180
+ config["adapters"][adapter_name] = {"base_path": ".aitrackdown"}
181
+ else:
182
+ config["adapters"][adapter_name] = {"type": adapter_name}
183
+
184
+ save_config(config)
185
+ logger.info(f"Saved {adapter_name} as default adapter")
186
+
187
+ except Exception as e:
188
+ logger.warning(f"Could not save adapter configuration: {e}")
189
+
190
+
191
+ @app.command()
192
+ def create(
193
+ title: str = typer.Argument(..., help="Ticket title"),
194
+ description: str | None = typer.Option(
195
+ None, "--description", "-d", help="Ticket description"
196
+ ),
197
+ priority: Priority = typer.Option(
198
+ Priority.MEDIUM, "--priority", "-p", help="Priority level"
199
+ ),
200
+ tags: list[str] | None = typer.Option(
201
+ None, "--tag", "-t", help="Tags (can be specified multiple times)"
202
+ ),
203
+ assignee: str | None = typer.Option(
204
+ None, "--assignee", "-a", help="Assignee username"
205
+ ),
206
+ project: str | None = typer.Option(
207
+ None,
208
+ "--project",
209
+ help="Parent project/epic ID (synonym for --epic)",
210
+ ),
211
+ epic: str | None = typer.Option(
212
+ None,
213
+ "--epic",
214
+ help="Parent epic/project ID (synonym for --project)",
215
+ ),
216
+ adapter: AdapterType | None = typer.Option(
217
+ None, "--adapter", help="Override default adapter"
218
+ ),
219
+ ) -> None:
220
+ """Create a new ticket with comprehensive health checks."""
221
+ # IMMEDIATE HEALTH CHECK - Critical for reliability
222
+ health_monitor = QueueHealthMonitor()
223
+ health = health_monitor.check_health()
224
+
225
+ # Display health status
226
+ if health["status"] == HealthStatus.CRITICAL:
227
+ console.print("[red]🚨 CRITICAL: Queue system has serious issues![/red]")
228
+ for alert in health["alerts"]:
229
+ if alert["level"] == "critical":
230
+ console.print(f"[red] • {alert['message']}[/red]")
231
+
232
+ # Attempt auto-repair
233
+ console.print("[yellow]Attempting automatic repair...[/yellow]")
234
+ repair_result = health_monitor.auto_repair()
235
+
236
+ if repair_result["actions_taken"]:
237
+ for action in repair_result["actions_taken"]:
238
+ console.print(f"[yellow] ✓ {action}[/yellow]")
239
+
240
+ # Re-check health after repair
241
+ health = health_monitor.check_health()
242
+ if health["status"] == HealthStatus.CRITICAL:
243
+ console.print(
244
+ "[red]❌ Auto-repair failed. Manual intervention required.[/red]"
245
+ )
246
+ console.print(
247
+ "[red]Cannot safely create ticket. Please check system status.[/red]"
248
+ )
249
+ raise typer.Exit(1) from None
250
+ else:
251
+ console.print(
252
+ "[green]✓ Auto-repair successful. Proceeding with ticket creation.[/green]"
253
+ )
254
+ else:
255
+ console.print(
256
+ "[red]❌ No repair actions available. Manual intervention required.[/red]"
257
+ )
258
+ raise typer.Exit(1) from None
259
+
260
+ elif health["status"] == HealthStatus.WARNING:
261
+ console.print("[yellow]⚠️ Warning: Queue system has minor issues[/yellow]")
262
+ for alert in health["alerts"]:
263
+ if alert["level"] == "warning":
264
+ console.print(f"[yellow] • {alert['message']}[/yellow]")
265
+ console.print("[yellow]Proceeding with ticket creation...[/yellow]")
266
+
267
+ # Get the adapter name with priority: 1) argument, 2) config, 3) .env files, 4) default
268
+ if adapter:
269
+ # Priority 1: Command-line argument - save to config for future use
270
+ adapter_name = adapter.value
271
+ _save_adapter_to_config(adapter_name)
272
+ else:
273
+ # Priority 2: Check existing config
274
+ config = load_config()
275
+ adapter_name = config.get("default_adapter")
276
+
277
+ if not adapter_name or adapter_name == "aitrackdown":
278
+ # Priority 3: Check .env files and save if found
279
+ env_adapter = _discover_from_env_files()
280
+ if env_adapter:
281
+ adapter_name = env_adapter
282
+ _save_adapter_to_config(adapter_name)
283
+ else:
284
+ # Priority 4: Default
285
+ adapter_name = "aitrackdown"
286
+
287
+ # Resolve project/epic synonym - prefer whichever is provided
288
+ parent_epic_id = project or epic
289
+
290
+ # Create task data
291
+ # Import Priority for type checking
292
+ from ..core.models import Priority as PriorityEnum
293
+
294
+ task_data = {
295
+ "title": title,
296
+ "description": description,
297
+ "priority": priority.value if isinstance(priority, PriorityEnum) else priority,
298
+ "tags": tags or [],
299
+ "assignee": assignee,
300
+ "parent_epic": parent_epic_id,
301
+ }
302
+
303
+ # WORKAROUND: Use direct operation for Linear adapter to bypass worker subprocess issue
304
+ if adapter_name == "linear":
305
+ console.print(
306
+ "[yellow]⚠️[/yellow] Using direct operation for Linear adapter (bypassing queue)"
307
+ )
308
+ try:
309
+ # Load configuration and create adapter directly
310
+ config = load_config()
311
+ adapter_config = config.get("adapters", {}).get(adapter_name, {})
312
+
313
+ # Import and create adapter
314
+ from ..core.registry import AdapterRegistry
315
+
316
+ adapter_instance = AdapterRegistry.get_adapter(adapter_name, adapter_config)
317
+
318
+ # Create task directly
319
+ from ..core.models import Priority, Task
320
+
321
+ task = Task(
322
+ title=task_data["title"],
323
+ description=task_data.get("description"),
324
+ priority=(
325
+ Priority(task_data["priority"])
326
+ if task_data.get("priority")
327
+ else Priority.MEDIUM
328
+ ),
329
+ tags=task_data.get("tags", []),
330
+ assignee=task_data.get("assignee"),
331
+ parent_epic=task_data.get("parent_epic"),
332
+ )
333
+
334
+ # Create ticket synchronously
335
+ import asyncio
336
+
337
+ result = asyncio.run(adapter_instance.create(task))
338
+
339
+ console.print(f"[green]✓[/green] Ticket created successfully: {result.id}")
340
+ console.print(f" Title: {result.title}")
341
+ console.print(f" Priority: {result.priority}")
342
+ console.print(f" State: {result.state}")
343
+ # Get URL from metadata if available
344
+ if (
345
+ result.metadata
346
+ and "linear" in result.metadata
347
+ and "url" in result.metadata["linear"]
348
+ ):
349
+ console.print(f" URL: {result.metadata['linear']['url']}")
350
+
351
+ return result.id
352
+
353
+ except Exception as e:
354
+ console.print(f"[red]❌[/red] Failed to create ticket: {e}")
355
+ raise
356
+
357
+ # Use queue for other adapters
358
+ queue = Queue()
359
+ queue_id = queue.add(
360
+ ticket_data=task_data,
361
+ adapter=adapter_name,
362
+ operation="create",
363
+ project_dir=str(Path.cwd()), # Explicitly pass current project directory
364
+ )
365
+
366
+ # Register in ticket registry for tracking
367
+ registry = TicketRegistry()
368
+ registry.register_ticket_operation(
369
+ queue_id, adapter_name, "create", title, task_data
370
+ )
371
+
372
+ console.print(f"[green]✓[/green] Queued ticket creation: {queue_id}")
373
+ console.print(f" Title: {title}")
374
+ console.print(f" Priority: {priority}")
375
+ console.print(f" Adapter: {adapter_name}")
376
+ console.print(
377
+ "[dim]Use 'mcp-ticketer ticket check {queue_id}' to check progress[/dim]"
378
+ )
379
+
380
+ # Start worker if needed with immediate feedback
381
+ manager = WorkerManager()
382
+ worker_started = manager.start_if_needed()
383
+
384
+ if worker_started:
385
+ console.print("[dim]Worker started to process request[/dim]")
386
+
387
+ # Give immediate feedback on processing
388
+ import time
389
+
390
+ time.sleep(1) # Brief pause to let worker start
391
+
392
+ # Check if item is being processed
393
+ item = queue.get_item(queue_id)
394
+ if item and item.status == QueueStatus.PROCESSING:
395
+ console.print("[green]✓ Item is being processed by worker[/green]")
396
+ elif item and item.status == QueueStatus.PENDING:
397
+ console.print("[yellow]⏳ Item is queued for processing[/yellow]")
398
+ else:
399
+ console.print(
400
+ "[red]⚠️ Item status unclear - check with 'mcp-ticketer ticket check {queue_id}'[/red]"
401
+ )
402
+ else:
403
+ # Worker didn't start - this is a problem
404
+ pending_count = queue.get_pending_count()
405
+ if pending_count > 1: # More than just this item
406
+ console.print(
407
+ f"[red]❌ Worker failed to start with {pending_count} pending items![/red]"
408
+ )
409
+ console.print(
410
+ "[red]This is a critical issue. Try 'mcp-ticketer queue worker start' manually.[/red]"
411
+ )
412
+ else:
413
+ console.print(
414
+ "[yellow]Worker not started (no other pending items)[/yellow]"
415
+ )
416
+
417
+
418
+ @app.command("list")
419
+ def list_tickets(
420
+ state: TicketState | None = typer.Option(
421
+ None, "--state", "-s", help="Filter by state"
422
+ ),
423
+ priority: Priority | None = typer.Option(
424
+ None, "--priority", "-p", help="Filter by priority"
425
+ ),
426
+ limit: int = typer.Option(10, "--limit", "-l", help="Maximum number of tickets"),
427
+ adapter: AdapterType | None = typer.Option(
428
+ None, "--adapter", help="Override default adapter"
429
+ ),
430
+ ) -> None:
431
+ """List tickets with optional filters."""
432
+
433
+ async def _list() -> list[Any]:
434
+ adapter_instance = get_adapter(
435
+ override_adapter=adapter.value if adapter else None
436
+ )
437
+ filters = {}
438
+ if state:
439
+ filters["state"] = state
440
+ if priority:
441
+ filters["priority"] = priority
442
+ return await adapter_instance.list(limit=limit, filters=filters)
443
+
444
+ tickets = asyncio.run(_list())
445
+
446
+ if not tickets:
447
+ console.print("[yellow]No tickets found[/yellow]")
448
+ return
449
+
450
+ # Create table
451
+ table = Table(title="Tickets")
452
+ table.add_column("ID", style="cyan", no_wrap=True)
453
+ table.add_column("Title", style="white")
454
+ table.add_column("State", style="green")
455
+ table.add_column("Priority", style="yellow")
456
+ table.add_column("Assignee", style="blue")
457
+
458
+ for ticket in tickets:
459
+ # Handle assignee field - Epic doesn't have assignee, Task does
460
+ assignee = getattr(ticket, "assignee", None) or "-"
461
+
462
+ table.add_row(
463
+ ticket.id or "N/A",
464
+ ticket.title,
465
+ ticket.state,
466
+ ticket.priority,
467
+ assignee,
468
+ )
469
+
470
+ console.print(table)
471
+
472
+
473
+ @app.command()
474
+ def show(
475
+ ticket_id: str = typer.Argument(..., help="Ticket ID"),
476
+ comments: bool = typer.Option(False, "--comments", "-c", help="Show comments"),
477
+ adapter: AdapterType | None = typer.Option(
478
+ None, "--adapter", help="Override default adapter"
479
+ ),
480
+ ) -> None:
481
+ """Show detailed ticket information."""
482
+
483
+ async def _show() -> tuple[Any, Any]:
484
+ adapter_instance = get_adapter(
485
+ override_adapter=adapter.value if adapter else None
486
+ )
487
+ ticket = await adapter_instance.read(ticket_id)
488
+ ticket_comments = None
489
+ if comments and ticket:
490
+ ticket_comments = await adapter_instance.get_comments(ticket_id)
491
+ return ticket, ticket_comments
492
+
493
+ ticket, ticket_comments = asyncio.run(_show())
494
+
495
+ if not ticket:
496
+ console.print(f"[red]✗[/red] Ticket not found: {ticket_id}")
497
+ raise typer.Exit(1) from None
498
+
499
+ # Display ticket details
500
+ console.print(f"\n[bold]Ticket: {ticket.id}[/bold]")
501
+ console.print(f"Title: {ticket.title}")
502
+ console.print(f"State: [green]{ticket.state}[/green]")
503
+ console.print(f"Priority: [yellow]{ticket.priority}[/yellow]")
504
+
505
+ if ticket.description:
506
+ console.print("\n[dim]Description:[/dim]")
507
+ console.print(ticket.description)
508
+
509
+ if ticket.tags:
510
+ console.print(f"\nTags: {', '.join(ticket.tags)}")
511
+
512
+ if ticket.assignee:
513
+ console.print(f"Assignee: {ticket.assignee}")
514
+
515
+ # Display comments if requested
516
+ if ticket_comments:
517
+ console.print(f"\n[bold]Comments ({len(ticket_comments)}):[/bold]")
518
+ for comment in ticket_comments:
519
+ console.print(f"\n[dim]{comment.created_at} - {comment.author}:[/dim]")
520
+ console.print(comment.content)
521
+
522
+
523
+ @app.command()
524
+ def comment(
525
+ ticket_id: str = typer.Argument(..., help="Ticket ID"),
526
+ content: str = typer.Argument(..., help="Comment content"),
527
+ adapter: AdapterType | None = typer.Option(
528
+ None, "--adapter", help="Override default adapter"
529
+ ),
530
+ ) -> None:
531
+ """Add a comment to a ticket."""
532
+
533
+ async def _comment() -> Comment:
534
+ adapter_instance = get_adapter(
535
+ override_adapter=adapter.value if adapter else None
536
+ )
537
+
538
+ # Create comment
539
+ comment_obj = Comment(
540
+ ticket_id=ticket_id,
541
+ content=content,
542
+ author="cli-user", # Could be made configurable
543
+ )
544
+
545
+ result = await adapter_instance.add_comment(comment_obj)
546
+ return result
547
+
548
+ try:
549
+ result = asyncio.run(_comment())
550
+ console.print("[green]✓[/green] Comment added successfully")
551
+ if result.id:
552
+ console.print(f"Comment ID: {result.id}")
553
+ console.print(f"Content: {content}")
554
+ except Exception as e:
555
+ console.print(f"[red]✗[/red] Failed to add comment: {e}")
556
+ raise typer.Exit(1) from None
557
+
558
+
559
+ @app.command()
560
+ def update(
561
+ ticket_id: str = typer.Argument(..., help="Ticket ID"),
562
+ title: str | None = typer.Option(None, "--title", help="New title"),
563
+ description: str | None = typer.Option(
564
+ None, "--description", "-d", help="New description"
565
+ ),
566
+ priority: Priority | None = typer.Option(
567
+ None, "--priority", "-p", help="New priority"
568
+ ),
569
+ assignee: str | None = typer.Option(None, "--assignee", "-a", help="New assignee"),
570
+ adapter: AdapterType | None = typer.Option(
571
+ None, "--adapter", help="Override default adapter"
572
+ ),
573
+ ) -> None:
574
+ """Update ticket fields."""
575
+ updates = {}
576
+ if title:
577
+ updates["title"] = title
578
+ if description:
579
+ updates["description"] = description
580
+ if priority:
581
+ updates["priority"] = (
582
+ priority.value if isinstance(priority, Priority) else priority
583
+ )
584
+ if assignee:
585
+ updates["assignee"] = assignee
586
+
587
+ if not updates:
588
+ console.print("[yellow]No updates specified[/yellow]")
589
+ raise typer.Exit(1) from None
590
+
591
+ # Get the adapter name
592
+ config = load_config()
593
+ adapter_name = (
594
+ adapter.value if adapter else config.get("default_adapter", "aitrackdown")
595
+ )
596
+
597
+ # Add ticket_id to updates
598
+ updates["ticket_id"] = ticket_id
599
+
600
+ # Add to queue with explicit project directory
601
+ queue = Queue()
602
+ queue_id = queue.add(
603
+ ticket_data=updates,
604
+ adapter=adapter_name,
605
+ operation="update",
606
+ project_dir=str(Path.cwd()), # Explicitly pass current project directory
607
+ )
608
+
609
+ console.print(f"[green]✓[/green] Queued ticket update: {queue_id}")
610
+ for key, value in updates.items():
611
+ if key != "ticket_id":
612
+ console.print(f" {key}: {value}")
613
+ console.print(
614
+ "[dim]Use 'mcp-ticketer ticket check {queue_id}' to check progress[/dim]"
615
+ )
616
+
617
+ # Start worker if needed
618
+ manager = WorkerManager()
619
+ if manager.start_if_needed():
620
+ console.print("[dim]Worker started to process request[/dim]")
621
+
622
+
623
+ @app.command()
624
+ def transition(
625
+ ticket_id: str = typer.Argument(..., help="Ticket ID"),
626
+ state_positional: TicketState | None = typer.Argument(
627
+ None, help="Target state (positional - deprecated, use --state instead)"
628
+ ),
629
+ state: TicketState | None = typer.Option(
630
+ None, "--state", "-s", help="Target state (recommended)"
631
+ ),
632
+ adapter: AdapterType | None = typer.Option(
633
+ None, "--adapter", help="Override default adapter"
634
+ ),
635
+ ) -> None:
636
+ """Change ticket state with validation.
637
+
638
+ Examples:
639
+ # Recommended syntax with flag:
640
+ mcp-ticketer ticket transition BTA-215 --state done
641
+ mcp-ticketer ticket transition BTA-215 -s in_progress
642
+
643
+ # Legacy positional syntax (still supported):
644
+ mcp-ticketer ticket transition BTA-215 done
645
+
646
+ """
647
+ # Determine which state to use (prefer flag over positional)
648
+ target_state = state if state is not None else state_positional
649
+
650
+ if target_state is None:
651
+ console.print("[red]Error: State is required[/red]")
652
+ console.print(
653
+ "Use either:\n"
654
+ " - Flag syntax (recommended): mcp-ticketer ticket transition TICKET-ID --state STATE\n"
655
+ " - Positional syntax: mcp-ticketer ticket transition TICKET-ID STATE"
656
+ )
657
+ raise typer.Exit(1) from None
658
+
659
+ # Get the adapter name
660
+ config = load_config()
661
+ adapter_name = (
662
+ adapter.value if adapter else config.get("default_adapter", "aitrackdown")
663
+ )
664
+
665
+ # Add to queue with explicit project directory
666
+ queue = Queue()
667
+ queue_id = queue.add(
668
+ ticket_data={
669
+ "ticket_id": ticket_id,
670
+ "state": (
671
+ target_state.value if hasattr(target_state, "value") else target_state
672
+ ),
673
+ },
674
+ adapter=adapter_name,
675
+ operation="transition",
676
+ project_dir=str(Path.cwd()), # Explicitly pass current project directory
677
+ )
678
+
679
+ console.print(f"[green]✓[/green] Queued state transition: {queue_id}")
680
+ console.print(f" Ticket: {ticket_id} → {target_state}")
681
+ console.print(
682
+ "[dim]Use 'mcp-ticketer ticket check {queue_id}' to check progress[/dim]"
683
+ )
684
+
685
+ # Start worker if needed
686
+ manager = WorkerManager()
687
+ if manager.start_if_needed():
688
+ console.print("[dim]Worker started to process request[/dim]")
689
+
690
+
691
+ @app.command()
692
+ def search(
693
+ query: str | None = typer.Argument(None, help="Search query"),
694
+ state: TicketState | None = typer.Option(None, "--state", "-s"),
695
+ priority: Priority | None = typer.Option(None, "--priority", "-p"),
696
+ assignee: str | None = typer.Option(None, "--assignee", "-a"),
697
+ limit: int = typer.Option(10, "--limit", "-l"),
698
+ adapter: AdapterType | None = typer.Option(
699
+ None, "--adapter", help="Override default adapter"
700
+ ),
701
+ ) -> None:
702
+ """Search tickets with advanced query."""
703
+
704
+ async def _search() -> list[Any]:
705
+ adapter_instance = get_adapter(
706
+ override_adapter=adapter.value if adapter else None
707
+ )
708
+ search_query = SearchQuery(
709
+ query=query,
710
+ state=state,
711
+ priority=priority,
712
+ assignee=assignee,
713
+ limit=limit,
714
+ )
715
+ return await adapter_instance.search(search_query)
716
+
717
+ tickets = asyncio.run(_search())
718
+
719
+ if not tickets:
720
+ console.print("[yellow]No tickets found matching query[/yellow]")
721
+ return
722
+
723
+ # Display results
724
+ console.print(f"\n[bold]Found {len(tickets)} ticket(s)[/bold]\n")
725
+
726
+ for ticket in tickets:
727
+ console.print(f"[cyan]{ticket.id}[/cyan]: {ticket.title}")
728
+ console.print(f" State: {ticket.state} | Priority: {ticket.priority}")
729
+ if ticket.assignee:
730
+ console.print(f" Assignee: {ticket.assignee}")
731
+ console.print()
732
+
733
+
734
+ @app.command()
735
+ def check(queue_id: str = typer.Argument(..., help="Queue ID to check")) -> None:
736
+ """Check status of a queued operation."""
737
+ queue = Queue()
738
+ item = queue.get_item(queue_id)
739
+
740
+ if not item:
741
+ console.print(f"[red]Queue item not found: {queue_id}[/red]")
742
+ raise typer.Exit(1) from None
743
+
744
+ # Display status
745
+ console.print(f"\n[bold]Queue Item: {item.id}[/bold]")
746
+ console.print(f"Operation: {item.operation}")
747
+ console.print(f"Adapter: {item.adapter}")
748
+
749
+ # Status with color
750
+ if item.status == QueueStatus.COMPLETED:
751
+ console.print(f"Status: [green]{item.status}[/green]")
752
+ elif item.status == QueueStatus.FAILED:
753
+ console.print(f"Status: [red]{item.status}[/red]")
754
+ elif item.status == QueueStatus.PROCESSING:
755
+ console.print(f"Status: [yellow]{item.status}[/yellow]")
756
+ else:
757
+ console.print(f"Status: {item.status}")
758
+
759
+ # Timestamps
760
+ console.print(f"Created: {item.created_at.strftime('%Y-%m-%d %H:%M:%S')}")
761
+ if item.processed_at:
762
+ console.print(f"Processed: {item.processed_at.strftime('%Y-%m-%d %H:%M:%S')}")
763
+
764
+ # Error or result
765
+ if item.error_message:
766
+ console.print(f"\n[red]Error:[/red] {item.error_message}")
767
+ elif item.result:
768
+ console.print("\n[green]Result:[/green]")
769
+ for key, value in item.result.items():
770
+ console.print(f" {key}: {value}")
771
+
772
+ if item.retry_count > 0:
773
+ console.print(f"\nRetry Count: {item.retry_count}")