From 0c24b43d20520def8580a2f80972e1b6c3712185 Mon Sep 17 00:00:00 2001 From: Tom Softreck Date: Wed, 4 Nov 2026 08:54:13 +0100 Subject: [PATCH] feat(sync): add fleet sync with 6h timer and inbound sync on ticket creation (ticket-278) --- planfile/cli/groups/sync/__init__.py | 2 + planfile/cli/groups/sync/commands.py | 14 ++ planfile/cli/groups/sync/core.py | 4 + planfile/cli/groups/sync/fleet.py | 308 +++++++++++++++++++++++ planfile/cli/groups/ticket/commands.py | 48 +++- planfile/sync/operations.py | 31 +++ project/TICKETS.md | 1 + project/ticket-278/README.md | 39 +++ project/ticket-278/intent.json | 27 ++ tests/test_fleet_sync.py | 94 +++++++ tests/test_ticket_create_inbound_sync.py | 75 ++++++ 11 files changed, 641 insertions(+), 2 deletions(-) create mode 100644 planfile/cli/groups/sync/fleet.py create mode 100644 project/ticket-278/README.md create mode 100644 project/ticket-278/intent.json create mode 100644 tests/test_fleet_sync.py create mode 100644 tests/test_ticket_create_inbound_sync.py diff --git a/planfile/cli/groups/sync/__init__.py b/planfile/cli/groups/sync/__init__.py index 199be495..d2dc82eb 100644 --- a/planfile/cli/groups/sync/__init__.py +++ b/planfile/cli/groups/sync/__init__.py @@ -4,6 +4,7 @@ from planfile.cli.groups.sync.commands import ( all_cmd, + fleet_cmd, github_cmd, gitlab_cmd, jira_cmd, @@ -28,5 +29,6 @@ def register_sync_commands(app: typer.Typer) -> None: sync_app.command("all")(all_cmd) sync_app.command("watch")(watch_cmd) sync_app.command("retry")(retry_cmd) + sync_app.command("fleet")(fleet_cmd) app.add_typer(sync_app, name="sync") diff --git a/planfile/cli/groups/sync/commands.py b/planfile/cli/groups/sync/commands.py index 893e955c..c16373ab 100644 --- a/planfile/cli/groups/sync/commands.py +++ b/planfile/cli/groups/sync/commands.py @@ -11,6 +11,20 @@ from planfile.cli.core import console from planfile.cli.groups.sync.core import sync_integration +from planfile.cli.groups.sync.fleet import fleet_cmd + +__all__ = [ + "all_cmd", + "fleet_cmd", + "github_cmd", + "gitlab_cmd", + "jira_cmd", + "markdown_cmd", + "onedev_cmd", + "publish_cmd", + "retry_cmd", + "watch_cmd", +] def retry_cmd( diff --git a/planfile/cli/groups/sync/core.py b/planfile/cli/groups/sync/core.py index 5751abee..8e2dbaa8 100644 --- a/planfile/cli/groups/sync/core.py +++ b/planfile/cli/groups/sync/core.py @@ -242,6 +242,7 @@ def _execute_sync_with_progress( ticket_ids: list[str] | None = None, sprint_ids: list[str] | None = None, remote_labels: list[str] | None = None, + exclude_incident_noise: bool = False, ) -> None: """Execute sync with progress bar.""" with Progress( @@ -267,6 +268,7 @@ def _execute_sync_with_progress( ticket_ids=ticket_ids, sprint_ids=sprint_ids, remote_labels=remote_labels, + exclude_incident_noise=exclude_incident_noise, ) progress.update(task, description="[green]✓ Synced from external system[/green]") @@ -284,6 +286,7 @@ def sync_integration( managed_only: bool = False, incremental: bool = False, max_tickets: int = 2, + exclude_incident_noise: bool = False, ) -> None: """Sync with a specific integration.""" if show_header: @@ -383,6 +386,7 @@ def sync_integration( ticket_ids, sprint_ids, remote_labels, + exclude_incident_noise=exclude_incident_noise, ) delivered_comments = [] if integration_name == "github" and direction in {"to", "both"} and not dry_run: diff --git a/planfile/cli/groups/sync/fleet.py b/planfile/cli/groups/sync/fleet.py new file mode 100644 index 00000000..01a26eaa --- /dev/null +++ b/planfile/cli/groups/sync/fleet.py @@ -0,0 +1,308 @@ +"""Fleet GitHub synchronization across local repositories with 6h schedule integration.""" + +from __future__ import annotations + +import shutil +import subprocess +from pathlib import Path +from typing import Any + +import typer +from rich.table import Table + +from planfile.cli.core import console, print_error, print_success +from planfile.cli.groups.sync.core import sync_integration +from planfile.integrations.config import IntegrationConfig + +DEFAULT_INTERVAL_HOURS = 6 +SERVICE_NAME = "planfile-fleet-sync.service" +TIMER_NAME = "planfile-fleet-sync.timer" + + +def get_systemd_user_dir() -> Path: + """Return user systemd directory, creating it if needed.""" + user_dir = Path.home() / ".config" / "systemd" / "user" + user_dir.mkdir(parents=True, exist_ok=True) + return user_dir + + +def generate_service_content(root: Path | None = None, planfile_bin: str | None = None) -> str: + """Generate systemd user service unit content.""" + root_str = str(root.resolve()) if root else "%h/github" + bin_str = planfile_bin or shutil.which("planfile") or "%h/miniconda3/bin/planfile" + return f"""[Unit] +Description=Planfile Fleet GitHub Inbound Synchronization +Wants=network-online.target +After=network-online.target + +[Service] +Type=oneshot +ExecStart={bin_str} sync fleet {root_str} +TimeoutStartSec=20min +Nice=10 +UMask=0077 +NoNewPrivileges=true +""" + + +def generate_timer_content(interval_hours: int = DEFAULT_INTERVAL_HOURS) -> str: + """Generate systemd user timer unit content.""" + return f"""[Unit] +Description=Run Planfile Fleet GitHub synchronization every {interval_hours} hours + +[Timer] +OnBootSec=5min +OnUnitActiveSec={interval_hours}h +Persistent=true +Unit={SERVICE_NAME} + +[Install] +WantedBy=timers.target +""" + + +def install_fleet_systemd_timer( + interval_hours: int = DEFAULT_INTERVAL_HOURS, + root: Path | None = None, +) -> tuple[bool, str]: + """Install and enable systemd user service and timer.""" + user_dir = get_systemd_user_dir() + service_path = user_dir / SERVICE_NAME + timer_path = user_dir / TIMER_NAME + + service_path.write_text(generate_service_content(root=root), encoding="utf-8") + timer_path.write_text(generate_timer_content(interval_hours=interval_hours), encoding="utf-8") + + try: + subprocess.run(["systemctl", "--user", "daemon-reload"], check=True, capture_output=True, text=True) + subprocess.run(["systemctl", "--user", "enable", "--now", TIMER_NAME], check=True, capture_output=True, text=True) + return True, f"Installed and started {TIMER_NAME} (cycle: every {interval_hours}h)" + except Exception as exc: + return False, f"Failed to activate systemd timer: {exc}" + + +def uninstall_fleet_systemd_timer() -> tuple[bool, str]: + """Disable and remove systemd user service and timer.""" + user_dir = get_systemd_user_dir() + service_path = user_dir / SERVICE_NAME + timer_path = user_dir / TIMER_NAME + + try: + subprocess.run(["systemctl", "--user", "disable", "--now", TIMER_NAME], check=False, capture_output=True, text=True) + except Exception: + pass + + if service_path.exists(): + service_path.unlink() + if timer_path.exists(): + timer_path.unlink() + + try: + subprocess.run(["systemctl", "--user", "daemon-reload"], check=False, capture_output=True, text=True) + except Exception: + pass + + return True, f"Uninstalled {TIMER_NAME} and {SERVICE_NAME}" + + +def status_fleet_systemd_timer() -> str: + """Check status of the systemd fleet timer.""" + try: + res = subprocess.run( + ["systemctl", "--user", "status", TIMER_NAME], + capture_output=True, + text=True, + check=False, + ) + return res.stdout or res.stderr + except Exception as exc: + return f"Could not inspect systemctl: {exc}" + + +def discover_fleet_repositories( + root: Path, + max_depth: int = 2, +) -> list[tuple[Path, str]]: + """Scan subdirectories up to max_depth for .planfile stores configured with GitHub.""" + results: list[tuple[Path, str]] = [] + if not root.is_dir(): + return results + + # Breadth-first search bounded by max_depth + queue: list[tuple[Path, int]] = [(root, 0)] + while queue: + current, depth = queue.pop(0) + if depth > 0: + try: + planfile_dir = current / ".planfile" + if planfile_dir.is_dir(): + try: + config = IntegrationConfig(str(current)) + config.load_configs() + gh_cfg = config.get_integration_config("github") + repo_name = gh_cfg.get("repo") if isinstance(gh_cfg, dict) else None + if repo_name and config.validate_integration("github"): + results.append((current, str(repo_name))) + except Exception: + pass + # Once a repository with .planfile is matched, do not descend into internal subtrees + continue + except (PermissionError, OSError): + continue + + if depth < max_depth: + try: + for entry in sorted(current.iterdir()): + if entry.is_dir() and not entry.name.startswith(".") and not entry.is_symlink(): + queue.append((entry, depth + 1)) + except PermissionError: + continue + + return results + + +def sync_fleet( + root: Path, + max_depth: int = 2, + dry_run: bool = False, + exclude_incident_noise: bool = True, + managed_only: bool = False, + max_projects: int | None = None, +) -> dict[str, Any]: + """Execute inbound sync across all discovered fleet repositories.""" + discovered = discover_fleet_repositories(root, max_depth=max_depth) + if max_projects: + discovered = discovered[:max_projects] + + stats: dict[str, Any] = { + "scanned": len(discovered), + "synced": 0, + "failed": 0, + "results": [], + } + + if not discovered: + console.print(f"[dim]â„šī¸ No GitHub-integrated repositories found under {root}[/dim]") + return stats + + console.print(f"\n[bold blue]🚀 Starting Fleet Sync across {len(discovered)} repositories...[/bold blue]") + console.print(f"[dim] Root: {root} (depth: {max_depth})[/dim]") + console.print("[dim] Direction: from (inbound GitHub ➔ Planfile)[/dim]") + console.print(f"[dim] Filter incident noise: {exclude_incident_noise}[/dim]") + console.print(f"[dim] Managed labels only: {managed_only}[/dim]\n") + + for repo_path, gh_repo in discovered: + repo_name = repo_path.name + console.print(f"[bold cyan]📁 {repo_name}[/bold cyan] [dim]({gh_repo})[/dim]") + try: + sync_integration( + "github", + str(repo_path), + dry_run=dry_run, + direction="from", + show_header=False, + managed_only=managed_only, + exclude_incident_noise=exclude_incident_noise, + ) + stats["synced"] += 1 + stats["results"].append({"repo": repo_name, "github": gh_repo, "status": "ok"}) + except Exception as exc: + stats["failed"] += 1 + stats["results"].append({ + "repo": repo_name, + "github": gh_repo, + "status": "error", + "error": str(exc), + }) + console.print(f" [red]✗ Sync error for {repo_name}: {exc}[/red]") + + return stats + + +def fleet_cmd( + root: str = typer.Argument( + str(Path.home() / "github"), + help="Root directory containing repositories (e.g. ~/github)", + ), + depth: int = typer.Option(2, "--depth", "-d", help="Directory search depth (default: 2 for ~/github/*/*)"), + dry_run: bool = typer.Option(False, "--dry-run", help="Preview sync without saving changes"), + exclude_incident_noise: bool = typer.Option( + True, + "--exclude-incident-noise/--include-incidents", + help="Filter out transient browser/system crash dumps and incident logs", + ), + managed_only: bool = typer.Option( + False, + "--managed-only", + help="Only sync issues with 'planfile' or 'managed' labels", + ), + install_timer: bool = typer.Option( + False, + "--install-timer", + help="Install and activate 6-hour systemd user timer for automated fleet sync", + ), + uninstall_timer: bool = typer.Option( + False, + "--uninstall-timer", + help="Uninstall and deactivate systemd user timer", + ), + status_timer: bool = typer.Option( + False, + "--status-timer", + help="Show status of systemd fleet timer", + ), + interval_hours: int = typer.Option( + DEFAULT_INTERVAL_HOURS, + "--interval-hours", + "-i", + help="Timer interval in hours (default: 6)", + ), +) -> None: + """Synchronize GitHub issues into local Planfile backlogs across a fleet of projects.""" + if install_timer: + ok, msg = install_fleet_systemd_timer(interval_hours=interval_hours, root=Path(root)) + if ok: + print_success(msg) + else: + print_error(msg) + raise typer.Exit(1) + return + + if uninstall_timer: + ok, msg = uninstall_fleet_systemd_timer() + print_success(msg) + return + + if status_timer: + status_output = status_fleet_systemd_timer() + console.print(status_output) + return + + root_path = Path(root).expanduser().resolve() + if not root_path.exists(): + print_error(f"Root path does not exist: {root_path}") + raise typer.Exit(1) + + stats = sync_fleet( + root_path, + max_depth=depth, + dry_run=dry_run, + exclude_incident_noise=exclude_incident_noise, + managed_only=managed_only, + ) + + table = Table(title="Fleet Sync Summary", show_header=True, header_style="bold magenta") + table.add_column("Project", style="cyan") + table.add_column("GitHub Target", style="dim") + table.add_column("Status", justify="center") + + for res in stats["results"]: + status_styled = "[green]✓ synced[/green]" if res["status"] == "ok" else f"[red]✗ {res.get('error', 'failed')}[/red]" + table.add_row(res["repo"], res["github"], status_styled) + + console.print(table) + console.print( + f"[bold]Total scanned:[/bold] {stats['scanned']} | " + f"[green bold]Synced:[/green bold] {stats['synced']} | " + f"[red bold]Failed:[/red bold] {stats['failed']}\n" + ) diff --git a/planfile/cli/groups/ticket/commands.py b/planfile/cli/groups/ticket/commands.py index 743cf84b..e6fdcc9d 100644 --- a/planfile/cli/groups/ticket/commands.py +++ b/planfile/cli/groups/ticket/commands.py @@ -79,6 +79,34 @@ def _auto_sync( ) raise typer.Exit(1) from last_failure + +def _inbound_sync_before_create( + directory: str, + integrations: list[str], + dry_run: bool = False, + exclude_incident_noise: bool = True, +) -> None: + """Sync remote records into local planfile before ticket creation.""" + from planfile.cli.groups.sync.core import sync_integration + + for integration in integrations: + try: + sync_integration( + integration, + directory, + dry_run, + "from", + show_header=False, + exclude_incident_noise=exclude_incident_noise, + ) + except typer.Exit: + pass + except Exception as exc: + console.print( + f"[yellow]âš ī¸ Inbound sync from {integration} skipped: {exc}; proceeding with local ticket creation.[/yellow]" + ) + + def format_markdown_tickets(tickets: list, details: bool = False, gh_repo: str = "") -> str: """Format ticket list as a markdown summary table, optionally with full details.""" lines = [] @@ -302,6 +330,11 @@ def ticket_create( sync_dry_run: bool = typer.Option( False, "--sync-dry-run", help="Preview sync without making changes" ), + inbound_sync: bool | None = typer.Option( + None, + "--inbound-sync/--no-inbound-sync", + help="Inspect and sync remote issues from configured integrations before creating the ticket (defaults to true when remote integrations are configured)", + ), force: bool = typer.Option( False, "--force", @@ -349,6 +382,17 @@ def ticket_create( if k != "markdown" and integration_config.validate_integration(k) ] + # Reconcile inbound tickets from remote integrations before creating the new ticket + should_inbound_sync = inbound_sync if inbound_sync is not None else bool(valid_remote_integrations) + if should_inbound_sync and valid_remote_integrations: + _inbound_sync_before_create( + str(pf.store.project_dir), + valid_remote_integrations, + dry_run=sync_dry_run, + ) + # Reload planfile store so newly fetched remote tickets/dedupe keys are in memory + pf = Planfile.auto_discover() + target_integrations: list[str] = [] if integration: target_integrations = list(integration) @@ -776,7 +820,7 @@ def ticket_ready(ticket_id: str=typer.Argument(..., help='Ticket ID to make runn ticket = pf.ready_ticket(ticket_id, note=note) except ValueError as exc: console.print(f'[red]✗[/red] Cannot ready {ticket_id}: {exc}') - raise typer.Exit(1) + raise typer.Exit(1) from exc if not ticket: console.print(f'[red]✗[/red] Ticket {ticket_id} not found.') raise typer.Exit(1) @@ -793,7 +837,7 @@ def ticket_resume( ticket = pf.resume_ticket(ticket_id, note=note) except ValueError as exc: console.print(f'[red]✗[/red] Cannot resume {ticket_id}: {exc}') - raise typer.Exit(1) + raise typer.Exit(1) from exc if not ticket: console.print(f'[red]✗[/red] Ticket {ticket_id} not found.') raise typer.Exit(1) diff --git a/planfile/sync/operations.py b/planfile/sync/operations.py index 149b6cbb..d34f4a36 100644 --- a/planfile/sync/operations.py +++ b/planfile/sync/operations.py @@ -643,6 +643,7 @@ def sync_from_external( ticket_ids: list[str] | None = None, sprint_ids: list[str] | None = None, remote_labels: list[str] | None = None, + exclude_incident_noise: bool = False, ) -> None: """Sync tickets from external system to planfile.""" sync_state = _bind_sync_state( @@ -701,6 +702,8 @@ def sync_from_external( return for ext_ticket in external_tickets: + if exclude_incident_noise and is_incident_noise(ext_ticket): + continue imported_count, updated_count = _process_external_ticket( ext_ticket, sprint, @@ -731,6 +734,34 @@ def sync_from_external( ) +_INCIDENT_NAME_PATTERN = re.compile( + r"^(\[(?:autocontrol|computer-use)[^\]]*\]|Runtime crash:|Auto-detected degradation:|Failed to run action:)", + re.IGNORECASE, +) +_INCIDENT_LABEL_KEYWORDS = { + "incident", + "crash", + "auto-detected", + "degradation", + "runtime-crash", + "incident-report", +} + + +def is_incident_noise(ext_ticket) -> bool: + """Return True if an external ticket represents raw runtime crash or degradation noise.""" + data = _extract_ticket_data(ext_ticket) + name = (data.get("name") or "").strip() + if _INCIDENT_NAME_PATTERN.search(name): + return True + labels = data.get("labels") or [] + for lbl in labels: + clean_lbl = str(lbl).strip().lower() + if clean_lbl in _INCIDENT_LABEL_KEYWORDS or clean_lbl.startswith("incident:"): + return True + return False + + def _extract_ticket_data(ext_ticket) -> dict: """Extract standardized ticket data from external ticket (dict or Pydantic model).""" if hasattr(ext_ticket, "id"): diff --git a/project/TICKETS.md b/project/TICKETS.md index e29fc205..4651616d 100644 --- a/project/TICKETS.md +++ b/project/TICKETS.md @@ -174,4 +174,5 @@ This file indexes governance tickets without taking ownership of | **ticket-273** | [`README.md`](./ticket-273/README.md) | - | - | - | - | - | | **ticket-274** | [`README.md`](./ticket-274/README.md) | - | - | - | - | - | | **ticket-275** | [`README.md`](./ticket-275/README.md) | - | - | - | - | - | +| **ticket-277** | [`README.md`](./ticket-277/README.md) | - | - | - | - | - | diff --git a/project/ticket-278/README.md b/project/ticket-278/README.md new file mode 100644 index 00000000..ae39ebd4 --- /dev/null +++ b/project/ticket-278/README.md @@ -0,0 +1,39 @@ +# Ticket 278: Fleet sync and inbound GitHub sync on ticket creation + +- **ID**: ticket-278 +- **Owner**: agent:antigravity +- **Status**: IN_PROGRESS +- **Workflow state**: VALIDATION +- **Created**: 2026-11-04 + +## Goal and scope + +Implement autonomous and cyclic synchronization from GitHub to Planfile: +1. Fleet sync across repositories in `~/github/*/*` with 6-hour systemd user timer integration, rate limit protection, and filtering of transient crash/incident noise (such as browser autocontrol dumps). +2. Automatic inbound GitHub inspection and synchronization before creating local tickets in `planfile ticket create` to ensure the local store is up-to-date with remote issues and avoid duplicate allocations. + +## Acceptance criteria + +- [x] AC-01: Incident noise filter (`is_incident_noise`) excludes transient runtime crashes and degradation reports (`[autocontrol-...]`, `[computer-use:...]`, `incident-report`). +- [x] AC-02: `planfile sync fleet` discovers repositories configured with GitHub and performs bounded inbound synchronization. +- [x] AC-03: `planfile sync fleet --install-timer` generates, registers, and starts a 6-hour systemd user timer (`planfile-fleet-sync.timer` & `planfile-fleet-sync.service`). +- [x] AC-04: `planfile ticket create` inspects and synchronizes remote GitHub issues into local Planfile prior to creating new tickets when remote integration is configured, with `--inbound-sync / --no-inbound-sync` control and graceful failure handling. +- [x] AC-05: Unit and integration tests in `tests/test_fleet_sync.py` and `tests/test_ticket_create_inbound_sync.py` pass without regression. + +## Implementation details + +- `planfile/sync/operations.py`: + - Added `is_incident_noise(ext_ticket)` detecting transient crash logs and degradation reports. + - Added `exclude_incident_noise: bool = False` to `sync_from_external`. +- `planfile/cli/groups/sync/core.py`: + - Propagated `exclude_incident_noise` through `_execute_sync_with_progress` and `sync_integration`. +- `planfile/cli/groups/sync/fleet.py`: + - Created fleet synchronization module: `discover_fleet_repositories`, `sync_fleet`, `install_fleet_systemd_timer`, `uninstall_fleet_systemd_timer`, `status_fleet_systemd_timer`, and `fleet_cmd`. +- `planfile/cli/groups/sync/commands.py` & `planfile/cli/groups/sync/__init__.py`: + - Registered `fleet_cmd` under `planfile sync fleet`. +- `planfile/cli/groups/ticket/commands.py`: + - Added `inbound_sync` option and `_inbound_sync_before_create` helper to reconcile remote issues before local ticket creation. +- `tests/test_fleet_sync.py`: + - Added comprehensive tests for noise detection, repo discovery, systemd unit generation, and CLI dry-run. +- `tests/test_ticket_create_inbound_sync.py`: + - Added tests for automatic inbound synchronization, `--no-inbound-sync` override, and error tolerance. diff --git a/project/ticket-278/intent.json b/project/ticket-278/intent.json new file mode 100644 index 00000000..919e1caa --- /dev/null +++ b/project/ticket-278/intent.json @@ -0,0 +1,27 @@ +{ + "schema": "new-project.intent/v3", + "ticket": "ticket-278", + "summary": "Fleet sync and inbound GitHub sync on ticket creation", + "workstream": "application", + "classification": { + "kind": "FEATURE", + "priority": "P2", + "origin": "requested" + }, + "allowedPaths": [ + "project/ticket-278/**", + "TODO.md", + "project/TICKETS.md", + "planfile/cli/groups/sync/**", + "planfile/cli/groups/ticket/**", + "planfile/sync/**", + "tests/**" + ], + "forbiddenPaths": [ + "project/ticket-*/user-*.md" + ], + "stacks": [], + "dependsOn": [], + "conflictsWith": [], + "integrationTicket": null +} diff --git a/tests/test_fleet_sync.py b/tests/test_fleet_sync.py new file mode 100644 index 00000000..2e99def2 --- /dev/null +++ b/tests/test_fleet_sync.py @@ -0,0 +1,94 @@ +"""Tests for fleet synchronization and 6-hour systemd schedule generation.""" + +from unittest.mock import patch + +import pytest +import typer +from typer.testing import CliRunner + +from planfile.cli.groups.sync import register_sync_commands +from planfile.cli.groups.sync.fleet import ( + discover_fleet_repositories, + generate_service_content, + generate_timer_content, + sync_fleet, +) +from planfile.sync.operations import is_incident_noise + + +@pytest.fixture() +def sync_cli(): + app = typer.Typer() + register_sync_commands(app) + return app + + +def test_is_incident_noise_detects_crash_and_degradation(): + assert is_incident_noise({"id": "1", "name": "[computer-use:autocontrol-browser] Auto-detected degradation: browser_navigation_stalled"}) + assert is_incident_noise({"id": "2", "name": "[autocontrol-browser] Runtime crash: cdp session died"}) + assert is_incident_noise({"id": "3", "name": "Runtime crash: segmentation fault"}) + assert is_incident_noise({"id": "4", "name": "Auto-detected degradation: latency spike"}) + assert is_incident_noise({"id": "5", "name": "Fix navigation in cdp_form", "labels": ["incident", "browser"]}) + assert is_incident_noise({"id": "6", "name": "Memory issue", "labels": ["incident-report"]}) + assert not is_incident_noise({"id": "7", "name": "Implement user authentication", "labels": ["feature", "auth"]}) + assert not is_incident_noise({"id": "8", "name": "Refactor database models", "labels": ["task"]}) + + +def test_discover_fleet_repositories(tmp_path): + # Repo 1: valid with github integration + repo1 = tmp_path / "org" / "proj1" + planfile1 = repo1 / ".planfile" + planfile1.mkdir(parents=True) + (planfile1 / "github.planfile.yaml").write_text("integrations:\n github:\n repo: org/proj1\n") + + # Repo 2: planfile present but no github + repo2 = tmp_path / "org" / "proj2" + planfile2 = repo2 / ".planfile" + planfile2.mkdir(parents=True) + + # Repo 3: no planfile + repo3 = tmp_path / "org" / "proj3" + repo3.mkdir(parents=True) + + discovered = discover_fleet_repositories(tmp_path, max_depth=2) + assert len(discovered) == 1 + path, gh_repo = discovered[0] + assert path == repo1 + assert gh_repo == "org/proj1" + + +def test_generate_service_and_timer_content(tmp_path): + service = generate_service_content(root=tmp_path, planfile_bin="/usr/local/bin/planfile") + assert "/usr/local/bin/planfile sync fleet" in service + assert str(tmp_path.resolve()) in service + + timer = generate_timer_content(interval_hours=6) + assert "OnUnitActiveSec=6h" in timer + assert "Unit=planfile-fleet-sync.service" in timer + + +def test_sync_fleet_runs_bounded_integration(tmp_path): + repo1 = tmp_path / "group" / "repo1" + planfile1 = repo1 / ".planfile" + planfile1.mkdir(parents=True) + (planfile1 / "github.planfile.yaml").write_text("integrations:\n github:\n repo: group/repo1\n") + + with patch("planfile.cli.groups.sync.fleet.sync_integration") as mock_sync: + stats = sync_fleet(tmp_path, max_depth=2, dry_run=True, exclude_incident_noise=True) + assert stats["scanned"] == 1 + assert stats["synced"] == 1 + assert stats["failed"] == 0 + mock_sync.assert_called_once() + args, kwargs = mock_sync.call_args + assert args[0] == "github" + assert args[1] == str(repo1) + assert kwargs["direction"] == "from" + assert kwargs["dry_run"] is True + assert kwargs["exclude_incident_noise"] is True + + +def test_fleet_cli_dry_run(sync_cli, tmp_path): + runner = CliRunner() + result = runner.invoke(sync_cli, ["sync", "fleet", str(tmp_path), "--dry-run"]) + assert result.exit_code == 0 + assert "No GitHub-integrated repositories found" in result.output diff --git a/tests/test_ticket_create_inbound_sync.py b/tests/test_ticket_create_inbound_sync.py new file mode 100644 index 00000000..40349ac5 --- /dev/null +++ b/tests/test_ticket_create_inbound_sync.py @@ -0,0 +1,75 @@ +"""Tests for inbound synchronization before ticket creation.""" + +from unittest.mock import patch + +import pytest +import typer +from typer.testing import CliRunner + +from planfile import Planfile +from planfile.cli.groups.ticket import register_ticket_commands + + +@pytest.fixture() +def ticket_cli(): + app = typer.Typer() + register_ticket_commands(app) + return app + + +@pytest.fixture() +def initialized_repo(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + pf = Planfile(str(tmp_path)) + pf.store.init() + return tmp_path + + +class TestTicketCreateInboundSync: + def test_inbound_sync_triggered_by_default_when_github_configured( + self, ticket_cli, initialized_repo + ): + github_config = initialized_repo / ".planfile" / "github.planfile.yaml" + github_config.write_text("integrations:\n github:\n repo: owner/repo\n") + + runner = CliRunner() + with patch("planfile.cli.groups.ticket.commands._inbound_sync_before_create") as mock_inbound, \ + patch("planfile.cli.groups.ticket.commands._auto_sync"): + result = runner.invoke(ticket_cli, ["ticket", "create", "Inbound sync check"]) + assert result.exit_code == 0 + assert mock_inbound.called + args, kwargs = mock_inbound.call_args + assert args[0] == str(initialized_repo) + assert args[1] == ["github"] + assert kwargs.get("dry_run") is False + + def test_no_inbound_sync_flag_skips_inbound_check( + self, ticket_cli, initialized_repo + ): + github_config = initialized_repo / ".planfile" / "github.planfile.yaml" + github_config.write_text("integrations:\n github:\n repo: owner/repo\n") + + runner = CliRunner() + with patch("planfile.cli.groups.ticket.commands._inbound_sync_before_create") as mock_inbound, \ + patch("planfile.cli.groups.ticket.commands._auto_sync"): + result = runner.invoke( + ticket_cli, ["ticket", "create", "Skip inbound", "--no-inbound-sync"] + ) + assert result.exit_code == 0 + mock_inbound.assert_not_called() + + def test_inbound_sync_failure_does_not_block_ticket_creation( + self, ticket_cli, initialized_repo + ): + github_config = initialized_repo / ".planfile" / "github.planfile.yaml" + github_config.write_text("integrations:\n github:\n repo: owner/repo\n") + + runner = CliRunner() + with patch( + "planfile.cli.groups.sync.core.sync_integration", + side_effect=RuntimeError("GitHub API rate limit exceeded"), + ), patch("planfile.cli.groups.ticket.commands._auto_sync"): + result = runner.invoke(ticket_cli, ["ticket", "create", "Resilient ticket"]) + assert result.exit_code == 0 + assert "Created PLF-001: Resilient ticket" in result.output + assert "Inbound sync from github skipped" in result.output