Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 46 additions & 13 deletions planfile/sync/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -353,6 +354,29 @@ def _build_metadata_body(self, body: str, metadata: dict[str, Any] | None) -> st
DESCRIPTION_START = "<!-- planfile:description:start -->"
DESCRIPTION_END = "<!-- planfile: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.
Expand All @@ -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]:
Expand Down Expand Up @@ -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()
Expand All @@ -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

Expand All @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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,
Expand Down
28 changes: 5 additions & 23 deletions planfile/sync/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand All @@ -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(
Expand Down
8 changes: 7 additions & 1 deletion planfile/sync/outbound.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down
24 changes: 24 additions & 0 deletions project/ticket-283/README.md
Original file line number Diff line number Diff line change
@@ -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.
89 changes: 89 additions & 0 deletions project/ticket-283/intent.json
Original file line number Diff line number Diff line change
@@ -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."
}
]
}
}
Loading
Loading