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
42 changes: 32 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ 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 3 of 6.** Claude can inspect an org and propose a validated mapping for
> every target field; an evaluation scores those proposals against answer keys for six
> synthetic orgs; and a deterministic dry-run engine now executes stored proposals over
> real records — writing nothing — and reports, per record, whether it would load,
> grouped by root cause, with duplicates flagged by natural key. The evaluation checks
> that the pipeline catches the defects planted in org D (it catches 4 of 4, for both
> models tested). Approval, migration and sync are not built yet. This is a reference
> implementation with no customers. See
> **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).

## The rule the design is built on
Expand All @@ -34,7 +34,7 @@ The full design is in [docs/SPEC.md](docs/SPEC.md).

## What works today

Nine tools, served from one MCP server:
Ten tools, served from one MCP server:

| Tool | What it does |
| --- | --- |
Expand All @@ -47,6 +47,27 @@ Nine tools, served from one MCP server:
| `mapping_propose` | Validates mapping proposals and stores the valid ones for approval |
| `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 |

Approval and migration are deliberately **not** MCP tools. They are CLI commands run by
a person:

```bash
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
```

An approval stores a SHA-256 of each approved proposal. If any proposal changes
afterwards — the model proposed again, a file was edited — the migration refuses to run
and names the changed fields, until a person approves again. The migration builds every
row with the same `build_row` the dry-run used, so what the administrator saw in the
dry-run is exactly what loads: `clean` and `warning` records load (a warned optional
value is dropped), `blocking` and `needs_decision` records are skipped with their Ids in
the report. The upsert key is `(tenant, external_id)`, so re-running a migration is
always safe: the second run reports everything `unchanged`. The target database is
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.

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
Expand Down Expand Up @@ -82,7 +103,7 @@ Pythons refuse installs outside one.
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
pytest -q # 185 tests, no network, no API key
pytest -q # 198 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 @@ -252,6 +273,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 |
| 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
101 changes: 101 additions & 0 deletions src/firstsync/approval.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"""The approval gate.

Approval is a human act, done at the command line or (later) in the portal. It is not an
MCP tool, so there is no path by which the model approves its own proposals.

An approval binds to the content of what was approved: it stores a SHA-256 of each
proposal's canonical JSON. If a proposal changes afterwards — the model proposed again,
or a file was edited — the stored hash no longer matches and the migration refuses to
run until a person approves again. Approving is cheap; migrating something nobody looked
at is not.
"""

from __future__ import annotations

import getpass
import hashlib
import json
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

from firstsync.config import get_settings
from firstsync.mapping import ProposalStore, target_fields


def proposal_hash(proposal: dict[str, Any]) -> str:
canon = json.dumps(proposal, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canon.encode("utf-8")).hexdigest()[:16]


def _path(connection: str) -> Path:
return get_settings().state_dir / "approvals" / f"{connection}.json"


def load(connection: str) -> dict[str, Any] | None:
path = _path(connection)
if not path.is_file():
return None
return json.loads(path.read_text(encoding="utf-8"))


def approve(
connection: str, excluded: list[str] | None = None, approved_by: str | None = None
) -> dict[str, Any]:
"""Approve the proposals as they stand right now. Returns the approval record."""
proposals = ProposalStore(connection).load()
if not proposals:
raise ValueError(f"No proposals are stored for {connection!r}; nothing to approve.")
excluded = sorted(set(excluded or []))
unknown = [t for t in excluded if t not in target_fields()]
if unknown:
raise ValueError(f"Cannot exclude unknown target fields: {', '.join(unknown)}.")
unanswered = sorted(
t
for t, p in proposals.items()
if p.get("question_for_admin") and t not in excluded
)
record = {
"connection": connection,
"approved_at": datetime.now(UTC).isoformat(timespec="seconds"),
"approved_by": approved_by or getpass.getuser(),
"excluded": excluded,
"open_questions": unanswered,
"proposal_sha256_16": {
t: proposal_hash(p) for t, p in proposals.items() if t not in excluded
},
}
path = _path(connection)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(record, indent=2, sort_keys=True) + "\n", encoding="utf-8")
return record


def check(connection: str) -> dict[str, Any]:
"""Is the migration allowed to run? Returns {'ok': bool, 'why': ..., 'approved': ...}.

ok is True only when an approval exists and every approved hash still matches the
stored proposal. Targets excluded at approval time are simply not migrated.
"""
record = load(connection)
if record is None:
return {
"ok": False,
"why": f"No approval exists for {connection!r}. Run: firstsync approve {connection}",
}
proposals = ProposalStore(connection).load()
stale = sorted(
t
for t, digest in record["proposal_sha256_16"].items()
if proposal_hash(proposals.get(t, {})) != digest
)
if stale:
return {
"ok": False,
"why": (
"Proposals changed after approval for: "
+ ", ".join(stale)
+ f". Approve again: firstsync approve {connection}"
),
}
return {"ok": True, "approved": record}
66 changes: 63 additions & 3 deletions src/firstsync/cli.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
"""The firstsync command.

Three subcommands an administrator or a developer actually needs:
The subcommands an administrator or a developer actually needs:

firstsync serve run the MCP server on stdio (what Claude talks to)
firstsync dryrun ORG [--limit] run stored proposals over real records, write nothing
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 audit [--last N] show the last audit-log entries

Everything else happens through Claude; the CLI is the deterministic side.
Approval and migration are deliberately CLI commands, not MCP tools: the model proposes;
a person authorizes.
"""

from __future__ import annotations
Expand All @@ -15,8 +19,10 @@
import json
import sys

from firstsync import audit, dryrun
from firstsync import approval, audit, dryrun, migrate
from firstsync.connections import get_client
from firstsync.mapping import ProposalStore
from firstsync.target.db import TargetDB


def main(argv: list[str] | None = None) -> int:
Expand All @@ -29,6 +35,20 @@ def main(argv: list[str] | None = None) -> int:
run.add_argument("connection")
run.add_argument("--limit", type=int, default=dryrun.PREVIEW_LIMIT)

props = sub.add_parser("proposals", help="List stored proposals and approval state.")
props.add_argument("connection")

appr = sub.add_parser("approve", help="Approve the stored proposals as they stand.")
appr.add_argument("connection")
appr.add_argument("--except", dest="excluded", default="",
help="Comma-separated target fields to leave out of the approval.")
appr.add_argument("--by", default=None, help="Name to record as the approver.")

mig = sub.add_parser("migrate", help="Run the approved migration.")
mig.add_argument("connection")
mig.add_argument("--db", required=True, help="SQLite database path (created if absent).")
mig.add_argument("--limit", type=int, default=dryrun.SCAN_LIMIT)

log = sub.add_parser("audit", help="Show the last audit-log entries.")
log.add_argument("--last", type=int, default=20)

Expand All @@ -50,6 +70,46 @@ def main(argv: list[str] | None = None) -> int:
blocked = sum(t.blocking for t in result.tables)
return 1 if blocked else 0

if args.command == "proposals":
stored = ProposalStore(args.connection).load()
if not stored:
print(f"No proposals stored for {args.connection!r}.", file=sys.stderr)
return 2
gate = approval.check(args.connection)
state = "APPROVED" if gate["ok"] else gate["why"]
print(f"{len(stored)} proposals for {args.connection} [{state}]")
for target, p in sorted(stored.items()):
question = " ASKS" if p.get("question_for_admin") else ""
print(f" {target:<28} <- {p.get('source') or '(nothing)':<28} "
f"{p.get('confidence', '')}{question}")
return 0

if args.command == "approve":
excluded = [t for t in args.excluded.split(",") if t]
try:
record = approval.approve(args.connection, excluded, args.by)
except ValueError as exc:
print(str(exc), file=sys.stderr)
return 2
print(f"Approved {len(record['proposal_sha256_16'])} proposals for "
f"{args.connection} as {record['approved_by']}.")
if record["open_questions"]:
print("Open questions you are approving past (the dry-run flags these rows):")
for target in record["open_questions"]:
print(f" {target}")
return 0

if args.command == "migrate":
db = TargetDB(args.db)
try:
outcome = migrate.run_migration(
get_client(args.connection), args.connection, db, args.limit
)
finally:
db.close()
print(json.dumps(migrate.status_summary(outcome), indent=2))
return 0 if outcome.status == "completed" else 1

path = audit.log_path()
if not path.is_file():
print("No audit log yet.", file=sys.stderr)
Expand Down
80 changes: 59 additions & 21 deletions src/firstsync/dryrun.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,32 +159,38 @@ def run_dry_run(
)


def _one_record(
class Issue(BaseModel):
"""One field of one record that did not come out clean."""

target: str
reason: str
severity: Severity
source_field: str | None


def build_row(
record: dict[str, Any],
record_id: str,
fields: dict[str, dict[str, Any]],
mapped: dict[str, dict[str, Any] | None],
source_object: str,
treatments: dict[str, str],
table: str,
groups: dict[tuple[str, str], FailureGroup],
result: TableResult,
rows: list[tuple[str, dict[str, Any]]],
shown: list[dict[str, Any]],
) -> None:
) -> tuple[dict[str, Any], str, list[Issue]]:
"""Build one target row the way the migration would, and judge it.

This is the single row builder: the dry-run and the migration both call it, so what
the dry-run showed the administrator is exactly what the migration will do.
"""
table = next(iter(fields.values())).get("_table", "") if fields else ""
row: dict[str, Any] = {}
visible_row: dict[str, Any] = {}
status = "clean"
issues: list[Issue] = []
for name, field in fields.items():
proposal = mapped[name]
target = f"{table}.{name}"
if proposal is None:
value, failure = None, None
reason = check_target_value(field, None)
treatment = "pass"
src = None
else:
obj, src = _split(proposal.get("source"))
treatment = treatments.get(src or "", "pass") if obj else "pass"
raw = record.get(src) if obj == source_object and src else None
failure, reason, value = None, None, None
if obj is not None and obj != source_object:
Expand All @@ -197,20 +203,52 @@ def _one_record(
failure, reason = exc, str(exc)
if reason is None:
row[name] = value
hidden = treatment in ("shape", "summary") or _uses_concat(proposal)
visible_row[name] = display("shape", value) if hidden else value
continue
severity = _severity(field, failure or RuleFailure(reason))
if RANK[severity] > RANK[status]:
status = severity
source_field = _split((proposal or {}).get("source"))[1]
shown_input = display(treatment, record.get(source_field or ""))
group = groups.setdefault(
(target, reason),
FailureGroup(
target=target,
issues.append(
Issue(
target=f"{table}.{name}" if table else name,
reason=reason,
severity=severity,
source_field=src,
)
)
return row, status, issues


def _one_record(
record: dict[str, Any],
record_id: str,
fields: dict[str, dict[str, Any]],
mapped: dict[str, dict[str, Any] | None],
source_object: str,
treatments: dict[str, str],
table: str,
groups: dict[tuple[str, str], FailureGroup],
result: TableResult,
rows: list[tuple[str, dict[str, Any]]],
shown: list[dict[str, Any]],
) -> None:
named = {n: {**f, "_table": table} for n, f in fields.items()}
row, status, issues = build_row(record, named, mapped, source_object)
visible_row: dict[str, Any] = {}
for name, value in row.items():
proposal = mapped[name]
src = _split((proposal or {}).get("source"))[1]
treatment = treatments.get(src or "", "pass")
hidden = treatment in ("shape", "summary") or _uses_concat(proposal)
visible_row[name] = display("shape", value) if hidden else value
for issue in issues:
treatment = treatments.get(issue.source_field or "", "pass")
shown_input = display(treatment, record.get(issue.source_field or ""))
group = groups.setdefault(
(issue.target, issue.reason),
FailureGroup(
target=issue.target,
reason=issue.reason,
severity=issue.severity,
count=0,
record_ids=[],
example_input=shown_input,
Expand Down
Loading
Loading