diff --git a/planfile/sync/github.py b/planfile/sync/github.py index d4731b6c..fbd1e8b6 100644 --- a/planfile/sync/github.py +++ b/planfile/sync/github.py @@ -127,6 +127,7 @@ class GitHubBackend(BasePMBackend): # Sync owns the managed description, not deliberate tracker titles. preserves_remote_titles = True + _managed_description_projection = True MAX_LABEL_LENGTH = 50 DEFAULT_MUTATION_INTERVAL = 1.0 @@ -353,6 +354,29 @@ def _build_metadata_body(self, body: str, metadata: dict[str, Any] | None) -> st DESCRIPTION_START = "" DESCRIPTION_END = "" + @classmethod + def _description_bounds(cls, body: str) -> tuple[int, int] | None: + """Accept only an absent or unique, well ordered owned region.""" + starts, ends = body.count(cls.DESCRIPTION_START), body.count(cls.DESCRIPTION_END) + if not starts and not ends: + return None + if starts != 1 or ends != 1: + raise ValueError("sync_github_description_markers_ambiguous") + start, end = body.index(cls.DESCRIPTION_START), body.index(cls.DESCRIPTION_END) + if end < start: + raise ValueError("sync_github_description_markers_ambiguous") + return start, end + len(cls.DESCRIPTION_END) + + @classmethod + def _description_text(cls, body: str | None) -> str: + """Import owned text; unmarked legacy issues retain whole-body imports.""" + current = body or "" + bounds = cls._description_bounds(current) + if bounds is None: + return current + start, end = bounds + return current[start + len(cls.DESCRIPTION_START):end - len(cls.DESCRIPTION_END)].strip() + @classmethod def _merge_description(cls, existing: str | None, description: str) -> str: """Write the description into its own section and keep the rest. @@ -362,17 +386,17 @@ def _merge_description(cls, existing: str | None, description: str) -> str: Replacing the body with the description deletes the former, so own a delimited section and leave every other line untouched. """ + if cls.DESCRIPTION_START in description or cls.DESCRIPTION_END in description: + raise ValueError("sync_github_description_contains_reserved_marker") section = f"{cls.DESCRIPTION_START}\n{description.strip()}\n{cls.DESCRIPTION_END}" current = existing or "" - owned = re.compile( - re.escape(cls.DESCRIPTION_START) + r".*?" + re.escape(cls.DESCRIPTION_END), - re.DOTALL, - ) - if owned.search(current): - return owned.sub(lambda _match: section, current, count=1) - if not current.strip(): + bounds = cls._description_bounds(current) + if bounds is not None: + start, end = bounds + return current[:start] + section + current[end:] + if not current: return section - return f"{current.rstrip()}\n\n{section}" + return f"{current}\n\n{section}" @staticmethod def _deduplication_markers(body: str | None) -> list[str]: @@ -493,11 +517,19 @@ def create_ticket(self, ticket: dict[str, Any], **kwargs) -> TicketRef: expected = self.project_remote_status(status) if status else None if status and expected is None: raise ValueError("sync_github_status_unsupported") - reference = super().create_ticket(ticket, **kwargs) + payload = dict(ticket) + description = ticket.get("description") if "description" in ticket else ticket.get("body") + if description is not None: + payload["description"] = self._merge_description(None, description) + reference = super().create_ticket(payload, **kwargs) self._clear_read_cache() issue = self.repo.get_issue(int(reference.id)) if getattr(issue, "pull_request", None) is not None: raise ValueError("sync_github_create_resolved_pull_request") + if description is not None: + # A durable marker may resolve to an older issue. Repair that same + # issue's owned region and preserve its independently written prose. + self._update_ticket(str(reference.id), body=description) if expected is not None: self._update_issue_state(issue, status) self._clear_read_cache() @@ -515,8 +547,8 @@ def _create_ticket( metadata: dict[str, Any] | None = None, ) -> TicketRef: """Create a new GitHub issue.""" - issue_labels = self._prepare_labels(labels, priority) body = self._build_metadata_body(body, metadata) + self._description_bounds(body) markers = self._deduplication_markers(body) dedup_key = markers[0] if markers else None @@ -527,6 +559,7 @@ def _create_ticket( raise ValueError( f"{self.repo.full_name}#{existing.number} is a pull request, not an issue" ) + self._description_bounds(getattr(existing, "body", "") or "") return self.build_ticket_ref( id=str(existing.number), url=existing.html_url, @@ -538,7 +571,7 @@ def _create_ticket( create_kwargs = { "title": name, "body": body, - "labels": issue_labels, + "labels": self._prepare_labels(labels, priority), } if assignee: create_kwargs["assignee"] = assignee @@ -606,7 +639,7 @@ def _update_ticket( # The title is set when the issue is created. Renaming it from a ticket # name silently shortened semcod/fixos#46 on 2026-09-16, so a rename is # a deliberate action on the issue, not a side effect of a sync. - if body: + if body is not None: merged = self._merge_description(issue.body, body) markers = self._deduplication_markers(issue.body) missing_markers = [marker for marker in markers if marker not in merged] @@ -661,7 +694,7 @@ def _issue_to_ticket_status(self, issue: Issue) -> TicketState: id=str(number), key=f"{repo_name}#{number}", name=getattr(issue, "title", ""), - description=body, + description=self._description_text(body), url=getattr(issue, "html_url", ""), status=getattr(issue, "state", ""), assignee=assignee_login, diff --git a/planfile/sync/operations.py b/planfile/sync/operations.py index d34f4a36..0d8f017d 100644 --- a/planfile/sync/operations.py +++ b/planfile/sync/operations.py @@ -115,11 +115,14 @@ def _update_existing_ticket( backend, ticket, ticket_id: str, external_id: str, integration_name: str, sync_state ) -> str: """Update an existing ticket in the external system.""" + body = ticket.get("description", "") or ticket.get("body", "") + if getattr(backend, "_managed_description_projection", False) is True: + body = ticket.get("description") if "description" in ticket else ticket.get("body") try: backend.update_ticket( external_id, name=ticket.get("name") or ticket.get("title"), - body=ticket.get("description", "") or ticket.get("body", ""), + body=body, status=ticket.get("status"), labels=ticket.get("labels"), priority=ticket.get("priority"), @@ -144,28 +147,7 @@ def _update_existing_ticket( # Keep status and retry headers available to the outbound scheduler. raise elif "404" in str(e) or "Not Found" in str(e): - console.print(f" ⚠️ Issue not found, creating new: {external_id}") - external_ticket = backend.create_ticket( - _backend_ticket_payload( - ticket, - ticket_id, - _backend_repository(backend), - getattr(sync_state, "store_identity", None), - ) - ) - new_id = ( - external_ticket.id - if hasattr(external_ticket, "id") - else str(external_ticket.get("id")) - ) - sync_state.save_sync({ticket_id: new_id}) - _record_backend_ref(ticket, integration_name, external_ticket, new_id) - console.print(f" ✓ Created: {ticket_id} → {new_id}") - return "created" - elif _is_rate_limit_error(e): - _print_rate_limit_error(ticket_id, e) - # Keep status and retry headers available to the outbound scheduler. - raise + raise RuntimeError("sync_mapped_ticket_unavailable") from e elif _is_permission_error(e): _print_permission_error(ticket_id) raise RuntimeError( diff --git a/planfile/sync/outbound.py b/planfile/sync/outbound.py index 2e17293d..79b00f4e 100644 --- a/planfile/sync/outbound.py +++ b/planfile/sync/outbound.py @@ -141,6 +141,12 @@ def _verify_remote_readback( actual_name = getattr(remote, "name", None) or getattr(remote, "title", None) if check_title and expected_name and actual_name and str(expected_name) != str(actual_name): raise RuntimeError("sync_readback_title_mismatch") + if getattr(backend, "_managed_description_projection", False) is True: + desired = ticket.get("description") if "description" in ticket else ticket.get("body") + if desired is not None: + actual = remote.get("description") if isinstance(remote, dict) else getattr(remote, "description", None) + if str(actual or "").strip() != str(desired).strip(): + raise RuntimeError("sync_readback_description_mismatch") # Only backends declaring a lifecycle projection opt into this contract. # Looking it up on the class avoids fabricating a capability on mocks. projector = getattr(type(backend), "project_remote_status", None) @@ -255,7 +261,7 @@ def sync_to_external( check_title=not getattr(backend, "preserves_remote_titles", False), ) except RuntimeError as exc: - if str(exc) not in {"sync_readback_status_mismatch", "sync_receipt_payload_superseded"}: + if str(exc) not in {"sync_readback_status_mismatch", "sync_readback_description_mismatch", "sync_receipt_payload_superseded"}: raise # The receipt binds identity, not current payload/lifecycle. Reuse # that exact issue for repair and verify the update below. diff --git a/project/ticket-283/README.md b/project/ticket-283/README.md new file mode 100644 index 00000000..8051a028 --- /dev/null +++ b/project/ticket-283/README.md @@ -0,0 +1,24 @@ +# Ticket 283: Preserve managed GitHub descriptions across round trips + +- **ID**: ticket-283 +- **Owner**: agent:codex-heyasa-audit +- **Status**: IN_PROGRESS +- **Workflow state**: PUBLICATION +- **Created**: 2026-11-06 + +SESSION_EXECUTION_AUTHORIZATION: existing rootPLF-19975 audit/repair and explicit instruction to execute autonomously with existing consent, without repeated routine questions. Existing sourcePLF-20372/GitHub341 owns this request. Native279/282 are independently merged; foreign280 stays preserved. A genuine current protected controller grant is required before implementation. + +## Goal and scope + +Project only the unique machine-owned description on inbound; preserve remote-only prose and existing339local planning behavior. New managed creates use the owned region, explicit empty updates clear it, and ambiguous markers fail before mutation. Verify desired descriptions for actual outbound updates and receipt reuse; preserve mapped identity, lifecycle, raw snapshot and live execution protections. Legacy unmarked issues retain explicit import semantics. No mass historical edits, schema/dependency/signature changes or changes to foreign coreStore/allocator scope. + +## Acceptance criteria + +- [x] AC-01: Native behavior covers stable roundtrips, no human-prose import, empty updates, ambiguity, managed create/recovery and fresh/reused description verification, preserving identity/legacy and existing safeguards. +- [ ] AC-02: Ruff/governance, all8requiredchecks and independent exact-head publication succeed. + +## Validation and publication + +42 native description/receipt tests passed; 412 identity, CAS, raw-snapshot, live-execution and bidirectional regressions passed. The broad run passed807tests and exposed a poll fixture that patched stdlibtime globally, allowing storage waits to consume simulated pollticks. The fixture now patches only the watch dependency; its12tests pass. An obsolete redirect backend fixture now models its accepted body writes. Whole changed Python files pass Ruff; the managed gate passes. Final broad verification and all8independent publication checks remain required. + +Native283 was rebound from925to926after an authentic cancelled/released handoff and fast-forward to the independently merged9abfd11f9d0c22c11ec2c5888d4c364682eb7885baseline. All foreign280bytes, implementation bytes, scope and original17:21:09UTC45minute ceiling are preserved. No source closure commit is authorized; retain IN_PROGRESS/PUBLICATION through trusted merge. diff --git a/project/ticket-283/intent.json b/project/ticket-283/intent.json new file mode 100644 index 00000000..9df97afa --- /dev/null +++ b/project/ticket-283/intent.json @@ -0,0 +1,89 @@ +{ + "schema": "new-project.intent/v3", + "ticket": "ticket-283", + "summary": "Preserve managed GitHub description ownership and verify outbound body projection", + "workstream": "application", + "classification": { + "kind": "BUG", + "priority": "P1", + "origin": "health" + }, + "allowedPaths": [ + "project/ticket-283/**", + "TODO.md", + "project/TICKETS.md", + "planfile/sync/github.py", + "planfile/sync/outbound.py", + "planfile/sync/operations.py", + "tests/test_github*.py", + "tests/test_sync*.py" + ], + "forbiddenPaths": [ + "project/ticket-*/user-*.md" + ], + "stacks": [], + "dependsOn": [], + "conflictsWith": [], + "integrationTicket": null, + "delivery": { + "acceptedBaseSha": "9abfd11f9d0c22c11ec2c5888d4c364682eb7885", + "targetBranch": "main", + "outcome": "Managed GitHub descriptions round-trip without nesting or importing remote-only discussion; explicit empty descriptions clear the owned region, ambiguous markers fail before mutation, and fresh/reused outbound receipts verify the managed description without weakening identity, lifecycle, snapshot or live-execution guards.", + "nonGoals": [ + "No mass rewrite of historical issue bodies", + "No schema, dependency or public signature changes", + "No foreign280coreStore/allocator changes", + "Existing339CLIplanning/snapshotguards remain authoritative" + ], + "complexity": "M", + "estimatedMinutes": 45, + "budgets": { + "maxImplementationFiles": 8, + "maxAffectedComponents": 1, + "maxPublicInterfaceChanges": 0, + "maxRuntimeDependencies": 0 + }, + "architecture": { + "status": "accepted", + "decision": "Keep ownership parsing/projection in GitHubBackend, verify opt-in managed descriptions in existing outbound readbacks and receipt reuse, and fail closed for missing mapped issues instead of allocating replacements. Preserve unmarked legacy imports, all unowned prose, and existing339snapshot/live execution safeguards.", + "components": [ + { + "name": "GitHub synchronization description ownership", + "paths": [ + "planfile/sync/github.py", + "planfile/sync/outbound.py", + "planfile/sync/operations.py", + "tests/test_github*.py", + "tests/test_sync*.py" + ] + } + ], + "responsibilityChanges": false, + "interfaceChanges": [], + "dataChanges": [], + "ui": { + "impact": "none", + "states": [], + "evidence": [] + }, + "rollback": "Revert bounded code through independent publication; keep provider/local data and all existing receipts." + }, + "runtimeDependencies": [], + "validation": [ + { + "criterion": "AC-01", + "commands": [ + "python -m pytest tests/test_github_description_roundtrip.py tests/test_github_sync_preserves_issue.py tests/test_github_deduplication.py tests/test_sync_receipts.py -q" + ], + "evidence": "Pending admitted native projection, stable roundtrip, empty, ambiguity, receipt reuse, identity/legacy/live-execution regressions." + }, + { + "criterion": "AC-02", + "commands": [ + "./project/governance-check.sh" + ], + "evidence": "Pending native gate, all8protectedchecks and independent exact-head merge." + } + ] + } +} diff --git a/tests/test_github_description_roundtrip.py b/tests/test_github_description_roundtrip.py new file mode 100644 index 00000000..769dfc72 --- /dev/null +++ b/tests/test_github_description_roundtrip.py @@ -0,0 +1,267 @@ +"""Exercise actual provider projection and durable outbound retries together.""" +from copy import deepcopy +from types import SimpleNamespace + +import pytest + +from planfile.core.store import Store +from planfile.sync.github import GitHubBackend +from planfile.sync.operations import sync_from_external +from planfile.sync.outbound import OutboundSyncError, sync_to_external + +START = GitHubBackend.DESCRIPTION_START +END = GitHubBackend.DESCRIPTION_END + + +class Issue(SimpleNamespace): + def __init__(self, body="human evidence \n", number=42): + super().__init__(body=body, number=number, title="remote title", state="open", + html_url=f"https://github.com/owner/repo/issues/{number}", + labels=[], pull_request=None, edits=[], ignore_body=False) + + def edit(self, **fields): + self.edits.append(fields) + for key, value in fields.items(): + if key != "body" or not self.ignore_body: + setattr(self, key, value) + + def set_labels(self, *labels): + self.labels = list(labels) + + +class Repo: + full_name = "owner/repo" + + def __init__(self, issue): + self.issue = issue + self.created = [] + self.missing = False + + def get_issue(self, number): + if self.missing: + raise RuntimeError("404 Not Found") + assert number == self.issue.number + return self.issue + + def get_issues(self, **kwargs): + return [self.issue] if self.issue else [] + + def get_labels(self): + return [] + + def create_label(self, **kwargs): + pass + + def create_issue(self, **fields): + self.created.append(fields) + self.issue = Issue(fields["body"]) + self.issue.title = fields["title"] + return self.issue + + +def backend(tmp_path, issue=None): + result = GitHubBackend.__new__(GitHubBackend) + result.config = {"repo": "owner/repo", "cache_dir": str(tmp_path / "cache")} + result.repo = Repo(issue) + result._mutation_interval = 0 + result._last_mutation_at = 0 + return result + + +def publication(tmp_path): + issue = Issue() + provider = backend(tmp_path, issue) + store = Store(tmp_path) + store.init() + ticket = {"id": "PLF-1", "name": "local title", "description": "accepted plan", + "status": "open", "sync": {"github": {"id": "42", "repository": "owner/repo"}}} + return provider, issue, store, ticket + + +def test_repeated_roundtrips_project_only_owned_text_and_preserve_outside_bytes(tmp_path): + issue = Issue() + provider = backend(tmp_path, issue) + provider.update_ticket("42", body="accepted plan") + issue.body += "\n\nhuman decision \n" + expected = issue.body + for _ in range(4): + remote = provider.get_ticket("42") + assert remote.description == "accepted plan" + provider.update_ticket("42", body=remote.description) + assert issue.body == expected + assert issue.body.count(START) == 1 + assert len(issue.edits) == 1 + + +def test_legacy_unmarked_imports_remain_explicit(tmp_path): + issue = Issue("legacy human body \n") + assert backend(tmp_path, issue).get_ticket("42").description == issue.body + + +def test_empty_clears_owned_description_and_none_leaves_it_unchanged(tmp_path): + provider, issue, store, ticket = publication(tmp_path) + sync_to_external(provider, [("PLF-1", ticket)], False, store, "github") + ticket.update(description="", body="stale legacy alias") + sync_to_external(provider, [("PLF-1", ticket)], False, store, "github") + assert provider.get_ticket("42").description == "" + assert "stale legacy alias" not in issue.body + assert issue.body.startswith("human evidence \n") + expected = issue.body + provider.update_ticket("42", body=None) + assert issue.body == expected + + +@pytest.mark.parametrize("body", [START, END, END + START, START + START + END, + START + END + END, START + END + START + END]) +def test_ambiguous_markers_fail_reads_and_updates_before_mutation(tmp_path, body): + issue = Issue(body) + provider = backend(tmp_path, issue) + with pytest.raises(ValueError, match="description_markers_ambiguous"): + provider.get_ticket("42") + with pytest.raises(ValueError, match="description_markers_ambiguous"): + provider.update_ticket("42", body="new plan", status="closed", labels=[]) + assert issue.edits == [] + assert issue.body == body + assert issue.state == "open" + + +@pytest.mark.parametrize("marker", [START, END]) +def test_reserved_local_markers_fail_before_create_or_update(tmp_path, marker): + issue = Issue() + provider = backend(tmp_path, issue) + with pytest.raises(ValueError, match="contains_reserved_marker"): + provider.create_ticket({"name": "test", "description": marker}) + with pytest.raises(ValueError, match="contains_reserved_marker"): + provider.update_ticket("42", body=marker) + assert provider.repo.created == [] + assert issue.edits == [] + + +@pytest.mark.parametrize("description", ["accepted plan", ""]) +def test_managed_create_and_marker_recovery_preserve_one_region_and_payload(tmp_path, description): + provider = backend(tmp_path) + payload = {"name": "test", "description": description, + "metadata": {"planfile_id": "store:PLF-1"}} + original = deepcopy(payload) + reference = provider.create_ticket(payload) + assert payload == original + issue = provider.repo.issue + issue.body += "\nhuman recovery evidence" + expected = issue.body + recovered = provider.create_ticket(payload) + assert recovered.id == reference.id + assert len(provider.repo.created) == 1 + assert issue.body == expected + assert issue.body.count(START) == 1 + assert provider.get_ticket(reference.id).description == description + assert issue.body.index("planfile:deduplication-key=") < issue.body.index(START) + changed = {**payload, "description": "changed accepted plan"} + assert provider.create_ticket(changed).id == reference.id + assert provider.get_ticket(reference.id).description == "changed accepted plan" + assert issue.body.endswith("human recovery evidence") + assert len(provider.repo.created) == 1 + + +def test_ambiguous_marker_match_never_creates_or_changes_lifecycle(tmp_path): + issue = Issue("\n" + START) + provider = backend(tmp_path, issue) + with pytest.raises(ValueError, match="markers_ambiguous"): + provider.create_ticket({"name": "test", "description": "accepted plan", "status": "closed", + "metadata": {"planfile_id": "PLF-1"}}) + assert issue.edits == [] + assert issue.state == "open" + assert provider.repo.created == [] + + +def test_receipt_reuse_verifies_owned_text_and_repairs_same_issue(tmp_path): + provider, issue, store, ticket = publication(tmp_path) + sync_to_external(provider, [("PLF-1", ticket)], False, store, "github") + issue.body += "\nnew human evidence" + edits = len(issue.edits) + reused = sync_to_external(provider, [("PLF-1", ticket)], False, store, "github") + assert reused.reused == ("PLF-1",) + assert len(issue.edits) == edits + issue.body = issue.body.replace("accepted plan", "remote drift") + repaired = sync_to_external(provider, [("PLF-1", ticket)], False, store, "github") + assert repaired.updated == ("PLF-1",) + assert provider.get_ticket("42").description == "accepted plan" + assert issue.body.endswith("new human evidence") + assert provider.repo.created == [] + + +def test_ignored_provider_edit_is_failed_and_retry_keeps_identity(tmp_path): + provider, issue, store, ticket = publication(tmp_path) + issue.ignore_body = True + with pytest.raises(OutboundSyncError) as error: + sync_to_external(provider, [("PLF-1", ticket)], False, store, "github") + assert error.value.result.failed == ("PLF-1",) + issue.ignore_body = False + repaired = sync_to_external(provider, [("PLF-1", ticket)], False, store, "github") + assert repaired.succeeded == ("PLF-1",) + assert ticket["sync"]["github"]["id"] == "42" + assert provider.repo.created == [] + + +def test_missing_mapped_issue_without_receipt_never_creates_or_remaps(tmp_path): + provider, issue, store, ticket = publication(tmp_path) + provider.repo.missing = True + with pytest.raises(OutboundSyncError): + sync_to_external(provider, [("PLF-1", ticket)], False, store, "github") + assert ticket["sync"]["github"]["id"] == "42" + assert provider.repo.created == [] + + +def test_wrong_repository_binding_fails_before_mutation(tmp_path): + provider, issue, store, ticket = publication(tmp_path) + ticket["sync"]["github"]["repository"] = "other/repo" + with pytest.raises(OutboundSyncError): + sync_to_external(provider, [("PLF-1", ticket)], False, store, "github") + assert issue.edits == [] + assert provider.repo.created == [] + + +def test_transparent_proxy_retains_description_readback_contract(tmp_path): + provider, issue, store, ticket = publication(tmp_path) + + class Proxy: + def __getattr__(self, name): + return getattr(provider, name) + + issue.ignore_body = True + with pytest.raises(OutboundSyncError): + sync_to_external(Proxy(), [("PLF-1", ticket)], False, store, "github") + + +@pytest.mark.parametrize("sharded", [False, True]) +def test_real_sdk_roundtrip_keeps_description_and_concurrency_guards(tmp_path, sharded): + from planfile.core.store import Ticket, TicketUpdatedAtConflictError + + store = Store(tmp_path) + store.init() + store.create_ticket(Ticket(id="PLF-001", name="local", description="accepted plan", + status="open", sprint="backlog", integration=["github"], + sync={"github": {"id": "42", "repository": "owner/repo"}})) + if sharded: + store.migrate_to_sharded_yaml() + desired = store.get_ticket("PLF-001").description + issue = Issue(GitHubBackend._merge_description("human evidence", desired)) + provider = backend(tmp_path, issue) + sync_from_external(provider, store, False, "github", ticket_ids=["PLF-001"]) + before = store.get_ticket("PLF-001") + assert before.description == desired + issue.body += "\nnew human discussion" + sync_from_external(provider, store, False, "github", ticket_ids=["PLF-001"]) + assert store.get_ticket("PLF-001").model_dump(mode="json") == before.model_dump(mode="json") + issue.body = provider._merge_description(issue.body, "remote accepted edit") + sync_from_external(provider, store, False, "github", ticket_ids=["PLF-001"]) + with pytest.raises(TicketUpdatedAtConflictError): + store.update_ticket("PLF-001", expected_updated_at=before.updated_at, description="stale writer") + assert store.get_ticket("PLF-001").description == "remote accepted edit" + store.update_ticket("PLF-001", status="in_progress", execution={ + "state": "running", "assigned_to": "other", "lease_expires_at": "2099-01-01T00:00:00Z"}) + before = store.get_ticket("PLF-001").model_dump(mode="json") + issue.state = "closed" + issue.state_reason = "completed" + with pytest.raises(ValueError, match="execution_reconciliation"): + sync_from_external(provider, store, False, "github", ticket_ids=["PLF-001"]) + assert store.get_ticket("PLF-001").model_dump(mode="json") == before diff --git a/tests/test_sync_legacy_operations.py b/tests/test_sync_legacy_operations.py index 0c460f2e..1f0fcbb5 100644 --- a/tests/test_sync_legacy_operations.py +++ b/tests/test_sync_legacy_operations.py @@ -283,7 +283,7 @@ def test_preserved_title_policy_cannot_waive_create_readback(tmp_path): assert caught.value.result.created == () -def test_missing_mapping_replacement_still_checks_create_title(tmp_path): +def test_missing_mapping_fails_without_creating_replacement(tmp_path): class MissingUpdateBackend(ReadbackBackend): preserves_remote_titles = True @@ -300,7 +300,8 @@ def update_ticket(self, ticket_id, **kwargs): assert caught.value.result.succeeded == () assert caught.value.result.updated == () assert caught.value.result.created == () - assert len(backend.created) == 1 + assert backend.created == [] + assert ticket['sync']['github']['id'] == '19' def test_preserved_title_update_still_rejects_wrong_remote_identity(tmp_path): diff --git a/tests/test_sync_repository_redirects.py b/tests/test_sync_repository_redirects.py index 1392a277..55c0b12c 100644 --- a/tests/test_sync_repository_redirects.py +++ b/tests/test_sync_repository_redirects.py @@ -46,15 +46,18 @@ def __init__(self, configured='owner/old'): self._identity_requester = MetadataRequester() self.repo = SimpleNamespace(full_name='owner/new') self.mutations = [] + self.descriptions = {} def update_ticket(self, ticket_id, **kwargs): self.mutations.append(str(ticket_id)) + self.descriptions[str(ticket_id)] = kwargs.get('body', '') def create_ticket(self, ticket): raise AssertionError('A renamed repository must retain its existing mapping') def get_ticket(self, remote_id): return SimpleNamespace(id=str(remote_id), name='Original', status='open', + description=self.descriptions.get(str(remote_id), ''), key=f'owner/new#{remote_id}', url=f'https://github.com/owner/new/issues/{remote_id}') diff --git a/tests/test_sync_watch_inbound_polling.py b/tests/test_sync_watch_inbound_polling.py index 3c1d32d5..25e715be 100644 --- a/tests/test_sync_watch_inbound_polling.py +++ b/tests/test_sync_watch_inbound_polling.py @@ -1,5 +1,7 @@ """Inbound polling exercises the actual watch loop, store and import adapter.""" +from types import SimpleNamespace + import pytest import typer @@ -50,8 +52,9 @@ def sleep(seconds): monkeypatch.setattr(IntegrationConfig, "load_configs", lambda self: None) monkeypatch.setattr(commands, "sync_integration", sync) - monkeypatch.setattr(commands.time, "monotonic", lambda: state["clock"]) - monkeypatch.setattr(commands.time, "sleep", sleep) + # Patch only the watch dependency. Store locks and provider caches also + # use stdlib time; their waits must not advance this fixture's poll ticks. + monkeypatch.setattr(commands, "time", SimpleNamespace(monotonic=lambda: state["clock"], sleep=sleep)) state.update(pf=pf, local_id=local.id) state["run"] = lambda once=False: commands.watch_cmd( str(tmp_path), 5, ["github"], "from", once, @@ -201,8 +204,7 @@ def sleep(seconds): monkeypatch.setattr(IntegrationConfig, "load_configs", lambda self: None) monkeypatch.setattr(commands, "sync_integration", sync) - monkeypatch.setattr(commands.time, "monotonic", lambda: state["clock"]) - monkeypatch.setattr(commands.time, "sleep", sleep) + monkeypatch.setattr(commands, "time", SimpleNamespace(monotonic=lambda: state["clock"], sleep=sleep)) commands.watch_cmd( str(tmp_path), 5, ["github"], "both", False,