Phase 8 — Bidirectional Sync (v1.8.0)¶
Goal: Ship the sync surface for anvil. Multi-provider abstraction (so GitHub Issues, GitHub Projects, Monday, Linear, Jira can all plug in) with GitHub Issues as the first concrete v0 implementation. Bidirectional, polling-based, conflict-resolved, with a reconciliation engine that cross-checks SQLite state vs filesystem vs git.
Language: Python (anvil plugin codebase)
Crew: fakoli-crew v2.0.1
Base branch: feat/anvil-phase-8-sync (off main at v1.7.1)
Target version: 1.8.0 (minor — additive new public surface: SyncProvider Protocol, sync CLI, state-keeper agent, SyncMapping table)
Scope expansion vs original spec¶
The spec at docs/specs/2026-05-24-anvil-v0.md § Phase 8 said "GitHub Issues only in v0; multi-backend deferred." Per user direction (2026-05-25 session): build the multi-provider abstraction now, ship GitHub Issues as the first concrete impl, scaffold registry so Monday/Linear/Jira/etc. can be added by external contributors without engine changes. The abstraction is the load-bearing architectural choice; GitHub Issues is one client of it.
Architecture¶
SyncProvider Protocol¶
class SyncProvider(Protocol):
"""Abstract bidirectional sync target. Implementations: GitHub Issues
(v1.8.0), GitHub Projects / Monday / Linear / Jira (future).
"""
provider_id: str # e.g. "github-issues", "monday", "linear"
display_name: str # e.g. "GitHub Issues"
def push_task(self, task: Task, mapping: SyncMapping | None) -> ExternalRef: ...
def fetch_task(self, external_id: str) -> ExternalTask | None: ...
def list_tasks(self) -> list[ExternalTask]: ...
def delete_task(self, external_id: str) -> None: ...
def health_check(self) -> ProviderHealth: ...
ExternalTask and ExternalRef are Pydantic models for what the provider returns (id, title, body, status mapping, labels, assignees, url, last_modified).
RecordedSyncProvider (test double)¶
Same pattern as RecordedLLMProvider (Phase 7). Keyed dict of canned responses. Used in all integration tests so the suite never touches real GitHub.
Provider registry¶
PROVIDER_REGISTRY: dict[str, type[SyncProvider]] = {
"github-issues": GitHubIssuesProvider,
# contributor-added: monday, linear, jira, ...
}
anvil sync <provider> resolves the name → class. External providers register by importing their module and calling register_sync_provider("foo", FooProvider).
SyncMapping (per task)¶
Already in the spec at line 174. SQL table: task_id PRIMARY KEY, external_system, external_id, last_synced_at, sync_state, conflict_resolution_strategy. Phase 8 adds the DDL + handler + payload model.
Conflict resolution strategies¶
local_wins— overwrite remote with local on every pushremote_wins— overwrite local with remote on every fetchprompt— surface to user via CLI prompt; default behavior in interactive contextsmanual_merge— write both sides to a.sync-conflict-{task_id}.mdfile, refuse to sync until resolved
Configured per-task via SyncMapping.conflict_resolution_strategy; default falls back to project-level config in .anvil/config.yaml.
Tasks¶
Task 1: SyncProvider Protocol + ExternalTask/ExternalRef models + RecordedSyncProvider¶
Intent: Establish the abstraction other tasks build on.
Acceptance:
- bin/src/anvil/sync/__init__.py exports SyncProvider, ExternalTask, ExternalRef, ProviderHealth, SyncProviderError, RecordedSyncProvider, register_sync_provider, get_sync_provider
- bin/src/anvil/sync/provider.py defines the Protocol + models
- bin/src/anvil/sync/registry.py defines PROVIDER_REGISTRY + register/get functions
- bin/src/anvil/sync/recorded.py defines RecordedSyncProvider (test double; keyed by (method, *args_hash))
- bin/src/anvil/sync/errors.py defines SyncProviderError, SyncConflict, ProviderUnavailable
- 20+ unit tests covering Protocol structural validity, model serialization, registry register/get/list, RecordedSyncProvider hit/miss/replay
- Ruff clean
Scope: bin/src/anvil/sync/ (new package). tests/test_sync_provider.py (new file).
Agent: guido
Verify: cd bin && uv run pytest -q ../tests/test_sync_provider.py && uv run ruff check src/anvil/sync/
Depends on: (none)
Task 2: SyncMapping entity, DDL, payload model, handler¶
Intent: Persist the local↔external task mapping in canonical state.
Acceptance:
- state/models.py adds SyncMapping Pydantic model (task_id, external_system, external_id, last_synced_at, sync_state, conflict_resolution_strategy, external_url)
- state/schema.py adds sync_mappings table DDL (PRIMARY KEY task_id, FK to tasks.id) + bump SCHEMA_VERSION
- state/payloads.py adds SyncMappingUpsertedPayload, SyncMappingDeletedPayload (extra="forbid")
- state/sqlite.py adds _handle_sync_mapping_upserted, _handle_sync_mapping_deleted handlers + dispatch table entries
- Backend Protocol gains get_sync_mapping(task_id), list_sync_mappings(external_system?), apply_sync_mapping(mapping)
- Replay-from-empty test covers the new actions
- All 658 existing tests still pass
- 15+ new tests for the DDL + handlers + Backend methods
Scope: bin/src/anvil/state/models.py, state/schema.py, state/payloads.py, state/sqlite.py, state/backend.py. tests/test_sqlite.py (extend), tests/test_models.py (extend).
Agent: guido
Verify: cd bin && uv run pytest -q && uv run ruff check src/anvil/
Depends on: (none — independent of Task 1)
Task 3: state-keeper agent (4th plugin-owned agent)¶
Intent: Specialized agent for sync reconciliation and drift detection. Fallback when fakoli-crew is absent; defers to fakoli-crew:keeper when present.
Acceptance:
- plugins/anvil/agents/state-keeper.md with valid frontmatter (name, description, model, color, allowed-tools)
- Color does not collide with fakoli-crew (current state plugin colors: planner=white, critic=magenta, sentinel=gray; pick a 4th)
- Description explicitly covers: sync drift detection, reconciliation (SQLite vs filesystem vs git), conflict resolution prompting, audit-log inspection
- Defer-to-crew clause when fakoli-crew installed
Scope: plugins/anvil/agents/state-keeper.md (NEW only).
Agent: smith
Verify: head -20 plugins/anvil/agents/state-keeper.md shows valid YAML frontmatter; no color collision with fakoli-crew agents.
Depends on: (none)
Task 4: GitHubIssuesProvider concrete implementation¶
Intent: First production sync provider. gh CLI primary (auth via user's existing gh auth), HTTP + PAT fallback for environments without gh installed.
Acceptance:
- bin/src/anvil/sync/providers/__init__.py
- bin/src/anvil/sync/providers/github_issues.py implementing SyncProvider Protocol fully
- bin/src/anvil/sync/clients/__init__.py
- bin/src/anvil/sync/clients/gh_cli.py — shell out to gh issue create/edit/view/list via subprocess
- bin/src/anvil/sync/clients/github_http.py — httpx-based fallback using GITHUB_TOKEN env var
- Status mapping: Task status → GitHub label (status:ready, status:in-progress, status:done, etc.) + closed/open state
- Auto-registered in PROVIDER_REGISTRY at module load
- 30+ unit tests using responses library for HTTP mocking + subprocess mocking for gh CLI path
- Both happy paths (gh and HTTP) tested
- Error paths: auth missing, rate limit, conflict (issue deleted on remote)
Scope: bin/src/anvil/sync/providers/, bin/src/anvil/sync/clients/. tests/test_github_issues_provider.py (NEW). bin/pyproject.toml (re-add responses>=0.25 to dev group + httpx>=0.27 to runtime deps if not already there).
Agent: guido
Verify: cd bin && uv run pytest -q ../tests/test_github_issues_provider.py && uv run ruff check src/anvil/sync/
Depends on: Task 1, Task 2
Task 5: ReconciliationEngine¶
Intent: Cross-check SQLite state vs filesystem (packets/) vs git (branches/worktrees). Report orphans; --fix to remediate.
Acceptance:
- bin/src/anvil/sync/reconciliation.py with class ReconciliationEngine
- Methods: scan() -> ReconciliationReport, fix(report, dry_run=False) -> list[Action]
- Checks: orphan branches (claimed task no longer exists), orphan packets, orphan worktrees, claim/task status drift, missing SyncMapping for synced tasks
- Each check produces a Discrepancy with kind, severity, target_id, suggested_fix
- 25+ tests covering each discrepancy kind on real local git tmpdirs
Scope: bin/src/anvil/sync/reconciliation.py (NEW). tests/test_reconciliation.py (NEW).
Agent: welder
Verify: cd bin && uv run pytest -q ../tests/test_reconciliation.py
Depends on: Task 2 (SyncMapping table must exist)
Task 6: sync CLI commands¶
Intent: User-facing surface for all of the above.
Acceptance:
- bin/src/anvil/cli/sync.py (NEW module in the cli package)
- Subcommands wired into the main Typer app:
- anvil sync — runs ReconciliationEngine, prints report
- anvil sync <provider> — push/pull all tasks via the named provider (e.g. anvil sync github-issues)
- anvil sync github — backwards-compatible alias for sync github-issues
- anvil sync github --watch — long-running poll loop (interval from config)
- anvil sync --fix — run reconciliation + apply remediation actions; requires --yes for non-interactive
- anvil sync github --fix — pull mode that reconciles remote → local conflicts
- Conflict resolution honors SyncMapping.conflict_resolution_strategy (local_wins / remote_wins / prompt / manual_merge)
- All operations emit sync.* events to events.jsonl + state.db
- 40+ integration tests via Typer CliRunner + RecordedSyncProvider injection
Scope: bin/src/anvil/cli/sync.py (NEW). bin/src/anvil/cli/__init__.py (register sub-app). tests/test_cli_sync.py (NEW). tests/test_cli.py (extend with sync command discovery tests).
Agent: welder
Verify: cd bin && uv run pytest -q ../tests/test_cli_sync.py && uv run anvil sync --help
Depends on: Task 4, Task 5
Task 7: docs/github-sync.md + docs/sync-providers.md + skills update¶
Intent: User and contributor documentation.
Acceptance:
- docs/github-sync.md — config (gh auth vs GITHUB_TOKEN), conflict strategies, polling cadence, label-to-status mapping, troubleshooting (rate limits, deleted issues, label collisions)
- docs/sync-providers.md — Protocol contract, how to add a new provider (Monday/Linear/Jira examples), provider registry registration, test patterns (RecordedSyncProvider)
- Update skills/state-ops/SKILL.md to mention anvil sync commands
- Update skills/finish/SKILL.md to mention syncing the final state to GitHub when the project is sync-configured
Scope: docs/github-sync.md (NEW), docs/sync-providers.md (NEW), skills/state-ops/SKILL.md (edit), skills/finish/SKILL.md (edit).
Agent: herald
Verify: head -30 docs/github-sync.md and head -30 docs/sync-providers.md show valid markdown + frontmatter where applicable.
Depends on: Task 6 (so docs reflect actual CLI surface)
Task 8: Nightly live-GitHub CI job¶
Intent: Catch upstream API drift (label format changes, deprecated endpoints, gh CLI flag changes) before users hit them.
Acceptance:
- .github/workflows/anvil-live-github.yml — runs once nightly (cron), runs only @pytest.mark.live_github tests
- Gated on secrets.ANVIL_TEST_GH_TOKEN (if missing, job skips with a notice)
- Tests in tests/test_github_issues_live.py (NEW) with pytest.mark.live_github decorator — small smoke covering create-issue → fetch → close → delete
Scope: .github/workflows/anvil-live-github.yml (NEW), tests/test_github_issues_live.py (NEW), bin/pyproject.toml (add live_github marker if not registered).
Agent: keeper
Verify: head -30 .github/workflows/anvil-live-github.yml shows valid GitHub Actions YAML; cd bin && uv run pytest -q -m "not live_github" excludes them by default.
Depends on: Task 4 (need the provider to test against)
Task 9: Version bump 1.7.1 → 1.8.0 + CHANGELOG + marketplace regen¶
Intent: Release prep.
Acceptance:
- Six version sources updated: plugin.json, pyproject.toml, init.py, README badge, uv.lock, marketplace.json
- CHANGELOG.md gets a [1.8.0] section above [1.7.1] listing every component in this PR
- bash scripts/generate-index.sh succeeds with no warnings
Scope: All version sources + CHANGELOG + registry.
Agent: keeper
Verify: grep -rn '1\.7\.1' plugins/anvil/ | grep -v -E 'CHANGELOG|uv\.lock' is empty.
Depends on: Task 1, 2, 3, 4, 5, 6, 7, 8 (everything must land first)
Wave assignment¶
Wave 1 (parallel): Task 1, Task 2, Task 3 — foundation; independent
Wave 2 (parallel): Task 4, Task 5 — concrete impl + recon; depend on W1
Wave 3: Task 6 — CLI; depends on W2
Wave 4 (parallel): Task 7, Task 8 — docs + nightly CI; depend on W3
Wave 5: Task 9 — keeper release prep; depends on all
Critic gates run after each code-writing wave (1, 2, 3, 4). Sentinel runs after Wave 5.
Sentinel acceptance gate¶
After all waves complete:
- cd bin && uv run pytest -q — all tests pass (target: 658 → 800+ given the new test counts above)
- cd bin && uv run ruff check src/anvil/ — clean
- cd bin && uv run mypy src/anvil/ — clean
- bash tests/test_hooks.sh — 21 hook tests still pass
- bash scripts/generate-index.sh — registry + marketplace regen OK
- uv run anvil sync --help — surface exists
- uv run anvil sync github --help — alias works
- Version sync across 6 sources
- CHANGELOG entry present for 1.8.0
- docs/github-sync.md and docs/sync-providers.md exist and reference real implementation symbols
- .github/workflows/anvil-live-github.yml exists and parses as valid YAML
Notes for downstream waves¶
- Pattern alignment: SyncProvider Protocol shape MUST mirror LLMProvider Protocol shape (kw-only args, single exception type to catch, Recorded test double, registry pattern). Consistency is the user-facing contract.
- State events: every sync mutation (push, fetch, conflict, mapping change) emits a
sync.*event. Replay-from-empty must reconstruct all SyncMapping rows. - Backward compatibility: existing CLI surface is unchanged.
anvil syncis NEW; nothing pre-existing moved or changed semantics. - Critic preferences: based on PR #44/#45/#47/#48 review history, this codebase critic flags: (a) duplicate model_config assignments, (b) lazy import comments that aren't actually lazy, (c) token math no-ops, (d) docstrings that lie about parameters, (e) any place a Protocol-conforming provider's bug could abort a "best-effort" wrapping loop. Get those right the first time.