diff --git a/planfile/cli/groups/sync/core.py b/planfile/cli/groups/sync/core.py index 8e2dbaa8..53d2d511 100644 --- a/planfile/cli/groups/sync/core.py +++ b/planfile/cli/groups/sync/core.py @@ -3,6 +3,7 @@ from __future__ import annotations import glob +from copy import deepcopy from pathlib import Path from typing import Any @@ -12,7 +13,13 @@ from planfile.cli.core import console, print_error, print_warning from planfile.integrations.config import IntegrationConfig -from planfile.sync.operations import sync_from_external +from planfile.sync.github import GitHubBackend +from planfile.sync.operations import ( + _bind_sync_state, + _extract_ticket_data, + _ticket_external_id, + sync_from_external, +) from planfile.sync.outbound import OutboundSyncError, sync_to_external from planfile.sync.ticket_comments import sync_pending_comments @@ -229,6 +236,182 @@ def _load_tickets_for_sync( return all_tickets, tickets_source, v1_source_file, v1_data +class _InboundObservation: + """Retain this pass's provider states without changing backend capabilities.""" + + project_remote_status = staticmethod(GitHubBackend.project_remote_status) + + def __init__(self, backend, legacy_plans=None): + self.backend = backend + self.states = {} + self.legacy_plans = legacy_plans or {} + self.guard = None + + def resolve_repository_identity(self, *args, **kwargs): + resolver = getattr(type(self.backend), "resolve_repository_identity", None) + return resolver(self.backend, *args, **kwargs) if callable(resolver) else None + + def _bind_repository_identity(self, identity): + binder = getattr(type(self.backend), "_bind_repository_identity", None) + if callable(binder): + binder(self.backend, identity) + + def update_ticket(self, remote_id, **changes): + if self.guard is not None: + self.guard() + # Lifecycle belongs to inbound in both. A closure after that read + # must survive a later metadata edit; normal readback reports drift. + changes.pop("status", None) + return self.backend.update_ticket(remote_id, **changes) + + def create_ticket(self, ticket): + if self.guard is not None: + self.guard() + return self.backend.create_ticket(ticket) + + def __getattr__(self, name): + value = getattr(self.backend, name) + if name not in {"list_tickets", "list_selected_tickets"} or not callable(value): + return value + + def observe(*args, **kwargs): + result = value(*args, **kwargs) + if result is None: + return None + tickets = deepcopy(list(result)) + for ticket in tickets: + data = _extract_ticket_data(ticket) + previous = self.states.setdefault(data["id"], data["status"]) + if previous != data["status"]: + raise ValueError("sync_inbound_conflicting_remote_states") + if data["id"] in self.legacy_plans: + description = self.legacy_plans[data["id"]] + if isinstance(ticket, dict): + ticket["description"] = description + else: + ticket.description = description + return tickets + + return observe + + +class _LocalPlanningStore: + """Preserve this SDK snapshot's planning text while retaining normal CAS.""" + + def __init__(self, store): + self.store = store + + def __getattr__(self, name): + return getattr(self.store, name) + + def update_ticket(self, ticket_id, **changes): + snapshot = changes.get("expected_snapshot") + if not isinstance(snapshot, dict): + raise ValueError("sync_planning_requires_snapshot") + if "description" in changes: + changes["description"] = snapshot.get("description", "") + return self.store.update_ticket(ticket_id, **changes) + + + +class _OutboundSnapshotStore: + """Persist only backend references under exact native snapshot preconditions.""" + + def __init__(self, store, tickets): + self.store, self.payloads = store, dict(tickets) + self.snapshots, self.rejected = {}, set() + for key, payload in tickets: + located = store._locate_ticket_source(key) + if located is None or located[1] != payload: + raise ValueError("sync_outbound_snapshot_changed") + self.snapshots[key] = (located[0], deepcopy(located[1])) + + def __getattr__(self, name): + return getattr(self.store, name) + + def check(self, key): + located = self.store._locate_ticket_source(key) + if located is None or located != self.snapshots[key]: + raise ValueError("sync_outbound_snapshot_changed") + + def check_all(self): + for key in self.snapshots: + self.check(key) + + def _all_sprint_ids(self): + return list(dict.fromkeys(section for section, _ in self.snapshots.values())) + + def load_sprint(self, section): + return {"tickets": {key: deepcopy(data) for key, (physical, data) in self.snapshots.items() + if physical == section}} + + def save_sprint(self, section, data): + pending = [(key, payload) for key, payload in data.get("tickets", {}).items() + if key in self.payloads and payload is self.payloads[key]] + if not pending: + raise ValueError("sync_outbound_payload_required") + for key, payload in pending: + if key in self.rejected: + continue + try: + self.check(key) + physical, snapshot = self.snapshots[key] + if physical != section: + raise ValueError("sync_outbound_section_changed") + reference = deepcopy(payload.get("sync") or {}) + if reference != (snapshot.get("sync") or {}): + saved = self.store.update_ticket(key, sync=reference, expected_snapshot=snapshot) + located, current = self.store._locate_ticket_source(key), self.store.get_ticket(key) + if (saved is None or current is None or located is None + or saved.model_dump(mode="json") != current.model_dump(mode="json") + or any(located[1].get(k) != snapshot.get(k) + for k in set(located[1]) | set(snapshot) + if k not in {"sync", "updated_at", "history"})): + raise ValueError("sync_outbound_snapshot_changed") + self.snapshots[key] = (located[0], deepcopy(located[1])) + except Exception: + self.rejected.add(key) + raise + + def save_backlog(self, data): + self.save_sprint("backlog", data) + + +def _legacy_planning_descriptions(backend, store, tickets): + state = _bind_sync_state(Path(store.base_dir), "github", backend, dry_run=True) + plans = {} + for ticket_id, ticket in tickets: + remote_id = _ticket_external_id(ticket, ticket_id, "github", state) + if remote_id is not None: + description = ticket.get("description", "") + if remote_id in plans and plans[remote_id] != description: + raise ValueError("sync_ambiguous_local_planning") + plans[remote_id] = description + return plans + + +def _github_reconciled_outbound(backend, store, tickets, observed): + """Leave native lifecycle conflicts and unobserved mappings for explicit sync.""" + state = _bind_sync_state(Path(store.base_dir), "github", backend, dry_run=True) + eligible = [] + deferred = [] + for ticket_id, ticket in tickets: + remote_id = _ticket_external_id(ticket, ticket_id, "github", state) + if remote_id is not None and ( + remote_id not in observed + or GitHubBackend.project_remote_status(ticket.get("status")) != observed[remote_id] + ): + deferred.append(ticket_id) + else: + eligible.append((ticket_id, ticket)) + if deferred: + print_warning( + f"Deferred {len(deferred)} mapped ticket(s): lifecycle conflict or no inbound " + "observation. Reconcile intent before explicit --direction to." + ) + return eligible, deferred + + def _execute_sync_with_progress( backend: Any, all_tickets: list[tuple[str, dict]], @@ -244,22 +427,23 @@ def _execute_sync_with_progress( remote_labels: list[str] | None = None, exclude_incident_noise: bool = False, ) -> None: - """Execute sync with progress bar.""" + """Execute sync; GitHub both observes inbound before outbound mutation.""" + inbound_first = integration_name == "github" and direction == "both" + legacy_plans = ( + _legacy_planning_descriptions(backend, store, all_tickets) + if inbound_first and v1_source_file else None + ) + observer = _InboundObservation(backend, legacy_plans) if inbound_first else None + inbound_store = _LocalPlanningStore(store) if inbound_first and not v1_source_file else store + deferred = [] with Progress( SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console ) as progress: - if direction in ["to", "both"]: - task = progress.add_task("Syncing to external system...", total=None) - sync_to_external( - backend, all_tickets, dry_run, store, integration_name, v1_source_file, v1_data - ) - progress.update(task, description="[green]✓ Synced to external system[/green]") - - if direction in ["from", "both"]: + def pull(): task = progress.add_task("Syncing from external system...", total=None) sync_from_external( - backend, - store, + observer if inbound_first else backend, + inbound_store, dry_run, integration_name, v1_source_file, @@ -272,6 +456,45 @@ def _execute_sync_with_progress( ) progress.update(task, description="[green]✓ Synced from external system[/green]") + if inbound_first: + pull() + if dry_run: + console.print( + "[dim]Outbound preview deferred: inbound dry-run is not persisted. " + "Use --direction to for a local-only outbound preview.[/dim]" + ) + return + all_tickets, _, v1_source_file, v1_data = _load_tickets_for_sync( + store, str(store.project_dir), integration_name, + ticket_ids=ticket_ids, sprint_ids=sprint_ids, + ) + all_tickets, deferred = _github_reconciled_outbound( + backend, store, all_tickets, observer.states + ) + + outbound_store = store + if inbound_first and not v1_source_file: + all_tickets = deepcopy(all_tickets) + outbound_store = _OutboundSnapshotStore(store, all_tickets) + observer.guard = outbound_store.check_all + if direction in ["to", "both"] and (all_tickets or not inbound_first): + task = progress.add_task("Syncing to external system...", total=None) + sync_to_external( + observer if inbound_first else backend, all_tickets, dry_run, outbound_store, + integration_name, v1_source_file, v1_data + ) + if inbound_first and not v1_source_file: + outbound_store.check_all() + progress.update(task, description="[green]✓ Synced to external system[/green]") + + if deferred: + # Keep successful receipts, but do not claim the full selection is + # synchronized or deliver queued comments for unresolved work. + raise typer.Exit(2) + + if direction in ["from", "both"] and not inbound_first: + pull() + def sync_integration( integration_name: str, diff --git a/project/TICKETS.md b/project/TICKETS.md index 4651616d..2ab37186 100644 --- a/project/TICKETS.md +++ b/project/TICKETS.md @@ -175,4 +175,5 @@ This file indexes governance tickets without taking ownership of | **ticket-274** | [`README.md`](./ticket-274/README.md) | - | - | - | - | - | | **ticket-275** | [`README.md`](./ticket-275/README.md) | - | - | - | - | - | | **ticket-277** | [`README.md`](./ticket-277/README.md) | - | - | - | - | - | +| **ticket-279** | [`README.md`](./ticket-279/README.md) | Prevent stale bidirectional sync and owner overwrites | BUG | P1 | health | application | diff --git a/project/ticket-279/README.md b/project/ticket-279/README.md new file mode 100644 index 00000000..2863eb34 --- /dev/null +++ b/project/ticket-279/README.md @@ -0,0 +1,56 @@ +# Ticket 279: Prevent bidirectional GitHub sync from reopening stale remote closures + +- **ID**: ticket-279 +- **Owner**: agent:codex-heyasa-audit +- **Status**: IN_PROGRESS +- **Workflow state**: PUBLICATION +- **Created**: 2026-11-05 + +## Goal and scope + +SESSION_EXECUTION_AUTHORIZATION: the user requested investigation and immediate +repair of Heyasa dependencies and Planfile/GitHub synchronization on 2026-11-05. +Coordination request: PLF-20370; parent workspace request: PLF-19975. + +For `--direction both`, read GitHub before writing and reload the selected local +snapshot after inbound changes. The current outbound-first order can reopen a +remotely closed issue from a stale local open record. Preserve explicit one-way +semantics, exact repository/ticket/sprint selection, dry-run immutability and +native lifecycle guards. Do not force native blocked or terminal transitions. + +## Acceptance criteria + +- [x] AC-01: Session execution authorization and bounded scope recorded. +- [x] AC-02: Regression proves remote closure survives bidirectional sync and + outbound uses the refreshed selected snapshot. +- [x] AC-03: Inbound failure prevents outbound effects; unrelated records and + dry-run storage remain unchanged; native and legacy storage are covered. +- [ ] AC-04: Required checks and independent protected publication complete. + +## Implementation and validation + +The explicit operator decision on 2026-11-06 approved exactly this existing +allocation and its unchanged intent for a bounded initial source admission. +The deployed protected controller issued editing lease +`lease-c1b42dc54857ad048e6def49f710c7e6`, revision2/fencing838. Foreign ticket280 +and its primary checkout files remain preserved. This receipt grants no merge +approval and no renewal or takeover. + +GitHub both-direction synchronization now observes inbound first and reloads +the exact selected records. Native planning and live execution ownership stay +protected. Outbound uses detached payloads and exact raw snapshots, persists +only backend references through the existing CAS API and fails without +clobbering same-revision owner plans, notes or execution. Lifecycle conflicts +retain successful other receipts and prevent false full completion/comments. +Explicit one-way, non-GitHub and legacy behaviors retain their regression cases. + +Native source tests:128passed,0skipped (93directregressions+35existing scope/identity controls) for test_sync_bidirectional_order.py and +test_sync_failure_status.py. Supplementary immutable-model tests also cover +existing scope/identity contracts. Ruff import organization is applied with +this repository's configuration. Required source governance and independent +publication remain separately verified; no required hosted/OS context waived. +Historical V1/V2 proposals were not applied unchanged. + +Coordination: sourcePLF-20370/#339 and parentPLF-19975. Global managed-body and +outbound API persistence remain owned byPLF-20372/#341; this bounded CLI guard +does not claim that broader producer issue is resolved. diff --git a/project/ticket-279/intent.json b/project/ticket-279/intent.json new file mode 100644 index 00000000..9111766a --- /dev/null +++ b/project/ticket-279/intent.json @@ -0,0 +1,91 @@ +{ + "schema": "new-project.intent/v3", + "ticket": "ticket-279", + "summary": "Prevent bidirectional GitHub sync from reopening stale remote closures", + "workstream": "application", + "classification": { + "kind": "BUG", + "priority": "P1", + "origin": "health" + }, + "allowedPaths": [ + "project/ticket-279/**", + "TODO.md", + "project/TICKETS.md", + "planfile/cli/groups/sync/core.py", + "tests/test_sync_bidirectional_order.py", + "tests/test_sync_failure_status.py" + ], + "forbiddenPaths": [ + "project/ticket-*/user-*.md" + ], + "stacks": [], + "dependsOn": [], + "conflictsWith": [], + "integrationTicket": null, + "delivery": { + "acceptedBaseSha": "edfa131b22ae8f6081d9c90489d9689f5075337a", + "targetBranch": "main", + "outcome": "Bidirectional GitHub sync observes inbound state before any outbound mutation and reloads the selected local snapshot after reconciliation.", + "nonGoals": [ + "No forced native blocked or terminal state changes", + "No provider cache/credential/controller policy changes", + "No bulk-read performance redesign or new dependencies" + ], + "complexity": "S", + "estimatedMinutes": 30, + "budgets": { + "maxImplementationFiles": 3, + "maxAffectedComponents": 1, + "maxPublicInterfaceChanges": 0, + "maxRuntimeDependencies": 0 + }, + "architecture": { + "status": "accepted", + "decision": "Keep the existing sync orchestrator and adapter contracts; order its phases and reload through the existing scoped loader.", + "components": [ + { + "name": "GitHub sync orchestration", + "paths": [ + "planfile/cli/groups/sync/core.py", + "tests/test_sync_bidirectional_order.py", + "tests/test_sync_failure_status.py" + ] + } + ], + "responsibilityChanges": false, + "interfaceChanges": [], + "dataChanges": [], + "ui": { + "impact": "none", + "states": [], + "evidence": [] + }, + "rollback": "Revert only the bounded implementation change through its protected delivery process; preserve already reconciled operational ticket state." + }, + "runtimeDependencies": [], + "validation": [ + { + "criterion": "AC-02", + "commands": [ + "python -m pytest tests/test_sync_bidirectional_order.py -q" + ], + "evidence": "Pending admitted canonical checkout execution; no test result claimed." + }, + { + "criterion": "AC-03", + "commands": [ + "python -m pytest tests/test_sync_bidirectional_order.py tests/test_sync_failure_status.py -q" + ], + "evidence": "Pending scoped regression, failure, legacy-store and dry-run coverage." + }, + { + "criterion": "AC-04", + "commands": [ + "./project/governance-check.sh" + ], + "evidence": "Pending required stack checks, exact-head independent review and protected delivery." + } + ] + } +} diff --git a/tests/test_sync_bidirectional_order.py b/tests/test_sync_bidirectional_order.py new file mode 100644 index 00000000..c3bea8bf --- /dev/null +++ b/tests/test_sync_bidirectional_order.py @@ -0,0 +1,383 @@ +"""Offline regressions for GitHub inbound-first reconciliation and lifecycle intent.""" + +from copy import deepcopy + +import pytest +import typer +import yaml + +from planfile.cli.groups.sync import core +from planfile.core.store import PlanfileStore, Ticket +from planfile.sync.base import TicketRef, TicketState +from planfile.sync.github import GitHubBackend +from planfile.sync.state import SyncState + + +class Backend: + config = {"repo": "fixture/repo"} + + def __init__(self, status="closed", reason="completed"): + self.remote = {"42": TicketState( + id="42", name="remote title", description="remote evidence", status=status, + url="https://github.com/fixture/repo/issues/42", + metadata={"state_reason": reason}, + )} + self.events = [] + self.fail = False + self.omit = False + + def list_tickets(self, **kwargs): + return self.list_selected_tickets(set(self.remote), **kwargs) + + def list_selected_tickets(self, ids, **kwargs): + self.events.append(("read", sorted(ids), kwargs)) + if self.fail: + raise TimeoutError("controlled offline inbound failure") + return [] if self.omit else [deepcopy(t) for id, t in self.remote.items() if id in ids] + + def get_ticket(self, id): + return self.remote[str(id)] + + def update_ticket(self, id, **fields): + self.events.append(("update", str(id), fields)) + if "status" in fields: + self.remote[str(id)].status = GitHubBackend.project_remote_status(fields["status"]) + self.remote[str(id)].name = fields["name"] + self.remote[str(id)].description = fields["body"] + + def create_ticket(self, ticket): + self.events.append(("create", ticket)) + self.remote["900"] = TicketState( + id="900", name=ticket["name"], description=ticket.get("description", ""), + status=GitHubBackend.project_remote_status(ticket.get("status")), + ) + return TicketRef(id="900", url="https://github.com/fixture/repo/issues/900") + + +@pytest.fixture(params=["yaml", "sharded", "legacy"]) +def sample(tmp_path, request): + selected = {"id": "PLF-001", "name": "stale title", "status": "open", + "sprint": "backlog", "integration": ["github"], + "sync": {"github": {"id": "42", "repository": "fixture/repo"}}} + unrelated = {**deepcopy(selected), "id": "PLF-002", "name": "unrelated", + "sync": {"github": {"id": "43", "repository": "fixture/repo"}}} + store = PlanfileStore(tmp_path) + legacy = request.param == "legacy" + if legacy: + (tmp_path / "tickets.planfile.yaml").write_text(yaml.safe_dump({ + "backlog": {"tickets": {t["id"]: t for t in [selected, unrelated]}} + })) + else: + store.init() + for t in [selected, unrelated]: + store.create_ticket(Ticket(**t)) + if request.param == "sharded": + store.migrate_to_sharded_yaml() + return store, Backend(), legacy + + +def loaded(sample): + store, _, _ = sample + return core._load_tickets_for_sync(store, str(store.project_dir), "github") + + +def records(sample): + return dict(loaded(sample)[0]) + + +def replace_record(sample, id, **changes): + store, _, legacy = sample + if legacy: + path = store.project_dir / "tickets.planfile.yaml" + data = yaml.safe_load(path.read_text()) + data["backlog"]["tickets"][id].update(changes) + path.write_text(yaml.safe_dump(data)) + else: + store.update_ticket(id, **changes) + + +def run(sample, direction="both", dry_run=False): + store, backend, _ = sample + tickets, _, source, data = core._load_tickets_for_sync( + store, str(store.project_dir), "github", ticket_ids=["PLF-001"] + ) + core._execute_sync_with_progress( + backend, tickets, dry_run, store, "github", source, data, direction, + ticket_ids=["PLF-001"], + ) + + +@pytest.mark.parametrize("reason,status", [("completed", "done"), ("not_planned", "canceled"), (None, "blocked")]) +def test_remote_closure_is_not_reopened_and_scoped_snapshot_is_reloaded(sample, reason, status): + store, backend, _ = sample + backend.remote["42"].metadata["state_reason"] = reason + untouched = deepcopy(records(sample)["PLF-002"]) + if status == "blocked": + with pytest.raises(typer.Exit) as caught: + run(sample) + assert caught.value.exit_code == 2 + else: + run(sample) + after = records(sample) + assert after["PLF-001"]["status"] == status + assert after["PLF-001"]["name"] == "remote title" + assert after["PLF-002"] == untouched + assert backend.events[0][0] == "read" + assert backend.remote["42"].status == "closed" + updates = [e for e in backend.events if e[0] == "update"] + assert len(updates) == (0 if status == "blocked" else 1) + if updates: + assert updates[0][2]["name"] == "remote title" + assert "status" not in updates[0][2] + + +@pytest.mark.parametrize("local,remote", [("blocked", "closed"), ("done", "open"), ("canceled", "open"), ("failed", "open")]) +def test_conflicting_native_lifecycle_is_preserved_on_both_sides(sample, local, remote): + replace_record(sample, "PLF-001", status=local) + backend = sample[1] + backend.remote["42"].status = remote + with pytest.raises(typer.Exit) as caught: + run(sample) + assert caught.value.exit_code == 2 + assert records(sample)["PLF-001"]["status"] == local + assert backend.remote["42"].status == remote + assert [e[0] for e in backend.events] == ["read"] + + +def test_matching_blocked_open_mapping_can_still_publish_content(sample): + replace_record(sample, "PLF-001", status="blocked") + sample[1].remote["42"].status = "open" + run(sample) + assert [e[0] for e in sample[1].events] == ["read", "update"] + assert records(sample)["PLF-001"]["status"] == "blocked" + + +def test_unobserved_mapping_is_not_blindly_published(sample): + sample[1].omit = True + before = deepcopy(records(sample)) + with pytest.raises(typer.Exit) as caught: + run(sample) + assert caught.value.exit_code == 2 + assert records(sample) == before + assert [e[0] for e in sample[1].events] == ["read"] + + +def test_inbound_failure_prevents_any_outbound_mutation(sample): + sample[1].fail = True + before = deepcopy(records(sample)) + with pytest.raises(RuntimeError, match="sync_inbound_fetch_failed"): + run(sample) + assert records(sample) == before + assert [e[0] for e in sample[1].events] == ["read"] + + +def test_both_dry_run_previews_inbound_without_stale_outbound_or_writes(sample, capsys): + store, backend, _ = sample + before = deepcopy(records(sample)) + run(sample, dry_run=True) + assert records(sample) == before + assert [e[0] for e in backend.events] == ["read"] + assert not (store.base_dir / "sync/github.receipts.jsonl").exists() + assert "Outbound preview deferred" in capsys.readouterr().out + + +def test_explicit_to_can_apply_local_lifecycle_without_inbound(sample): + run(sample, direction="to") + assert [e[0] for e in sample[1].events] == ["update"] + assert sample[1].remote["42"].status == "open" + + +def test_from_remains_read_only_towards_provider(sample): + run(sample, direction="from") + assert [e[0] for e in sample[1].events] == ["read"] + assert records(sample)["PLF-001"]["status"] == "done" + + +def test_unmapped_local_ticket_can_be_published_after_inbound(sample): + replace_record(sample, "PLF-001", sync={}) + run(sample) + assert [e[0] for e in sample[1].events] == ["read", "create"] + assert records(sample)["PLF-001"]["sync"]["github"]["id"] == "900" + + +def test_state_file_only_mapping_receives_same_protection(sample): + replace_record(sample, "PLF-001", sync={}) + store, backend, _ = sample + SyncState.from_backend(store.base_dir, "github", backend).save_sync({"PLF-001": "42"}) + backend.omit = True + with pytest.raises(typer.Exit) as caught: + run(sample) + assert caught.value.exit_code == 2 + assert [e[0] for e in backend.events] == ["read"] + + +def test_non_github_both_retains_existing_phase_order(monkeypatch, tmp_path): + calls = [] + monkeypatch.setattr(core, "sync_from_external", lambda *a, **kw: calls.append("from")) + monkeypatch.setattr(core, "sync_to_external", lambda *a, **kw: calls.append("to")) + core._execute_sync_with_progress(object(), [], False, PlanfileStore(tmp_path), "jira", None, None, "both") + assert calls == ["to", "from"] + + +def test_both_preserves_unpublished_planning_and_publishes_it(sample): + planning = "accepted local scope not published yet" + replace_record(sample, "PLF-001", description=planning) + run(sample) + assert records(sample)["PLF-001"]["description"] == planning + assert sample[1].remote["42"].description == planning + assert sample[1].remote["42"].status == "closed" + + +def test_explicit_from_retains_intentional_remote_description_import(sample): + replace_record(sample, "PLF-001", description="unpublished local plan") + run(sample, direction="from") + assert records(sample)["PLF-001"]["description"] == "remote evidence" + assert [event[0] for event in sample[1].events] == ["read"] + + +@pytest.mark.parametrize("sample", ["yaml", "sharded"], indirect=True) +def test_native_preserves_snapshot_plan_newer_than_initial_selection(sample): + store, backend, legacy = sample + tickets, _, source, data = core._load_tickets_for_sync( + store, str(store.project_dir), "github", ticket_ids=["PLF-001"] + ) + store.update_ticket("PLF-001", description="newer accepted scope before inbound snapshot") + core._execute_sync_with_progress( + backend, tickets, False, store, "github", source, data, "both", + ticket_ids=["PLF-001"], + ) + assert records(sample)["PLF-001"]["description"] == "newer accepted scope before inbound snapshot" + assert backend.remote["42"].description == "newer accepted scope before inbound snapshot" + + +@pytest.mark.parametrize("sample", ["yaml", "sharded"], indirect=True) +def test_native_cas_still_rejects_owner_update_during_fetch(sample, monkeypatch): + store, backend, legacy = sample + original = backend.list_selected_tickets + + def concurrent(*args, **kwargs): + store.update_ticket("PLF-001", description="concurrent owner plan") + return original(*args, **kwargs) + + monkeypatch.setattr(backend, "list_selected_tickets", concurrent) + with pytest.raises(ValueError): + run(sample) + assert records(sample)["PLF-001"]["description"] == "concurrent owner plan" + assert [event[0] for event in backend.events] == ["read"] + + +@pytest.mark.parametrize("sample", ["yaml", "sharded"], indirect=True) +def test_native_live_worker_is_not_closed_by_both(sample): + _, backend, legacy = sample + replace_record(sample, "PLF-001", status="in_progress", description="active owner plan", + execution={"state": "running", "assigned_to": "other-owner", + "lease_expires_at": "2099-01-01T00:00:00Z"}) + before = deepcopy(records(sample)["PLF-001"]) + with pytest.raises(ValueError, match="execution_reconciliation"): + run(sample) + assert records(sample)["PLF-001"] == before + assert [event[0] for event in backend.events] == ["read"] + + +def test_closure_during_metadata_update_survives_and_fails_readback(sample, monkeypatch): + backend = sample[1] + backend.remote["42"].status = "open" + original = backend.update_ticket + + def concurrent(remote_id, **fields): + backend.remote[remote_id].status = "closed" + return original(remote_id, **fields) + + monkeypatch.setattr(backend, "update_ticket", concurrent) + from planfile.sync.outbound import OutboundSyncError + with pytest.raises(OutboundSyncError): + run(sample) + assert backend.remote["42"].status == "closed" + assert "status" not in next(event[2] for event in backend.events if event[0] == "update") + + +def test_observer_keeps_numeric_repository_identity_validation(sample): + from planfile.sync.state import SyncStateRepositoryMismatch + store, _, _ = sample + + class IdentityBackend(Backend): + def resolve_repository_identity(self, repository=None): + self.events.append(("identity", repository)) + return {"repository": "fixture/repo", "repository_id": "999"} + + backend = IdentityBackend() + state = SyncState(store.base_dir, "github", repository="fixture/repo") + state.state_file.parent.mkdir(parents=True, exist_ok=True) + state.state_file.write_text(yaml.safe_dump({"version": 2, "backend": "github", + "repository": "fixture/repo", "repository_id": "123", "ticket_map": {"PLF-001": "42"}})) + before = state.state_file.read_bytes() + tickets, _, source, data = loaded(sample) + with pytest.raises(SyncStateRepositoryMismatch): + core._execute_sync_with_progress(backend, tickets, False, store, "github", + source, data, "both", ticket_ids=["PLF-001"]) + assert state.state_file.read_bytes() == before + assert all(event[0] == "identity" for event in backend.events) + + +def test_selected_conflict_does_not_hide_safe_other_delivery(sample): + store, backend, _ = sample + replace_record(sample, "PLF-001", status="blocked") + backend.remote["43"] = backend.remote["42"].model_copy(update={"id": "43", + "url": "https://github.com/fixture/repo/issues/43"}) + tickets, _, source, data = loaded(sample) + with pytest.raises(typer.Exit) as caught: + core._execute_sync_with_progress(backend, tickets, False, store, "github", + source, data, "both", ticket_ids=["PLF-001", "PLF-002"]) + assert caught.value.exit_code == 2 + assert [event[1] for event in backend.events if event[0] == "update"] == ["43"] + assert records(sample)["PLF-001"]["status"] == "blocked" + assert records(sample)["PLF-002"]["status"] == "done" + + +@pytest.mark.parametrize("sample", ["yaml", "sharded"], indirect=True) +@pytest.mark.parametrize("field", ["description", "outputs", "execution"]) +def test_native_outbound_preserves_same_revision_owner_write(sample, monkeypatch, field): + from planfile.sync.outbound import OutboundSyncError + store, backend, _ = sample + backend.remote["42"].status = "open" + original = backend.update_ticket + def concurrent(*args, **kwargs): + result = original(*args, **kwargs) + section = store.load_backlog() + ticket = section["tickets"]["PLF-001"] + if field == "description": + ticket[field] = "late accepted owner plan" + elif field == "outputs": + ticket[field] = {"notes": ["late private owner note"]} + else: + ticket["status"] = "in_progress" + ticket[field] = {"state": "running", "assigned_to": "late-owner", + "lease_expires_at": "2099-01-01T00:00:00Z"} + store.save_backlog(section) + return result + monkeypatch.setattr(backend, "update_ticket", concurrent) + with pytest.raises((OutboundSyncError, ValueError)): + run(sample) + ticket = records(sample)["PLF-001"] + if field == "description": + assert ticket[field] == "late accepted owner plan" + elif field == "outputs": + assert ticket[field]["notes"] == ["late private owner note"] + else: + assert ticket["status"] == "in_progress" and ticket[field]["assigned_to"] == "late-owner" + + +@pytest.mark.parametrize("sample", ["yaml", "sharded"], indirect=True) +def test_native_outbound_checks_snapshot_before_remote_write(sample, monkeypatch): + from planfile.sync.outbound import OutboundSyncError + store, backend, _ = sample + backend.remote["42"].status = "open" + def preflight(_tickets): + section = store.load_backlog() + section["tickets"]["PLF-001"]["description"] = "owner changed before send" + store.save_backlog(section) + monkeypatch.setattr(backend, "preflight", preflight, raising=False) + with pytest.raises((OutboundSyncError, ValueError)): + run(sample) + assert all(event[0] not in {"update", "create"} for event in backend.events) + assert records(sample)["PLF-001"]["description"] == "owner changed before send" diff --git a/tests/test_sync_failure_status.py b/tests/test_sync_failure_status.py index 5f7010a8..aca57b60 100644 --- a/tests/test_sync_failure_status.py +++ b/tests/test_sync_failure_status.py @@ -1,5 +1,6 @@ """Offline regression coverage for outbound sync failures and safe retries.""" +from copy import deepcopy from dataclasses import asdict from types import SimpleNamespace @@ -200,7 +201,7 @@ def app(): @pytest.mark.parametrize("direction", ["to", "both"]) -def test_cli_partial_failure_is_nonzero_without_success_or_inbound( +def test_cli_partial_failure_is_nonzero_without_success( tmp_path, monkeypatch, direction ): source(tmp_path) @@ -210,7 +211,7 @@ def test_cli_partial_failure_is_nonzero_without_success_or_inbound( assert result.exit_code == 1, result.output assert "completed successfully" not in result.output assert "Synced to external system" not in result.output - assert not backend.fetched + assert backend.fetched is (direction == "both") assert backend.created == ["good", "bad", "later"] @@ -266,3 +267,60 @@ def fake_sync(*args, **kwargs): app(), ["watch", str(tmp_path), "--integration", "github", "--once"] ) assert result.exit_code == int(fail), result.output + + +@pytest.mark.parametrize("mixed", [False, True]) +def test_cli_deferred_lifecycle_is_nonzero_and_keeps_other_receipts(tmp_path, monkeypatch, mixed): + from planfile.cli.groups.sync import core + from planfile.sync.base import TicketState + + names = ("bad", "good") if mixed else ("bad",) + path, data, store = source(tmp_path, names) + for name, remote_id in [("bad", "42"), ("good", "43")]: + if name in names: + data["backlog"]["tickets"][name].update( + name=name, status="blocked" if name == "bad" else "open", + description="accepted " + name, + sync={"github": {"id": remote_id, "repository": "fixture/isolated"}}, + ) + path.write_text(yaml.safe_dump(data)) + + class ReconciliationBackend: + config = {"repo": "fixture/isolated"} + + def __init__(self): + self.updated = [] + self.remote = {remote_id: TicketState(id=remote_id, name=name, + description="remote text", status="closed", + url=f"https://github.com/fixture/isolated/issues/{remote_id}", + metadata={"state_reason": "completed"}) + for name, remote_id in [("bad", "42"), ("good", "43")] if name in names} + + def list_tickets(self, **kwargs): + return deepcopy(list(self.remote.values())) + + def get_ticket(self, remote_id): + return deepcopy(self.remote[remote_id]) + + def update_ticket(self, remote_id, **changes): + assert "status" not in changes + self.updated.append(remote_id) + self.remote[remote_id].description = changes["body"] + + backend = ReconciliationBackend() + monkeypatch.setattr(IntegrationConfig, "get_integration_backend", lambda *args: backend) + comments = [] + monkeypatch.setattr(core, "sync_pending_comments", lambda *args: comments.append(args)) + result = CliRunner().invoke(app(), ["github", str(tmp_path), "--direction", "both"]) + assert result.exit_code == 2, result.output + assert "Deferred" in result.output + assert "completed successfully" not in result.output + assert backend.updated == (["43"] if mixed else []) + assert comments == [] + saved = yaml.safe_load(path.read_text()) + assert saved["backlog"]["tickets"]["bad"]["status"] == "blocked" + assert saved["backlog"]["tickets"]["bad"]["description"] == "accepted bad" + assert backend.remote["42"].status == "closed" + if mixed: + assert saved["backlog"]["tickets"]["good"]["status"] == "done" + assert '"outcome": "succeeded"' in (store.base_dir / "sync/github.receipts.jsonl").read_text()