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
45 changes: 34 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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 |
| --- | --- |
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
```
Expand Down Expand Up @@ -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). |
Expand Down
31 changes: 30 additions & 1 deletion src/firstsync/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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)
Expand Down
130 changes: 130 additions & 0 deletions src/firstsync/golive.py
Original file line number Diff line number Diff line change
@@ -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)
23 changes: 22 additions & 1 deletion src/firstsync/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -44,6 +44,7 @@
"dryrun_start",
"dryrun_get_results",
"migration_get_status",
"sync_get_status",
)

_calls = 0
Expand Down Expand Up @@ -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")

Expand Down
Loading
Loading