diff --git a/README.md b/README.md index 3bb1383..ad12514 100644 --- a/README.md +++ b/README.md @@ -8,15 +8,16 @@ A support engineer usually does that by hand. FirstSync gives the work to Claude inspects the customer's org, proposes how each field maps, and explains every failure in plain language. Deterministic code decides what actually runs. -> **Status: week 4 of 6.** The full pipeline now runs end to end: Claude inspects an org -> and proposes a validated mapping; a deterministic dry-run shows, per record, exactly -> what would load and why anything would not; a person approves at the CLI — approval is -> hash-bound, so a proposal changed after approval invalidates it; and the migration -> engine loads approved data into the target database, idempotently (re-running reports -> everything `unchanged` and writes nothing). There is no tool by which the model -> approves proposals or starts a migration. Sync and the portal are not built yet. This -> is a reference implementation with no customers. See -> [What is and is not tested](#what-is-and-is-not-tested). +> **Status: week 5 of 6.** The full lifecycle runs end to end: Claude inspects an org and +> proposes a validated mapping; a deterministic dry-run shows, per record, exactly what +> would load and why anything would not; a person approves at the CLI — approval is +> hash-bound, so a proposal changed after approval invalidates it; the migration engine +> loads approved data idempotently; and a sync engine keeps the target in step with the +> source afterwards — adding and updating safely, and reporting (never acting on) records +> that regressed or vanished. A go-live report ties it together in plain language. There +> is no tool by which the model approves, migrates, syncs, or deletes anything. The +> hosted portal is the remaining piece. This is a reference implementation with no +> customers. See [What is and is not tested](#what-is-and-is-not-tested). ## The rule the design is built on @@ -34,7 +35,7 @@ The full design is in [docs/SPEC.md](docs/SPEC.md). ## What works today -Ten tools, served from one MCP server: +Eleven tools, served from one MCP server: | Tool | What it does | | --- | --- | @@ -48,6 +49,7 @@ Ten tools, served from one MCP server: | `dryrun_start` | Executes stored proposals over real records without writing, grouped by root cause | | `dryrun_get_results` | Returns a stored dry-run instead of re-running one | | `migration_get_status` | Returns a stored migration result — counts, skips and who approved. Read-only | +| `sync_get_status` | Returns a stored sync result — counts and the records that regressed or vanished. Read-only | Approval and migration are deliberately **not** MCP tools. They are CLI commands run by a person: @@ -56,6 +58,8 @@ a person: firstsync proposals org_d # list proposals and their approval state firstsync approve org_d # approve them as they stand (hash-bound) firstsync migrate org_d --db out.db # load approved data; exits non-zero if refused +firstsync sync org_d --db out.db # keep the target in step afterwards +firstsync report org_d # where the onboarding stands, in plain language ``` An approval stores a SHA-256 of each approved proposal. If any proposal changes @@ -69,6 +73,24 @@ always safe: the second run reports everything `unchanged`. The target database SQLite by default (tests and CI need no services); the DDL is generated from the same `TARGET_SCHEMA` the dry-run validates against, so the schema cannot drift. +**Sync** is the ongoing half. A migration happens once; onboarding does not end there. +`firstsync sync` re-reads the source, rebuilds every row with the same `build_row`, and +applies only what changed: new records are added, changed records updated, the rest left +alone. It moves data only in the safe direction. Two situations are reported for a person +to decide and otherwise left untouched: + +| sync finds | what it means | what sync does | +| --- | --- | --- | +| `regressed` | a record that loaded cleanly now fails validation in the source | leaves the good target row intact | +| `vanished` | a record in the target is no longer in the source | reports it; deleting is a human call | + +`firstsync sync` exits `0` when all is quiet, `2` when something needs attention, so a +scheduled run can page a human only when it should. Sync reads up to `--limit` records +per object (default 2000); a source larger than the limit is read only in part, so for a +true picture the limit must exceed the object's size. **`firstsync report`** is a plain +view over the state the engines already wrote — approval, last dry-run, migration, latest +sync — with a headline, what is live, and what is still open. It computes nothing new. + The dry-run engine is deterministic code, not the model. Every record is built the way the migration would build it and comes back as **clean**, **warning** (an optional value would be dropped), **needs_decision** (an unmapped picklist value the administrator must @@ -103,7 +125,7 @@ Pythons refuse installs outside one. python3 -m venv .venv source .venv/bin/activate pip install -e ".[dev]" -pytest -q # 198 tests, no network, no API key +pytest -q # 209 tests, no network, no API key python scripts/run_eval.py --baseline # the evaluation, with name matching instead of a model python -m firstsync.mcp_server # the MCP server, over stdio ``` @@ -274,6 +296,7 @@ administrator, and neither can a low-confidence mapping or a required field with | Tools, masking, rules, mapping validation, scoring, fixtures, answer keys | Unit tests, offline | | Dry-run engine | Unit tests against the planted defects in org D, plus property-based tests (Hypothesis) that any limit is safe and re-running never changes the verdict | | Approval gate and migration | Unit tests: no approval → refused; changed proposal → refused naming the field; migration counts equal the dry-run's per table; property-based test that N runs equal one run | +| Sync and go-live report | Unit tests mutate a source between runs: a new record is added, a changed one updated, a deleted one reported as vanished (not deleted), a broken one flagged as regressed (target left intact); report reflects the full onboarding | | MCP server | Unit tests, plus a real MCP client over stdio | | Evaluation pipeline | End to end with the baseline mapper | | `scripts/describe_org.py` | Run against org B in week 1: all six planted problems found. See [the report](docs/week1-org-b-report.md). | diff --git a/src/firstsync/cli.py b/src/firstsync/cli.py index 18beb66..0745360 100644 --- a/src/firstsync/cli.py +++ b/src/firstsync/cli.py @@ -7,6 +7,8 @@ firstsync proposals ORG list stored proposals and their approval state firstsync approve ORG approve the proposals as they stand (human-only gate) firstsync migrate ORG --db PATH run the approved migration into the target database + firstsync sync ORG --db PATH bring the target in step with the source, safely + firstsync report ORG where this onboarding stands, in plain language firstsync audit [--last N] show the last audit-log entries Approval and migration are deliberately CLI commands, not MCP tools: the model proposes; @@ -19,7 +21,7 @@ import json import sys -from firstsync import approval, audit, dryrun, migrate +from firstsync import approval, audit, dryrun, golive, migrate, sync from firstsync.connections import get_client from firstsync.mapping import ProposalStore from firstsync.target.db import TargetDB @@ -49,6 +51,15 @@ def main(argv: list[str] | None = None) -> int: mig.add_argument("--db", required=True, help="SQLite database path (created if absent).") mig.add_argument("--limit", type=int, default=dryrun.SCAN_LIMIT) + syn = sub.add_parser("sync", help="Bring the target in step with the source.") + syn.add_argument("connection") + syn.add_argument("--db", required=True, help="SQLite database path.") + syn.add_argument("--limit", type=int, default=dryrun.SCAN_LIMIT) + + rep = sub.add_parser("report", help="Where this onboarding stands.") + rep.add_argument("connection") + rep.add_argument("--json", action="store_true", help="Emit the raw report as JSON.") + log = sub.add_parser("audit", help="Show the last audit-log entries.") log.add_argument("--last", type=int, default=20) @@ -110,6 +121,24 @@ def main(argv: list[str] | None = None) -> int: print(json.dumps(migrate.status_summary(outcome), indent=2)) return 0 if outcome.status == "completed" else 1 + if args.command == "sync": + db = TargetDB(args.db) + try: + synced = sync.run_sync( + get_client(args.connection), args.connection, db, args.limit + ) + finally: + db.close() + print(json.dumps(sync.status_summary(synced), indent=2)) + if synced.status != "completed": + return 1 + return 2 if synced.needs_attention() else 0 + + if args.command == "report": + report = golive.build(args.connection) + print(json.dumps(report, indent=2) if args.json else golive.render(report)) + return 0 + path = audit.log_path() if not path.is_file(): print("No audit log yet.", file=sys.stderr) diff --git a/src/firstsync/golive.py b/src/firstsync/golive.py new file mode 100644 index 0000000..1544aae --- /dev/null +++ b/src/firstsync/golive.py @@ -0,0 +1,130 @@ +"""The go-live report. + +One readable page an administrator gets at the end of onboarding and after every sync. +It pulls together what already happened — the approval, the last dry-run, the migration, +the latest sync — and says plainly where things stand: what is live, what is still open +and waiting on a decision, and what has changed or needs attention since go-live. + +It computes nothing new and re-reads no source. It is a view over the state the other +engines already wrote, so it is cheap and always consistent with them. +""" + +from __future__ import annotations + +from typing import Any + +from firstsync import approval, dryrun, migrate, sync + + +def _latest(loader: Any, connection: str) -> Any | None: + try: + return loader(connection) + except ValueError: + return None + + +def build(connection: str) -> dict[str, Any]: + """Assemble the current state of one onboarding.""" + appr = approval.load(connection) + dry = _latest(dryrun.load, connection) + mig = _latest(migrate.load, connection) + syn = _latest(sync.load, connection) + + report: dict[str, Any] = {"connection": connection} + report["approved"] = ( + None + if appr is None + else { + "by": appr["approved_by"], + "at": appr["approved_at"], + "fields": len(appr["proposal_sha256_16"]), + "excluded": appr["excluded"], + "open_questions": appr["open_questions"], + } + ) + report["migration"] = ( + None if mig is None else {"run_id": mig.run_id, "status": mig.status, **mig.totals()} + ) + report["latest_sync"] = ( + None + if syn is None + else { + "run_id": syn.run_id, + "at": syn.started_at, + "needs_attention": syn.needs_attention(), + **syn.totals(), + } + ) + report["open_items"] = _open_items(appr, dry, syn) + report["headline"] = _headline(report) + return report + + +def _open_items(appr: Any, dry: Any, syn: Any) -> list[str]: + items: list[str] = [] + if appr and appr["open_questions"]: + items.append( + f"{len(appr['open_questions'])} field(s) approved with an open question: " + + ", ".join(appr["open_questions"]) + ) + if dry is not None: + blocking = sum(t.blocking for t in dry.tables) + decisions = sum(t.needs_decision for t in dry.tables) + if blocking: + items.append(f"{blocking} record(s) cannot load until the source is fixed") + if decisions: + items.append(f"{decisions} record(s) await an admin decision on an unmapped value") + if syn is not None: + for t in syn.tables: + if t.regressed: + items.append( + f"{t.table}: {len(t.regressed)} live record(s) regressed in the source" + ) + if t.vanished: + items.append(f"{t.table}: {len(t.vanished)} record(s) vanished from the source") + return items + + +def _headline(report: dict[str, Any]) -> str: + if report["approved"] is None: + return "Not approved. Nothing has been migrated." + if report["migration"] is None: + return "Approved, but no migration has run yet." + loaded = report["migration"].get("inserted", 0) + report["migration"].get("updated", 0) + base = f"{loaded} record(s) live" + if report["latest_sync"] and report["latest_sync"]["needs_attention"]: + return base + "; the latest sync flagged items that need attention." + if report["open_items"]: + return base + f"; {len(report['open_items'])} open item(s)." + return base + "; nothing outstanding." + + +def render(report: dict[str, Any]) -> str: + """A plain-text version of the report for the CLI.""" + lines = [f"Onboarding: {report['connection']}", "=" * (12 + len(report["connection"])), ""] + lines.append(report["headline"]) + lines.append("") + a = report["approved"] + if a: + lines.append(f"Approved by {a['by']} at {a['at']} — {a['fields']} field(s).") + if a["excluded"]: + lines.append(f" Excluded from the migration: {', '.join(a['excluded'])}") + m = report["migration"] + if m: + lines.append( + f"Migration {m['run_id']}: {m.get('inserted', 0)} inserted, " + f"{m.get('updated', 0)} updated, {m.get('unchanged', 0)} unchanged, " + f"{m.get('skipped', 0)} skipped." + ) + s = report["latest_sync"] + if s: + lines.append( + f"Latest sync {s['run_id']} at {s['at']}: {s.get('added', 0)} added, " + f"{s.get('changed', 0)} changed, {s.get('regressed', 0)} regressed, " + f"{s.get('vanished', 0)} vanished." + ) + if report["open_items"]: + lines.append("") + lines.append("Open items:") + lines.extend(f" - {item}" for item in report["open_items"]) + return "\n".join(lines) diff --git a/src/firstsync/mcp_server.py b/src/firstsync/mcp_server.py index aea913e..f2fbb72 100644 --- a/src/firstsync/mcp_server.py +++ b/src/firstsync/mcp_server.py @@ -16,7 +16,7 @@ from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver.exceptions import ToolError -from firstsync import audit, dryrun, migrate, tools +from firstsync import audit, dryrun, migrate, sync, tools from firstsync.config import get_settings from firstsync.connections import get_client from firstsync.rules import RULE_HELP @@ -44,6 +44,7 @@ "dryrun_start", "dryrun_get_results", "migration_get_status", + "sync_get_status", ) _calls = 0 @@ -242,6 +243,26 @@ def migration_get_status(connection: str, run_id: str | None = None) -> dict[str ) +SYNC_STATUS_DOC = ( + "Return the result of a stored sync run for a connection: the latest, or 'run_id' for " + "a specific run. Counts (added, changed, unchanged) and the record Ids that need an " + "administrator — 'regressed' (loaded before, now fails in the source) and 'vanished' " + "(gone from the source). Read-only: sync runs at the CLI, and it never deletes or " + "overwrites a loaded record with a broken one." +) + + +@server.tool(description=SYNC_STATUS_DOC) +def sync_get_status(connection: str, run_id: str | None = None) -> dict[str, Any]: + return _logged( + "sync_get_status", + "sync", + connection, + {"run_id": run_id}, + lambda: sync.status_summary(sync.load(connection, run_id)), + ) + + def main() -> None: server.run("stdio") diff --git a/src/firstsync/sync.py b/src/firstsync/sync.py new file mode 100644 index 0000000..d011a11 --- /dev/null +++ b/src/firstsync/sync.py @@ -0,0 +1,214 @@ +"""The sync engine. + +A migration is a one-time event; onboarding does not end when it finishes. Source data +keeps changing — new contacts, edited accounts, deals that close — and the target has to +keep up. Sync is the ongoing half: re-read the source, rebuild every row with the same +`build_row` the dry-run and migration used, and apply only what changed. + +It runs behind the same approval gate as the migration: the mapping is what a person +approved, and sync does not change the mapping, so the approval still holds. Sync changes +*data*, and only in the safe direction — it inserts new records and updates changed ones. +It never deletes and never overwrites a good row with a broken one. Two situations call +for a human, so sync reports them and touches nothing: + + regressed a record that loaded cleanly at go-live now fails validation in the + source (someone blanked a required field). The good target row is left + as it is; nobody wants onboarding to blank a live record. + vanished a record in the target is no longer in the source. It may have been + deleted, or merged, or simply fallen out of the query. Deleting in the + target is a decision for the administrator, not for sync. + +Everything sync does is deterministic and idempotent: run it twice with no source change +and the second run reports everything unchanged. +""" + +from __future__ import annotations + +import json +import uuid +from collections import Counter +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, Field + +from firstsync import approval +from firstsync.config import get_settings +from firstsync.dryrun import SCAN_LIMIT, _split, build_row +from firstsync.mapping import ProposalStore +from firstsync.salesforce import ObjectNotAccessible, SalesforceClient +from firstsync.salesforce.rest import UNSAMPLED_TYPES +from firstsync.target import TARGET_SCHEMA +from firstsync.target.db import TargetDB, tenant_id + + +class TableSync(BaseModel): + table: str + source_object: str | None = None + read: int = 0 + added: int = 0 + changed: int = 0 + unchanged: int = 0 + warnings: int = 0 + regressed: list[str] = Field(default_factory=list) + vanished: list[str] = Field(default_factory=list) + still_blocked: list[str] = Field(default_factory=list) + still_needs_decision: list[str] = Field(default_factory=list) + not_runnable: str | None = None + + @property + def quiet(self) -> bool: + """True when nothing changed and nothing needs attention.""" + return not ( + self.added or self.changed or self.regressed or self.vanished + ) + + +class Sync(BaseModel): + run_id: str + connection: str + tenant_id: str + started_at: str + status: Literal["completed", "refused"] + refused_because: str | None = None + tables: list[TableSync] = Field(default_factory=list) + + def totals(self) -> dict[str, int]: + c: Counter[str] = Counter() + for t in self.tables: + c.update( + added=t.added, + changed=t.changed, + unchanged=t.unchanged, + regressed=len(t.regressed), + vanished=len(t.vanished), + ) + return dict(c) + + def needs_attention(self) -> bool: + return any(t.regressed or t.vanished for t in self.tables) + + +def run_sync( + client: SalesforceClient, + connection: str, + db: TargetDB, + limit: int = SCAN_LIMIT, +) -> Sync: + """Bring the target in step with the source. Refuses without a current approval.""" + gate = approval.check(connection) + base: dict[str, Any] = dict( + run_id=uuid.uuid4().hex[:12], + connection=connection, + tenant_id=tenant_id(connection), + started_at=datetime.now(UTC).isoformat(timespec="seconds"), + ) + if not gate["ok"]: + return Sync(**base, status="refused", refused_because=gate["why"]) + + sync = Sync(**base, status="completed") + proposals = ProposalStore(connection).load() + excluded = set(gate["approved"]["excluded"]) + tenant = sync.tenant_id + + for table, spec in TARGET_SCHEMA["tables"].items(): + fields = {f["name"]: {**f, "_table": table} for f in spec["fields"]} + mapped = { + name: (None if f"{table}.{name}" in excluded else proposals.get(f"{table}.{name}")) + for name in fields + } + source_object, _ = _split((mapped["external_id"] or {}).get("source")) + result = TableSync(table=table, source_object=source_object) + sync.tables.append(result) + if source_object is None: + result.not_runnable = "No approved source for external_id; this table is not synced." + continue + try: + describe = client.describe(source_object) + except ObjectNotAccessible as exc: + result.not_runnable = str(exc) + continue + + in_target = db.external_ids(table, tenant) + names = [f["name"] for f in describe["fields"] if f.get("type") not in UNSAMPLED_TYPES] + seen: set[str] = set() + for record_ in client.sample(source_object, names, limit): + result.read += 1 + record_id = str(record_.get("Id")) + seen.add(record_id) + row, status, _issues = build_row(record_, fields, mapped, source_object) + if status in ("blocking", "needs_decision"): + if record_id in in_target: + # It loaded before; the source broke. Leave the good row untouched. + result.regressed.append(record_id) + elif status == "blocking": + result.still_blocked.append(record_id) + else: + result.still_needs_decision.append(record_id) + continue + if status == "warning": + result.warnings += 1 + outcome = db.upsert(table, tenant, row) + if outcome == "inserted": + result.added += 1 + elif outcome == "updated": + result.changed += 1 + else: + result.unchanged += 1 + db.commit() + # In the target but no longer seen in the source. Reported, never deleted. + result.vanished = sorted(in_target - seen) + + save(sync) + return sync + + +# --- storage ---------------------------------------------------------------------------- + + +def _folder(connection: str) -> Path: + return get_settings().state_dir / "syncs" / connection + + +def save(sync: Sync) -> Path: + folder = _folder(sync.connection) + folder.mkdir(parents=True, exist_ok=True) + path = folder / f"{sync.run_id}.json" + path.write_text(sync.model_dump_json(indent=2) + "\n", encoding="utf-8") + (folder / "latest").write_text(sync.run_id, encoding="utf-8") + return path + + +def load(connection: str, run_id: str | None = None) -> Sync: + folder = _folder(connection) + if run_id is None: + pointer = folder / "latest" + if not pointer.is_file(): + raise ValueError(f"No sync has been run for {connection!r}.") + run_id = pointer.read_text(encoding="utf-8").strip() + if not run_id.isalnum(): + raise ValueError("Not a valid sync run id.") + path = folder / f"{run_id}.json" + if not path.is_file(): + raise ValueError(f"No sync {run_id!r} for {connection!r}.") + return Sync.model_validate(json.loads(path.read_text(encoding="utf-8"))) + + +def status_summary(sync: Sync) -> dict[str, Any]: + """What the model may see: counts and the Ids that need a human, read-only.""" + return { + "run_id": sync.run_id, + "status": sync.status, + "refused_because": sync.refused_because, + "started_at": sync.started_at, + "totals": sync.totals(), + "needs_attention": sync.needs_attention(), + "tables": [t.model_dump(exclude={"quiet"}) for t in sync.tables], + "note": ( + "Sync inserts new records and updates changed ones. It never deletes and " + "never overwrites a loaded record with a broken one. 'regressed' (was live, " + "now fails validation) and 'vanished' (gone from the source) are reported for " + "an administrator to decide; sync touches neither." + ), + } diff --git a/src/firstsync/target/db.py b/src/firstsync/target/db.py index be0a104..f09c704 100644 --- a/src/firstsync/target/db.py +++ b/src/firstsync/target/db.py @@ -90,6 +90,15 @@ def count(self, table: str, tenant: str) -> int: ) return int(result.fetchone()[0]) + def external_ids(self, table: str, tenant: str) -> set[str]: + """Every external_id already loaded into one table for one tenant.""" + if table not in TARGET_SCHEMA["tables"]: + raise ValueError(f"No such target table: {table!r}.") + rows = self._conn.execute( + f"SELECT external_id FROM {table} WHERE tenant_id = ?", (tenant,) + ) + return {str(r[0]) for r in rows.fetchall()} + def commit(self) -> None: self._conn.commit() diff --git a/tests/test_server.py b/tests/test_server.py index 6b65187..a335a4f 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -29,6 +29,7 @@ def test_server_exposes_exactly_the_expected_tools(): "sf_count_records", "sf_describe_object", "sf_sample_records", + "sync_get_status", "target_get_schema", ] assert all(t.description for t in listed) diff --git a/tests/test_sync.py b/tests/test_sync.py new file mode 100644 index 0000000..94f7122 --- /dev/null +++ b/tests/test_sync.py @@ -0,0 +1,176 @@ +"""The sync engine and the go-live report. + +Sync is tested by mutating a source and watching the target follow — but only in the +safe direction. The fixture client holds a reference to its objects dict, so changing the +dict between runs is exactly a source that changed between syncs. +""" + +from __future__ import annotations + +import copy +import json + +import pytest + +from firstsync import approval, dryrun, golive, migrate, sync +from firstsync.connections import orgs_dir +from firstsync.mapping import ProposalStore +from firstsync.salesforce import FixtureSalesforceClient +from firstsync.target.db import TargetDB, tenant_id + + +def proposals_for(org: str) -> dict: + data = json.load(open("results/claude-claude-sonnet-5-5.json", encoding="utf-8")) + return data["orgs"][org]["runs"][0]["proposals"] + + +@pytest.fixture(autouse=True) +def state(tmp_path, monkeypatch): + monkeypatch.setenv("FIRSTSYNC_STATE_DIR", str(tmp_path)) + + +@pytest.fixture() +def world(tmp_path): + """A mutable org_d, approved, already migrated into a fresh SQLite db.""" + fixture = json.loads((orgs_dir() / "org_d" / "fixture.json").read_text()) + fixture = copy.deepcopy(fixture) + client = FixtureSalesforceClient(fixture) + ProposalStore("org_d").save(proposals_for("org_d")) + dryrun.start(client, "org_d") # the admin previews before approving + approval.approve("org_d", approved_by="test") + db = TargetDB(str(tmp_path / "t.db")) + migrate.run_migration(client, "org_d", db) + return client, db, fixture + + +def contacts(fixture: dict) -> list[dict]: + return fixture["objects"]["Contact"]["records"] + + +def a_clean_contact(fixture: dict) -> dict: + """A contact that migrated cleanly (has an email).""" + return next(c for c in contacts(fixture) if c.get("Email")) + + +def test_no_change_means_all_unchanged(world): + client, db, _ = world + result = sync.run_sync(client, "org_d", db) + assert result.status == "completed" + t = result.totals() + assert t["added"] == 0 and t["changed"] == 0 + assert t["regressed"] == 0 and t["vanished"] == 0 + assert t["unchanged"] > 0 + assert result.needs_attention() is False + + +def test_new_source_record_is_added(world): + client, db, fixture = world + before = db.count("contacts", tenant_id("org_d")) + contacts(fixture).append({ + "Id": "003000000000999AAA", "AccountId": "001000000000001AAA", + "FirstName": "New", "LastName": "Person", "Email": "new.person@acme.example", + "Phone": "+15125550199", "Department": "Billing", + }) + result = sync.run_sync(client, "org_d", db) + added = next(t for t in result.tables if t.table == "contacts").added + assert added == 1 + assert db.count("contacts", tenant_id("org_d")) == before + 1 + + +def test_changed_source_record_is_updated(world): + client, db, fixture = world + target = a_clean_contact(fixture) + target["FirstName"] = "Renamed" + result = sync.run_sync(client, "org_d", db) + contacts_sync = next(t for t in result.tables if t.table == "contacts") + assert contacts_sync.changed == 1 + assert contacts_sync.added == 0 + + +def test_vanished_record_is_reported_never_deleted(world): + client, db, fixture = world + before = db.count("contacts", tenant_id("org_d")) + victim = a_clean_contact(fixture) + victim_id = victim["Id"] + contacts(fixture).remove(victim) + result = sync.run_sync(client, "org_d", db) + contacts_sync = next(t for t in result.tables if t.table == "contacts") + assert victim_id in contacts_sync.vanished + # Reported, not deleted: the row is still in the target. + assert db.count("contacts", tenant_id("org_d")) == before + assert victim_id in db.external_ids("contacts", tenant_id("org_d")) + assert result.needs_attention() is True + + +def test_regressed_record_is_flagged_and_left_intact(world): + client, db, fixture = world + target = a_clean_contact(fixture) + target_id = target["Id"] + target["Email"] = None # a required field, blanked at the source + result = sync.run_sync(client, "org_d", db) + contacts_sync = next(t for t in result.tables if t.table == "contacts") + assert target_id in contacts_sync.regressed + # The good target row is untouched — onboarding does not blank a live record. + assert target_id in db.external_ids("contacts", tenant_id("org_d")) + assert result.needs_attention() is True + + +def test_sync_refuses_without_approval(tmp_path): + fixture = json.loads((orgs_dir() / "org_d" / "fixture.json").read_text()) + client = FixtureSalesforceClient(fixture) + ProposalStore("org_d").save(proposals_for("org_d")) + db = TargetDB(str(tmp_path / "t.db")) + result = sync.run_sync(client, "org_d", db) + assert result.status == "refused" + assert "approval" in (result.refused_because or "").lower() + + +def test_sync_is_idempotent(world): + client, db, _ = world + first = sync.run_sync(client, "org_d", db) + second = sync.run_sync(client, "org_d", db) + assert first.totals()["unchanged"] == second.totals()["unchanged"] + assert second.totals()["added"] == 0 and second.totals()["changed"] == 0 + + +def test_save_and_load_roundtrip(world): + client, db, _ = world + result = sync.run_sync(client, "org_d", db) + assert sync.load("org_d") == result + assert sync.load("org_d", result.run_id) == result + with pytest.raises(ValueError): + sync.load("org_d", "../escape") + + +# --- go-live report --------------------------------------------------------------------- + + +def test_report_reflects_the_full_onboarding(world): + client, db, fixture = world + sync.run_sync(client, "org_d", db) + report = golive.build("org_d") + assert report["approved"]["by"] == "test" + assert report["migration"]["inserted"] == 387 + assert report["latest_sync"] is not None + # org_d's dry-run has blocking records and the approval has open questions. + assert any("cannot load" in item for item in report["open_items"]) + assert any("open question" in item for item in report["open_items"]) + text = golive.render(report) + assert "Onboarding: org_d" in text + assert "live" in report["headline"] + + +def test_report_before_approval_says_so(): + ProposalStore("org_d").save(proposals_for("org_d")) + report = golive.build("org_d") + assert report["approved"] is None + assert "Not approved" in report["headline"] + + +def test_report_flags_sync_attention(world): + client, db, fixture = world + contacts(fixture).remove(a_clean_contact(fixture)) + sync.run_sync(client, "org_d", db) + report = golive.build("org_d") + assert "attention" in report["headline"] + assert any("vanished" in item for item in report["open_items"])