diff --git a/README.md b/README.md index ad12514..5149353 100644 --- a/README.md +++ b/README.md @@ -8,16 +8,38 @@ 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 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). +> **Status: week 6 of 6 — feature-complete.** 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 afterwards, adding and updating safely while reporting (never acting on) records +> that regressed or vanished. A go-live report and a `trace` view over the audit log tie +> it together. There is no tool by which the model approves, migrates, syncs, or deletes +> anything. The held-out org scored [100% with perfectly calibrated +> questions](#the-held-out-org-e). What remains is a hosted portal, not core logic. This +> is a reference implementation with no customers. See +> [What is and is not tested](#what-is-and-is-not-tested). + +```mermaid +flowchart LR + SF[(Customer
Salesforce)] -->|read-only, masked| C{{Claude}} + C -->|proposes mappings| P[Proposals
+ rules] + P --> D[Dry-run
deterministic] + D -->|per-record verdict| H([Human approves
hash-bound]) + H -->|authorizes| M[Migrate
idempotent] + M --> T[(Target DB)] + T --> Y[Sync
keeps in step] + SF -.-> Y + C -.every call logged.-> A[(Audit log
→ trace)] + classDef human fill:#fde68a,stroke:#b45309,color:#000; + classDef model fill:#dbeafe,stroke:#1e40af,color:#000; + class H human; + class C model; +``` + +Claude (blue) only ever reads and proposes. The human (amber) is the only authorizing +step. Everything between — dry-run, migrate, sync — is deterministic code. ## The rule the design is built on @@ -60,6 +82,18 @@ 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 +firstsync trace # what the agent did, read back from the audit log +``` + +Every tool call is logged with a hash of what it returned; `firstsync trace` reads that +log back and summarizes each session — the stages it moved through, every tool call, and +any failures. It is a reviewer's view, deliberately not an MCP tool: a person reads the +agent's record, the agent does not narrate its own. + +```text +Run de0581dc9e58 + stages: connect -> discover -> dryrun + calls: 4 (0 failed) ``` An approval stores a SHA-256 of each approved proposal. If any proposal changes @@ -125,7 +159,7 @@ Pythons refuse installs outside one. python3 -m venv .venv source .venv/bin/activate pip install -e ".[dev]" -pytest -q # 209 tests, no network, no API key +pytest -q # 214 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 ``` @@ -251,8 +285,43 @@ hypothetical questions on org B ("what if an unsampled record holds another valu same orgs. Each key change allowed a question that turned out to be legitimate; none changed a source. The first run also scored 100% but asked 17 extra questions in 4 runs. The full history is in [docs/week2-first-eval.md](docs/week2-first-eval.md). -- Org E has not been run. It is held out for exactly that reason and is run once, at the - end, with `--held-out`. +- Org E was held out and is now run (below). It is the one number tuned against nothing. + +### The held-out org (E) + +Org E was generated at the start, locked (two objects and several fields the connected +user cannot read), and **never looked at while the prompt or the answer keys were being +tuned**. It was run once, at the end: +[results/claude-claude-sonnet-5-5-held-out.json](results/claude-claude-sonnet-5-5-held-out.json). + +| | org E, held out | +| --- | --- | +| Accuracy | **29/29 (100%)** | +| Questions asked | 9 | +| Questions the key required | 9 | +| Extra questions | 0 | +| Cost / turns | ~$0.12, 14 turns | + +Every other 100% in this README was measured on an org the prompt had seen. This one was +not, and it is the result the project was built to earn. The accuracy matters less than +*how* it got there — the locked-down org is a test of judgment, not pattern-matching, and +the proposals show the judgment: + +- **It read values, not labels.** `accounts.industry` has no obvious source; the org's + `Segment__c` field *sounds* like something else. Claude looked at the sampled values + (Retail, Manufacturing, Healthcare…), saw they were industries, and mapped it — no + question needed. +- **It asked for access instead of inventing a source.** `contacts.email` and + `deals.amount` are required in the target but hidden by field-level security. Claude did + not guess a substitute; it named the missing field and asked for read access. +- **It asked once for a root cause, not once per symptom.** The whole `Task` object is + unreadable, which blocks six `activities.*` fields. Claude asked for Read on `Task` + once and pointed the other five at that one request, rather than raising six separate + questions — and left the optional `activities.notes` unmapped with no question at all. +- **It did not over-ask.** `contacts.role` had a plausible-looking source (`Title`), but + `Title` holds job titles, which the target explicitly says is not the role. Claude left + it unmapped without a question. 9 questions asked, 9 genuinely needed, 0 extra — on an + org it had never seen. ## How masking works @@ -297,6 +366,8 @@ administrator, and neither can a low-confidence mapping or a required field with | 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 | +| Trace / audit view | Unit tests: calls grouped by run, failures surfaced, connection filter, malformed lines skipped | +| Held-out org E | Run once, never tuned against; rescored by the repo's own scorer to 100% (29/29, 9/9 questions, 0 extra) | | 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/results/claude-claude-sonnet-5-5-held-out.json b/results/claude-claude-sonnet-5-5-held-out.json new file mode 100644 index 0000000..196991f --- /dev/null +++ b/results/claude-claude-sonnet-5-5-held-out.json @@ -0,0 +1,611 @@ +{ + "label": "claude-claude-sonnet-5-5-held-out", + "model": "claude-sonnet-5-5", + "orgs": { + "org_e": { + "mean_accuracy": 1.0, + "date": "2026-11-14T03:15:42+00:00", + "prompt_sha256_12": "a2d2c0412040", + "runs": [ + { + "org": "org_e", + "total": 29, + "accuracy": 1.0, + "counts": { + "correct": 29, + "should_have_asked": 0, + "wrong_source": 0, + "missed": 0, + "invented": 0 + }, + "questions_asked": 9, + "questions_required": 9, + "extra_questions": [], + "fields": [ + { + "target": "accounts.external_id", + "outcome": "correct", + "expected": "Account.Id", + "proposed": "Account.Id", + "must_ask": false + }, + { + "target": "accounts.name", + "outcome": "correct", + "expected": "Account.Name", + "proposed": "Account.Name", + "must_ask": false + }, + { + "target": "accounts.industry", + "outcome": "correct", + "expected": "Account.Segment__c", + "proposed": "Account.Segment__c", + "must_ask": false + }, + { + "target": "accounts.tier", + "outcome": "correct", + "expected": "Account.Plan_Level__c", + "proposed": "Account.Plan_Level__c", + "must_ask": true + }, + { + "target": "accounts.website", + "outcome": "correct", + "expected": "Account.Website", + "proposed": "Account.Website", + "must_ask": false + }, + { + "target": "accounts.customer_since", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": false + }, + { + "target": "accounts.owner_email", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": false + }, + { + "target": "contacts.external_id", + "outcome": "correct", + "expected": "Contact.Id", + "proposed": "Contact.Id", + "must_ask": false + }, + { + "target": "contacts.account_external_id", + "outcome": "correct", + "expected": "Contact.AccountId", + "proposed": "Contact.AccountId", + "must_ask": false + }, + { + "target": "contacts.first_name", + "outcome": "correct", + "expected": "Contact.FirstName", + "proposed": "Contact.FirstName", + "must_ask": false + }, + { + "target": "contacts.last_name", + "outcome": "correct", + "expected": "Contact.LastName", + "proposed": "Contact.LastName", + "must_ask": false + }, + { + "target": "contacts.email", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": true + }, + { + "target": "contacts.phone", + "outcome": "correct", + "expected": "Contact.Phone", + "proposed": "Contact.Phone", + "must_ask": false + }, + { + "target": "contacts.role", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": false + }, + { + "target": "deals.external_id", + "outcome": "correct", + "expected": "Opportunity.Id", + "proposed": "Opportunity.Id", + "must_ask": false + }, + { + "target": "deals.account_external_id", + "outcome": "correct", + "expected": "Opportunity.AccountId", + "proposed": "Opportunity.AccountId", + "must_ask": false + }, + { + "target": "deals.name", + "outcome": "correct", + "expected": "Opportunity.Name", + "proposed": "Opportunity.Name", + "must_ask": false + }, + { + "target": "deals.amount", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": true + }, + { + "target": "deals.currency", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": false + }, + { + "target": "deals.stage", + "outcome": "correct", + "expected": "Opportunity.StageName", + "proposed": "Opportunity.StageName", + "must_ask": false + }, + { + "target": "deals.close_date", + "outcome": "correct", + "expected": "Opportunity.CloseDate", + "proposed": "Opportunity.CloseDate", + "must_ask": false + }, + { + "target": "deals.owner_email", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": false + }, + { + "target": "activities.external_id", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": true + }, + { + "target": "activities.related_type", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": true + }, + { + "target": "activities.related_external_id", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": true + }, + { + "target": "activities.kind", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": true + }, + { + "target": "activities.subject", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": true + }, + { + "target": "activities.occurred_at", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": true + }, + { + "target": "activities.notes", + "outcome": "correct", + "expected": null, + "proposed": null, + "must_ask": false + } + ], + "turns": 14, + "seconds": 31.3, + "cost_usd": 0.12214199999999999, + "tool_calls": 13, + "dryrun_defects": null, + "proposals": { + "accounts.customer_since": { + "confidence": "high", + "evidence": [ + "describe:Account" + ], + "question_for_admin": null, + "reason": "No readable account date field in the org (optional); left unmapped.", + "rule": [], + "source": null, + "target": "accounts.customer_since" + }, + "accounts.external_id": { + "confidence": "high", + "evidence": [ + "describe:Account.Id" + ], + "question_for_admin": null, + "reason": "Source record Id.", + "rule": [], + "source": "Account.Id", + "target": "accounts.external_id" + }, + "accounts.industry": { + "confidence": "medium", + "evidence": [ + "describe:Account.Segment__c", + "sample:Account#1-40" + ], + "question_for_admin": null, + "reason": "Segment__c values are industries (Retail, Manufacturing, Technology, Energy, Healthcare, Financial Services), so it holds industry despite its label.", + "rule": [], + "source": "Account.Segment__c", + "target": "accounts.industry" + }, + "accounts.name": { + "confidence": "high", + "evidence": [ + "describe:Account.Name", + "sample:Account#1-40" + ], + "question_for_admin": null, + "reason": "Account name, required, matches.", + "rule": [], + "source": "Account.Name", + "target": "accounts.name" + }, + "accounts.owner_email": { + "confidence": "high", + "evidence": [ + "describe:Account" + ], + "question_for_admin": null, + "reason": "No owner or email field readable on Account (optional); left unmapped.", + "rule": [], + "source": null, + "target": "accounts.owner_email" + }, + "accounts.tier": { + "confidence": "low", + "evidence": [ + "describe:Account.Plan_Level__c", + "sample:Account#1-40" + ], + "question_for_admin": "How should Plan Level map to tier? I assumed Scale=enterprise, Growth=standard, Starter=free. Is Starter a paid plan that should be 'standard' instead?", + "reason": "Plan_Level__c has Scale/Growth/Starter; the three levels likely correspond to enterprise/standard/free but the org doesn't say, notably whether Starter is free or standard.", + "rule": [ + { + "case_insensitive": true, + "op": "map_values", + "table": { + "Growth": "standard", + "Scale": "enterprise", + "Starter": "free" + }, + "unmapped": "ask_admin" + } + ], + "source": "Account.Plan_Level__c", + "target": "accounts.tier" + }, + "accounts.website": { + "confidence": "high", + "evidence": [ + "describe:Account.Website", + "sample:Account#1-40" + ], + "question_for_admin": null, + "reason": "URL field maps directly.", + "rule": [], + "source": "Account.Website", + "target": "accounts.website" + }, + "activities.external_id": { + "confidence": "high", + "evidence": [ + "check_access:Task" + ], + "question_for_admin": "Please grant Read on Task (and Event if used) to the connected user via a permission set so activities can be mapped.", + "reason": "Activities would come from Task, which the connected user cannot read.", + "rule": [], + "source": null, + "target": "activities.external_id" + }, + "activities.kind": { + "confidence": "high", + "evidence": [ + "check_access:Task" + ], + "question_for_admin": "Blocked on Read permission for Task (see activities.external_id).", + "reason": "Task is unreadable; no source available.", + "rule": [], + "source": null, + "target": "activities.kind" + }, + "activities.notes": { + "confidence": "high", + "evidence": [ + "check_access:Task" + ], + "question_for_admin": null, + "reason": "Task is unreadable; optional field, left unmapped.", + "rule": [], + "source": null, + "target": "activities.notes" + }, + "activities.occurred_at": { + "confidence": "high", + "evidence": [ + "check_access:Task" + ], + "question_for_admin": "Blocked on Read permission for Task (see activities.external_id).", + "reason": "Task is unreadable; no source available.", + "rule": [], + "source": null, + "target": "activities.occurred_at" + }, + "activities.related_external_id": { + "confidence": "high", + "evidence": [ + "check_access:Task" + ], + "question_for_admin": "Blocked on Read permission for Task (see activities.external_id).", + "reason": "Task is unreadable; no source available.", + "rule": [], + "source": null, + "target": "activities.related_external_id" + }, + "activities.related_type": { + "confidence": "high", + "evidence": [ + "check_access:Task" + ], + "question_for_admin": "Blocked on Read permission for Task (see activities.external_id).", + "reason": "Task is unreadable; no source available.", + "rule": [], + "source": null, + "target": "activities.related_type" + }, + "activities.subject": { + "confidence": "high", + "evidence": [ + "check_access:Task" + ], + "question_for_admin": "Blocked on Read permission for Task (see activities.external_id).", + "reason": "Task is unreadable; no source available.", + "rule": [], + "source": null, + "target": "activities.subject" + }, + "contacts.account_external_id": { + "confidence": "high", + "evidence": [ + "describe:Contact.AccountId", + "sample:Contact#1-50" + ], + "question_for_admin": null, + "reason": "Reference to Account Id, which is used as accounts.external_id.", + "rule": [], + "source": "Contact.AccountId", + "target": "contacts.account_external_id" + }, + "contacts.email": { + "confidence": "high", + "evidence": [ + "describe:Contact" + ], + "question_for_admin": "Contact.Email is required in the target but isn't readable by the connected user. Please grant field-level read access on Contact.Email (and confirm it exists), or say where emails should come from.", + "reason": "Required, but Contact has no readable email field; describe shows only Id, AccountId, FirstName, LastName, Phone, Title. Possibly hidden by field-level security.", + "rule": [], + "source": null, + "target": "contacts.email" + }, + "contacts.external_id": { + "confidence": "high", + "evidence": [ + "describe:Contact.Id" + ], + "question_for_admin": null, + "reason": "Source record Id.", + "rule": [], + "source": "Contact.Id", + "target": "contacts.external_id" + }, + "contacts.first_name": { + "confidence": "high", + "evidence": [ + "describe:Contact.FirstName" + ], + "question_for_admin": null, + "reason": "Direct match.", + "rule": [], + "source": "Contact.FirstName", + "target": "contacts.first_name" + }, + "contacts.last_name": { + "confidence": "high", + "evidence": [ + "describe:Contact.LastName" + ], + "question_for_admin": null, + "reason": "Direct match, required.", + "rule": [], + "source": "Contact.LastName", + "target": "contacts.last_name" + }, + "contacts.phone": { + "confidence": "high", + "evidence": [ + "describe:Contact.Phone", + "sample:Contact#1-50", + "rule_test:Contact.Phone" + ], + "question_for_admin": null, + "reason": "US-format numbers normalize to E.164 with country code 1; 50/50 passed.", + "rule": [ + { + "default_country_code": "1", + "op": "normalize_phone" + } + ], + "source": "Contact.Phone", + "target": "contacts.phone" + }, + "contacts.role": { + "confidence": "high", + "evidence": [ + "describe:Contact.Title", + "sample:Contact#1-50" + ], + "question_for_admin": null, + "reason": "Title holds job titles (CTO, Controller, Analyst), which the target says is not the role. Nothing in the org holds buying-relationship role; optional, left unmapped.", + "rule": [], + "source": null, + "target": "contacts.role" + }, + "deals.account_external_id": { + "confidence": "high", + "evidence": [ + "describe:Opportunity.AccountId" + ], + "question_for_admin": null, + "reason": "Reference to Account Id.", + "rule": [], + "source": "Opportunity.AccountId", + "target": "deals.account_external_id" + }, + "deals.amount": { + "confidence": "high", + "evidence": [ + "describe:Opportunity" + ], + "question_for_admin": "Opportunity.Amount is required in the target but isn't readable. Please grant field-level read access on Opportunity.Amount, or tell us what the amount should be.", + "reason": "Required, but Opportunity has no readable Amount field (only Id, AccountId, Name, StageName, CloseDate). Likely blocked by field-level security.", + "rule": [], + "source": null, + "target": "deals.amount" + }, + "deals.close_date": { + "confidence": "high", + "evidence": [ + "describe:Opportunity.CloseDate", + "rule_test:Opportunity.CloseDate" + ], + "question_for_admin": null, + "reason": "Already ISO dates; 50/50 passed.", + "rule": [ + { + "op": "cast", + "to": "date" + } + ], + "source": "Opportunity.CloseDate", + "target": "deals.close_date" + }, + "deals.currency": { + "confidence": "medium", + "evidence": [ + "describe:Opportunity" + ], + "question_for_admin": null, + "reason": "No currency field readable; target says default USD, so USD is applied to all records.", + "rule": [ + { + "op": "default", + "value": "USD" + } + ], + "source": null, + "target": "deals.currency" + }, + "deals.external_id": { + "confidence": "high", + "evidence": [ + "describe:Opportunity.Id" + ], + "question_for_admin": null, + "reason": "Source record Id.", + "rule": [], + "source": "Opportunity.Id", + "target": "deals.external_id" + }, + "deals.name": { + "confidence": "high", + "evidence": [ + "describe:Opportunity.Name" + ], + "question_for_admin": null, + "reason": "Direct match.", + "rule": [], + "source": "Opportunity.Name", + "target": "deals.name" + }, + "deals.owner_email": { + "confidence": "high", + "evidence": [ + "describe:Opportunity" + ], + "question_for_admin": null, + "reason": "No owner field readable on Opportunity (optional); left unmapped.", + "rule": [], + "source": null, + "target": "deals.owner_email" + }, + "deals.stage": { + "confidence": "high", + "evidence": [ + "describe:Opportunity.StageName", + "rule_test:Opportunity.StageName" + ], + "question_for_admin": null, + "reason": "Each picklist value maps one-to-one to a target stage; 50/50 passed.", + "rule": [ + { + "op": "map_values", + "table": { + "Closed Lost": "closed_lost", + "Closed Won": "closed_won", + "Negotiation/Review": "negotiation", + "Proposal/Price Quote": "proposal", + "Prospecting": "lead", + "Qualification": "qualified" + }, + "unmapped": "error" + } + ], + "source": "Opportunity.StageName", + "target": "deals.stage" + } + } + } + ] + } + }, + "date": "2026-11-14T03:15:42+00:00", + "mean_accuracy": 1.0, + "rescored": "2026-11-14T03:24:33+00:00" +} diff --git a/src/firstsync/cli.py b/src/firstsync/cli.py index 0745360..228201f 100644 --- a/src/firstsync/cli.py +++ b/src/firstsync/cli.py @@ -9,6 +9,7 @@ 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 trace [--run ID] what the agent did, read back from the audit log firstsync audit [--last N] show the last audit-log entries Approval and migration are deliberately CLI commands, not MCP tools: the model proposes; @@ -21,7 +22,7 @@ import json import sys -from firstsync import approval, audit, dryrun, golive, migrate, sync +from firstsync import approval, audit, dryrun, golive, migrate, sync, trace from firstsync.connections import get_client from firstsync.mapping import ProposalStore from firstsync.target.db import TargetDB @@ -60,6 +61,10 @@ def main(argv: list[str] | None = None) -> int: rep.add_argument("connection") rep.add_argument("--json", action="store_true", help="Emit the raw report as JSON.") + tr = sub.add_parser("trace", help="Summarize what the agent did, from the audit log.") + tr.add_argument("--run", default=None, help="Show one run's full timeline.") + tr.add_argument("--connection", default=None, help="Only runs touching this connection.") + log = sub.add_parser("audit", help="Show the last audit-log entries.") log.add_argument("--last", type=int, default=20) @@ -139,6 +144,17 @@ def main(argv: list[str] | None = None) -> int: print(json.dumps(report, indent=2) if args.json else golive.render(report)) return 0 + if args.command == "trace": + if args.run: + try: + print(trace.render_run(trace.one(args.run))) + except ValueError as exc: + print(str(exc), file=sys.stderr) + return 2 + else: + print(trace.render_list(trace.runs(connection=args.connection))) + return 0 + path = audit.log_path() if not path.is_file(): print("No audit log yet.", file=sys.stderr) diff --git a/src/firstsync/trace.py b/src/firstsync/trace.py new file mode 100644 index 0000000..c639b7e --- /dev/null +++ b/src/firstsync/trace.py @@ -0,0 +1,129 @@ +"""A reviewer's view over the audit log. + +Every tool call has been recorded since week 1 — what was asked, whether it succeeded, a +hash of what came back, and the run ID that ties one onboarding session together. This +module reads that log back and summarizes it, so an operator can answer the question an +FDE is always asked: *what did the agent actually do, and did any of it fail?* + +It reads only. It never writes, and it is not an MCP tool — the agent does not get to +narrate its own record; a person reads it. +""" + +from __future__ import annotations + +import json +from collections import Counter +from pathlib import Path +from typing import Any + +from pydantic import BaseModel, Field + +from firstsync import audit + + +class RunTrace(BaseModel): + run_id: str + connections: list[str] = Field(default_factory=list) + started_at: str | None = None + ended_at: str | None = None + calls: int = 0 + failures: int = 0 + tools: dict[str, int] = Field(default_factory=dict) + stages: list[str] = Field(default_factory=list) + errors: list[dict[str, str]] = Field(default_factory=list) + + +def read_entries(path: Path | None = None) -> list[dict[str, Any]]: + """Every audit entry, oldest first. Malformed lines are skipped, not fatal.""" + path = path or audit.log_path() + if not path.is_file(): + return [] + entries = [] + for line in path.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line: + continue + try: + entries.append(json.loads(line)) + except json.JSONDecodeError: + continue + return entries + + +def _summarize(run_id: str, entries: list[dict[str, Any]]) -> RunTrace: + tools: Counter[str] = Counter() + stages: list[str] = [] + connections: list[str] = [] + errors: list[dict[str, str]] = [] + failures = 0 + for e in entries: + tools[e.get("tool", "?")] += 1 + stage = e.get("stage") + if stage and stage not in stages: + stages.append(stage) + conn = e.get("connection") + if conn and conn not in connections: + connections.append(conn) + if not e.get("ok", True): + failures += 1 + errors.append({"tool": e.get("tool", "?"), "error": e.get("error", "")}) + stamps = [e["ts"] for e in entries if e.get("ts")] + return RunTrace( + run_id=run_id, + connections=connections, + started_at=min(stamps) if stamps else None, + ended_at=max(stamps) if stamps else None, + calls=len(entries), + failures=failures, + tools=dict(sorted(tools.items())), + stages=stages, + errors=errors, + ) + + +def runs(path: Path | None = None, connection: str | None = None) -> list[RunTrace]: + """One trace per run_id, most recent first (by first-seen timestamp).""" + entries = read_entries(path) + if connection is not None: + entries = [e for e in entries if e.get("connection") == connection] + grouped: dict[str, list[dict[str, Any]]] = {} + for e in entries: + grouped.setdefault(e.get("run_id", "?"), []).append(e) + traces = [_summarize(rid, es) for rid, es in grouped.items()] + return sorted(traces, key=lambda t: t.started_at or "", reverse=True) + + +def one(run_id: str, path: Path | None = None) -> RunTrace: + entries = [e for e in read_entries(path) if e.get("run_id") == run_id] + if not entries: + raise ValueError(f"No audit entries for run {run_id!r}.") + return _summarize(run_id, entries) + + +def render_list(traces: list[RunTrace]) -> str: + if not traces: + return "No audit entries yet." + lines = [f"{'run':<14}{'when':<22}{'calls':>6}{'fail':>5} tools"] + for t in traces: + busiest = sorted(t.tools.items(), key=lambda x: -x[1])[:3] + top = ", ".join(f"{name}×{n}" for name, n in busiest) + lines.append( + f"{t.run_id:<14}{(t.started_at or ''):<22}{t.calls:>6}{t.failures:>5} {top}" + ) + return "\n".join(lines) + + +def render_run(t: RunTrace) -> str: + lines = [ + f"Run {t.run_id}", + f" connection(s): {', '.join(t.connections) or '(none)'}", + f" window: {t.started_at} -> {t.ended_at}", + f" stages: {' -> '.join(t.stages) or '(none)'}", + f" calls: {t.calls} ({t.failures} failed)", + " tools:", + ] + lines += [f" {name:<22}{n}" for name, n in t.tools.items()] + if t.errors: + lines.append(" failures:") + lines += [f" {e['tool']}: {e['error']}" for e in t.errors] + return "\n".join(lines) diff --git a/tests/test_trace.py b/tests/test_trace.py new file mode 100644 index 0000000..b7a65ce --- /dev/null +++ b/tests/test_trace.py @@ -0,0 +1,68 @@ +"""The trace view over the audit log.""" + +from __future__ import annotations + +import json + +import pytest + +from firstsync import audit, trace + + +@pytest.fixture(autouse=True) +def state(tmp_path, monkeypatch): + monkeypatch.setenv("FIRSTSYNC_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("FIRSTSYNC_AUDIT_LOG", str(tmp_path / "audit.jsonl")) + monkeypatch.setenv("FIRSTSYNC_RUN_ID", "run_aaaa") + + +def test_empty_log_is_not_an_error(): + assert trace.read_entries() == [] + assert trace.runs() == [] + assert "No audit entries" in trace.render_list([]) + + +def test_groups_calls_by_run(monkeypatch): + audit.record(tool="sf_describe_object", stage="discover", connection="org_b", + args={}, result={"x": 1}) + audit.record(tool="mapping_propose", stage="map", connection="org_b", args={}, result={}) + monkeypatch.setenv("FIRSTSYNC_RUN_ID", "run_bbbb") + audit.record(tool="rule_test", stage="map", connection="org_c", args={}, error="boom") + + all_runs = trace.runs() + assert len(all_runs) == 2 + by_id = {t.run_id: t for t in all_runs} + assert by_id["run_aaaa"].calls == 2 + assert by_id["run_aaaa"].failures == 0 + assert by_id["run_aaaa"].tools == {"mapping_propose": 1, "sf_describe_object": 1} + assert by_id["run_bbbb"].failures == 1 + assert by_id["run_bbbb"].errors[0]["error"] == "boom" + + +def test_filter_by_connection(): + audit.record(tool="t1", stage="s", connection="org_b", args={}, result={}) + audit.record(tool="t2", stage="s", connection="org_c", args={}, result={}) + only_b = trace.runs(connection="org_b") + assert sum(t.calls for t in only_b) == 1 + assert only_b[0].connections == ["org_b"] + + +def test_one_run_detail_and_missing(): + audit.record(tool="sf_count_records", stage="discover", connection="org_b", + args={}, result={}) + t = trace.one("run_aaaa") + assert t.calls == 1 + assert "sf_count_records" in trace.render_run(t) + with pytest.raises(ValueError): + trace.one("run_nope") + + +def test_malformed_lines_are_skipped(tmp_path): + path = tmp_path / "audit.jsonl" + path.write_text( + json.dumps({"run_id": "r", "tool": "t", "ts": "2026-01-01T00:00:00+00:00", "ok": True}) + + "\nnot json\n\n", + encoding="utf-8", + ) + entries = trace.read_entries(path) + assert len(entries) == 1