场景 115 · Codex Use Case

迁移一个验证模块

提供边界明确的迁移说明、契约夹具和云端环境,升级一个验证模块,交付聚焦改动、行为一致性证据、剩余差异和回滚说明。

EngineeringCode
Migrate a validation moduleEngineeringCodeQuality

原文核对:2026-11-10 · 中文正文 · 英文提示词与演示

场景定位

提供边界明确的迁移说明、契约夹具和云端环境,升级一个验证模块,交付聚焦改动、行为一致性证据、剩余差异和回滚说明。

难度
高级
时间跨度
长时间运行

适合用于

  • 迁移遗留验证组件的工程团队。
  • 具备明确契约和可重复测试的迁移任务。
  • 需要在其他模块继续工作时提交小范围审阅改动的团队。

起步提示词

英文原文 · 可复制后按实际材料修改

Migrate [module] in [repository] from [current pinned version] to [approved target version] in this cloud environment.

Read AGENTS.md, [migration brief], [official migration guide], the dependency lockfile, the module's callers, and [contract test locations]. Record the starting commit, environment/setup reference, installed Python version, framework/Pydantic/bundled-v1 versions, and lockfile hash. Confirm baseline/target compatibility; treat shared dependency/import preparation as a separate reviewed change.

First run [baseline commands], inventory the migration surface, and write a short plan in [plan file]. Preserve [public contracts]. Keep [out-of-scope modules] unchanged. Remove obsolete code only inside the approved slice; name any compatibility adapter that must remain.

If the slice can be isolated and the baseline is usable, run the same frozen HTTP contract tests before and after the change through the real router, error handler, and response serialization. Compare status codes, contractual headers, accepted/rejected inputs, public JSON keys/types, defaults/nulls, and the complete error envelope. Run affected integration, lint and type checks too. If this requires broader upgrades or public behavior changes, return that decision before expanding scope. Do not approve new snapshots, normalize away public differences or weaken assertions. Record each check's revisions/environment/versions, before/after commands, exit codes, evidence paths, and pass/fail/blocked/not run with limitations.

Return the diff, before-and-after evidence, unresolved differences, dependency and lockfile changes, rollback instructions, and a draft PR description. Create a draft PR only if the connected repository tools and my permissions support it; otherwise provide the patch and description. Do not merge, deploy, change production data, or begin another slice.

适用时机

迁移具有清晰边界,且测试能够比较新旧行为时使用。提供迁移说明、模块及调用方、冻结的契约夹具和准备好的云端环境,要求聚焦改动、证据和回滚路径。

示例将订单服务中的一个验证模型从 Pydantic v1 迁移到 v2,包含原实现、兼容准备阶段和最终模块。测试覆盖真实 FastAPI 路由、错误处理、响应序列化、相邻遗留路由及公开 OpenAPI 文档,不包含数据库迁移或部署。

准备云端环境

  1. 选择 Work in > Cloud,选用已发布环境。
  2. 新建环境时选择 Create environment 和 GitHub 仓库,让 Codex 准备运行时、依赖及隔离测试服务。
  3. 检查设置报告,解决失败检查,Publish 后再开始新任务。
  • 遵循 Cloud 环境指南。
  • 将仓库指引保存在 AGENTS.md。

依赖或服务设置变化时,编辑可复用环境,测试并重新发布。

在新任务中验证更新。仓库刷新保留依赖缓存,不重新运行安装或启动命令;已有任务保留自身状态。

分别配置所需网络目标和凭据。

每个阶段记录环境/设置引用、源提交、Python 补丁版本、框架和依赖版本、包管理器版本及锁文件哈希。使用结果前,在新任务内部核实这些版本。

运行示例

下载完整迁移示例,其中包含三个独立 uv 项目、已解析的 uv.lock、应用实现、共享错误与 schema 适配器、冻结 HTTP 夹具和契约运行器。

使用 Python 3.11、3.12 或 3.13,安装 uv 后运行:

官方代码示例
unzip sample.zip
cd migrate-a-validation-module
uv run --project support/target --python python3 --frozen python run.py --compare-stages --output evidence

比较过程为每个阶段创建独立 .venv,通过 uv sync --frozen 安装依赖。各阶段使用调用命令的同一 Python 解释器,以及相同 HTTP 和 schema 夹具,依赖版本保持锁定。

遗留 Pydantic v1 兼容桥不支持 Python 3.14 及以后版本,因此排除这些版本。成功运行的末尾输出如下:

官方代码示例
PASS: legacy, prepared, target HTTP/schema/serialization contracts match
Native model schemas differ; the existing public schema adapter is preserved.

阅读 evidence/legacy.json、prepared.json、target.json 和 summary.json,其中保存实际响应、运行时版本、源文件/夹具/锁文件哈希、命令、退出码和原始日志路径。

运行器通过 FastAPI 进程内 TestClient 测试 HTTP 端点。应在选定 Cloud 任务中运行,并保留该任务的证据。

不带 --compare-stages 的 python3 run.py 仅用于已安装 Pydantic v2 的环境中检查目标模型。该独立模式只检查七项验证与序列化案例,不验证 HTTP 或跨阶段一致性;迁移验收应使用完整比较命令。

完整比较在每阶段检查 23 个 HTTP 案例、公开 OpenAPI 及响应序列化,示例已在本地 Python 3.11、3.12、3.13 通过。README.md 记录测试版本和历史;仍需在当前 Cloud 环境运行并保存结果。

分开处理依赖阶段

阶段Python / FastAPI / Pydantic迁移边界
遗留3.11–3.13 / 0.119.0 / 1.10.22现有模型从 pydantic 导入。
准备基线3.11–3.13 / 0.119.0 / 2.12.3两个模型均使用 pydantic.v1,记录实际捆绑的 v1 版本。
目标3.11–3.13 / 0.119.0 / 2.12.3仅 OrderInput 迁移到 v2;相邻路由保留独立 v1 模型。

准备和目标阶段的依赖锁完全相同。本次模块迁移改变模型和直接序列化方法,不改变依赖环境。

兼容准备应作为独立改动审阅。它还将剩余 v1 路由适配器调整为在响应验证前通过 dict(by_alias=True) 返回别名键字典;在 v2 宿主下直接返回 v1 模型可能丢失公开别名。

目标订单适配器使用 model_dump(by_alias=True),相邻 v1 路由保留准备阶段的适配器。

FastAPI 迁移指南将临时混合 v1/v2 路由支持限定为 0.119.0 至 0.127.x;0.128.0 已移除该支持。

示例刻意固定 0.119.0 以演示过渡。较新版 FastAPI 应使用完整 v2 边界,并为临时兼容桥指定负责人和移除条件。不要嵌套 v1 与 v2 模型;该兼容桥不是 Python 3.14 的迁移方案。

审阅契约测试

冻结的 HTTP 案例覆盖成功请求、缺省及显式 null 备注、缺失/无效 ID、多个未知字段、混合字段错误、无效备注、畸形 JSON、错误 Content-Type、缺失请求体、别名、数组及字符串请求体和相邻遗留路由。比较状态码、Content-Type 和完整解析 JSON,不删除错误字段或改变预期类型。

服务从遗留阶段起就有应用自有错误封装与公开 OpenAPI 文档,错误和 schema 适配器保持不变。目标保留原错误顺序:先声明字段错误,再按字母顺序排列未知键。

测试比较完整且有序的 error.fields 数组,不排序实际响应。运行器另行记录各模型原生 schema,并确认它们不同;公开 schema 一致并不表示依赖生成的原生 schema 相同。

服务保留遗留输入行为:接受 [["order_id", "ord_123"]] 这样的键值对数组作为对象;[] 和空 JSON 字符串变成空对象,产生缺失 ID 错误;非空字符串仍无效。目标保留成功的 dict(value) 转换。如要只接受对象,需由负责人决定契约,不能直接改测试预期。

在自己的仓库中,修改前冻结实际响应。通过显式默认值保留可选字段,保持严格性与未知字段行为,并测试真实错误处理器和响应序列化。

版本间原始验证错误存在差异。Pydantic 迁移指南还说明别名、类型转换、可选字段和自定义验证函数的变化;v2 不再将验证函数抛出的 TypeError 转为 ValidationError。

检查契约运行器

以下来自下载文件 run.py,解压后运行完整文件;锁定阶段和 HTTP 夹具均已包含。

官方代码示例
class OrderInput(BaseModel):
    internal_order_id: StrictStr = Field(alias="order_id")
    customer_note: StrictStr | None = None
    model_config = ConfigDict(extra="forbid", populate_by_name=False)

    @model_validator(mode="before")
    @classmethod
    def preserve_legacy_mapping(cls, value):
        # v1 tries dict(value), so pairs, [] and "" can become objects.
        # Preserve successful conversions without changing failed-input errors.
        if not isinstance(value, dict):
            try:
                return dict(value)
            except (TypeError, ValueError):
                return value
        return value


def serialize_order(payload):
    return OrderInput(**payload).model_dump(by_alias=True)


def preserve_legacy_error_order(fields):
    # v1 reports declared-field errors first and unknown keys alphabetically.
    # v2 keeps unknown keys in input order; preserve the existing HTTP contract.
    known = [field for field in fields if field["code"] != "extra_forbidden"]
    extra = sorted(
        (field for field in fields if field["code"] == "extra_forbidden"),
        key=lambda field: field["path"],
    )
    return known + extra


def check_target_model():
    for payload, expected in (
        ({"order_id": "ord_123"}, {"order_id": "ord_123", "customer_note": None}),
        (
            {"order_id": "ord_123", "customer_note": "Leave at desk"},
            {"order_id": "ord_123", "customer_note": "Leave at desk"},
        ),
        (
            {"order_id": "ord_123", "customer_note": None},
            {"order_id": "ord_123", "customer_note": None},
        ),
    ):
        assert serialize_order(payload) == expected
    for payload, expected in (
        ({}, [("order_id", "missing")]),
        ({"order_id": 123}, [("order_id", "string_type")]),
        (
            {"order_id": "ord_123", "customer_note": 17},
            [("customer_note", "string_type")],
        ),
        (
            {"order_id": "ord_123", "unexpected": True},
            [("unexpected", "extra_forbidden")],
        ),
    ):
        try:
            OrderInput(**payload)
        except ValidationError as error:
            assert [
                (item["loc"][0], item["type"]) for item in error.errors()
            ] == expected
        else:
            raise AssertionError(f"Accepted invalid order: {payload}")
    print("PASS: target model validation and serialization (7 cases)")
    print("Model-only checks; use --compare-stages for HTTP migration parity.")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, default=ROOT / "evidence")
    parser.add_argument("--compare-stages", action="store_true")
    args = parser.parse_args()
    if not args.compare_stages:
        check_target_model()
        return
    args.output.mkdir(parents=True, exist_ok=True)
    reports = []
    commands = []
    for stage in ("legacy", "prepared", "target"):
        project = Path("support") / stage
        stage_commands = [
            [
                "uv",
                "sync",
                "--project",
                str(project),
                "--python",
                sys.executable,
                "--frozen",
            ],
            [
                "uv",
                "run",
                "--project",
                str(project),
                "--python",
                sys.executable,
                "--frozen",
                "python",
                "test/run_stage.py",
                stage,
                str(args.output / f"{stage}.json"),
            ],
        ]
        for command in stage_commands:
            completed = subprocess.run(
                command, cwd=ROOT, capture_output=True, text=True
            )
            label = f"{stage}-{len(commands)}"
            (args.output / f"{label}.log").write_text(
                completed.stdout + completed.stderr
            )
            commands.append(
                {
                    "command": command,
                    "exit_code": completed.returncode,
                    "log": f"{label}.log",
                }
            )
            (args.output / "commands.json").write_text(
                json.dumps(commands, indent=2, sort_keys=True) + "\n"
            )
            if completed.returncode:
                print(completed.stdout + completed.stderr, file=sys.stderr)
                raise SystemExit(completed.returncode)
            print(completed.stdout, end="")
        reports.append(json.loads((args.output / f"{stage}.json").read_text()))
    assert all(report["python"] == platform.python_version() for report in reports)
    for report in reports[1:]:
        for key in (
            "observations",
            "public_openapi",
            "direct_call",
            "fixture_sha256",
            "schema_fixture_sha256",
        ):
            assert report[key] == reports[0][key], f"Parity failed: {key}"
    assert reports[1]["lock_sha256"] == reports[2]["lock_sha256"]
    native_schema_differs = (
        reports[0]["native_model_schema"] != reports[2]["native_model_schema"]
    )
    assert native_schema_differs, "The example should expose native schema drift"
    manifest = {
        str(path.relative_to(ROOT)): digest(path)
        for path in sorted(ROOT.rglob("*"))
        if path.is_file()
        and not path.resolve().is_relative_to(args.output.resolve())
        and not any(
            part in {".venv", "__pycache__", "evidence", ".ruff_cache"}
            for part in path.relative_to(ROOT).parts
        )
    }
    summary = {
        "status": "pass",
        "scope": "synthetic in-process FastAPI TestClient execution",
        "stages": [report["stage"] for report in reports],
        "http_cases_per_stage": reports[0]["http_cases"],
        "native_model_schema_differs": native_schema_differs,
        "public_http_and_schema_parity": True,
        "commands": commands,
        "source_sha256": manifest,
    }
    (args.output / "summary.json").write_text(
        json.dumps(summary, indent=2, sort_keys=True) + "\n"
    )
    print("PASS: legacy, prepared, target HTTP/schema/serialization contracts match")
    print(
        "Native model schemas differ; the existing public schema adapter is preserved."
    )

在自己的仓库运行流程

  1. 编写说明:指定模块、直接调用方、负责人、获准版本、契约测试、范围外代码和回滚方式。需要更广泛依赖升级或改变公开行为时暂停。
  2. 建立基线:让 Codex 阅读 AGENTS.md、迁移说明、官方指南、锁文件、调用方和测试,记录起始提交及安装版本;宣称一致前先解释或修复基线失败。
  3. 单独准备兼容:共享依赖将模块与其他代码耦合时,先审查准备改动,证明相同夹具在原始与准备基线上均通过。
  4. 迁移一个切片:使用本页起始提示词,仅修改模块及直接适配器,保留无关模块,说明仍存在的兼容代码。
  5. 运行相同测试:不改变预期,比较基线与最终 HTTP/schema 夹具;运行受影响集成、lint 和类型检查,保存绑定最终源代码及依赖状态的输出。
  6. 审阅交接:检查差异、实际证据、未解决区别、剩余兼容桥和回滚方案。仅在工具和权限支持时创建草稿 PR;合并、部署及下一迁移切片交给审阅者。

记录验证结果

为每项验收标准保存证据记录:

官方代码示例
Criterion: [behavior and test]
Environment: [setup reference; actual runtime and dependency versions]
Before: [commit/diff ID; command; exit code; observed result; evidence path]
After: [final commit/diff ID; command; exit code; observed result; evidence path]
Status: [pass / fail / blocked / not run]
Limits: [untested behavior, missing prerequisite, or required owner decision]

导入成功、lint 通过或重新生成快照都不能证明 API 行为一致。单独记录有意差异,最终源码变化后重跑检查。改编示例时,将应用真实调用方和服务纳入契约测试。

展开英文原文对照

Give Codex a bounded migration brief, contract fixtures, and a prepared cloud environment. Upgrade one validation module and return the focused change, parity evidence, remaining differences, and rollback instructions.

When to use it

Use this workflow when a migration has a clear boundary and tests that compare old and new behavior. Give Codex a migration brief, the module and its callers, frozen contract fixtures, and a prepared cloud environment. Ask for one focused change with evidence and a rollback path.

The sample migrates one validation model in an orders service from Pydantic v1 to v2. It includes the original implementation, a compatibility preparation stage, and the final module. Its tests exercise the real FastAPI router, error handler, response serialization, adjacent legacy route, and public OpenAPI document. No database migration or deployment is included.

Prepare the cloud environment

  1. Choose Work in > Cloud and select a published environment.
  2. To create one, select Create environment, choose the GitHub repositories, and ask Codex to prepare the runtime, dependencies, and isolated test services.
  3. Review the setup report, resolve failed checks, and Publish before starting a new task.
  • Follow the Cloud environment guide.
  • Keep repository guidance in AGENTS.md.

If dependencies change or service setup changes, edit the reusable environment, test it, and Republish.

Validate the updated environment in a new task. Repository refresh preserves dependency caches without rerunning installation or startup commands, and existing tasks retain their own state.

Configure required network destinations and credentials separately.

Record the environment/setup reference, source commit, Python patch version, framework and dependency versions, package-manager version, and lockfile hash at each stage. Verify those versions inside the new task before using its results.

Run the sample

Download the complete migration sample. It includes three standalone uv projects, their resolved uv.lock files, application implementations, a shared error and schema adapter, frozen HTTP fixtures, and the contract runner.

Use Python 3.11, 3.12, or 3.13 and install uv, then run:

官方代码示例
unzip sample.zip
cd migrate-a-validation-module
uv run --project support/target --python python3 --frozen python run.py --compare-stages --output evidence

The comparison creates a separate .venv for each stage and installs dependencies with uv sync --frozen. All stages use the invoking Python interpreter and the same HTTP and schema fixtures; dependency versions remain locked.

Python 3.14 and later are excluded because the legacy Pydantic v1 bridge does not support them. A successful run ends with:

官方代码示例
PASS: legacy, prepared, target HTTP/schema/serialization contracts match
Native model schemas differ; the existing public schema adapter is preserved.

Read evidence/legacy.json, prepared.json, target.json, and summary.json. They contain observed responses, runtime versions, source, fixture, and lockfile hashes, commands, exit codes, and raw-log paths.

The runner exercises the sample application’s HTTP endpoints through FastAPI’s in-process TestClient. Run it inside your chosen Cloud task and retain that task’s evidence.

Run python3 run.py without --compare-stages only to check the target model in an environment with Pydantic v2 installed. That self-contained mode checks seven validation and serialization cases. It does not run HTTP or cross-stage parity checks. Use the full comparison command above to verify a migration.

The full comparison checks 23 HTTP cases in each stage, public OpenAPI, and response serialization. It passed locally on Python 3.11, 3.12, and 3.13. The download’s README.md records the tested versions and execution history. Run the current comparison in your Cloud environment to record its results there.

Keep the dependency stages separate

StagePython / FastAPI / PydanticMigration boundary
Legacy3.11–3.13 / 0.119.0 / 1.10.22Existing models import from pydantic.
Prepared baseline3.11–3.13 / 0.119.0 / 2.12.3Both models use pydantic.v1. Record the actual bundled-v1 version.
Target3.11–3.13 / 0.119.0 / 2.12.3Only OrderInput moves to v2. The adjacent route keeps its separate v1 model.

The prepared and target dependency locks are identical. The module slice changes the model and its direct serialization method, not the dependency environment.

The preparation step is a separate reviewed change. It also makes the remaining v1 route adapters emit alias-keyed dictionaries with dict(by_alias=True) before response validation; returning the v1 model directly under the v2 host can lose public aliases.

The target order adapter uses model_dump(by_alias=True), and the adjacent v1 route keeps its preparation adapter.

The FastAPI migration guide limits temporary mixed v1/v2 route support to 0.119.0 through 0.127.x; 0.128.0 removed it.

This example deliberately pins 0.119.0 to demonstrate that transition. Use a fully v2 boundary for a newer FastAPI application, and keep an owner and removal condition for the temporary bridge. Do not nest v1 and v2 models. This bridge is not a Python 3.14 migration path.

Review the contract tests

The frozen HTTP cases cover successful requests, an omitted note or a note explicitly set to null, missing and invalid IDs, multiple unknown fields, mixed field errors, invalid notes, malformed JSON, wrong content type, missing body, aliases, array and string bodies, and the adjacent legacy route. They compare status codes, the Content-Type header, and complete parsed JSON responses without stripping error fields or changing expected types.

The service has an application-owned error envelope and public OpenAPI document from the legacy stage. The error and schema adapters remain in place. The target preserves the legacy error order: declared-field errors first, then unknown keys alphabetically.

The tests compare the complete ordered error.fields array; they do not sort observed responses. The runner records each model’s native schema separately and verifies that native schemas differ; public schema parity does not mean the dependency’s generated schemas are identical.

The service preserves a legacy input behavior: it accepts an array of pairs such as [["order_id", "ord_123"]] as an object, and both [] and an empty JSON string become empty objects with a missing-ID error. A nonempty string remains an invalid body. The target model keeps successful dict(value) conversions. Changing it to object-only input requires an owner’s contract decision, not a rewritten test expectation.

For your repository, freeze its actual existing responses before editing. Preserve optional fields with explicit defaults, keep strictness and unknown-field behavior, and test the real error handler and response serialization.

Raw validation errors differ across versions. The Pydantic migration guide also describes changes to aliases, coercion, optional fields, and custom validation functions; v2 does not convert TypeError raised inside those functions into ValidationError.

Inspect the contract runner

This excerpt comes from run.py in the download. Run the complete files after extracting the ZIP; the locked stages and HTTP fixtures are included there.

官方代码示例
class OrderInput(BaseModel):
    internal_order_id: StrictStr = Field(alias="order_id")
    customer_note: StrictStr | None = None
    model_config = ConfigDict(extra="forbid", populate_by_name=False)

    @model_validator(mode="before")
    @classmethod
    def preserve_legacy_mapping(cls, value):
        # v1 tries dict(value), so pairs, [] and "" can become objects.
        # Preserve successful conversions without changing failed-input errors.
        if not isinstance(value, dict):
            try:
                return dict(value)
            except (TypeError, ValueError):
                return value
        return value


def serialize_order(payload):
    return OrderInput(**payload).model_dump(by_alias=True)


def preserve_legacy_error_order(fields):
    # v1 reports declared-field errors first and unknown keys alphabetically.
    # v2 keeps unknown keys in input order; preserve the existing HTTP contract.
    known = [field for field in fields if field["code"] != "extra_forbidden"]
    extra = sorted(
        (field for field in fields if field["code"] == "extra_forbidden"),
        key=lambda field: field["path"],
    )
    return known + extra


def check_target_model():
    for payload, expected in (
        ({"order_id": "ord_123"}, {"order_id": "ord_123", "customer_note": None}),
        (
            {"order_id": "ord_123", "customer_note": "Leave at desk"},
            {"order_id": "ord_123", "customer_note": "Leave at desk"},
        ),
        (
            {"order_id": "ord_123", "customer_note": None},
            {"order_id": "ord_123", "customer_note": None},
        ),
    ):
        assert serialize_order(payload) == expected
    for payload, expected in (
        ({}, [("order_id", "missing")]),
        ({"order_id": 123}, [("order_id", "string_type")]),
        (
            {"order_id": "ord_123", "customer_note": 17},
            [("customer_note", "string_type")],
        ),
        (
            {"order_id": "ord_123", "unexpected": True},
            [("unexpected", "extra_forbidden")],
        ),
    ):
        try:
            OrderInput(**payload)
        except ValidationError as error:
            assert [
                (item["loc"][0], item["type"]) for item in error.errors()
            ] == expected
        else:
            raise AssertionError(f"Accepted invalid order: {payload}")
    print("PASS: target model validation and serialization (7 cases)")
    print("Model-only checks; use --compare-stages for HTTP migration parity.")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, default=ROOT / "evidence")
    parser.add_argument("--compare-stages", action="store_true")
    args = parser.parse_args()
    if not args.compare_stages:
        check_target_model()
        return
    args.output.mkdir(parents=True, exist_ok=True)
    reports = []
    commands = []
    for stage in ("legacy", "prepared", "target"):
        project = Path("support") / stage
        stage_commands = [
            [
                "uv",
                "sync",
                "--project",
                str(project),
                "--python",
                sys.executable,
                "--frozen",
            ],
            [
                "uv",
                "run",
                "--project",
                str(project),
                "--python",
                sys.executable,
                "--frozen",
                "python",
                "test/run_stage.py",
                stage,
                str(args.output / f"{stage}.json"),
            ],
        ]
        for command in stage_commands:
            completed = subprocess.run(
                command, cwd=ROOT, capture_output=True, text=True
            )
            label = f"{stage}-{len(commands)}"
            (args.output / f"{label}.log").write_text(
                completed.stdout + completed.stderr
            )
            commands.append(
                {
                    "command": command,
                    "exit_code": completed.returncode,
                    "log": f"{label}.log",
                }
            )
            (args.output / "commands.json").write_text(
                json.dumps(commands, indent=2, sort_keys=True) + "\n"
            )
            if completed.returncode:
                print(completed.stdout + completed.stderr, file=sys.stderr)
                raise SystemExit(completed.returncode)
            print(completed.stdout, end="")
        reports.append(json.loads((args.output / f"{stage}.json").read_text()))
    assert all(report["python"] == platform.python_version() for report in reports)
    for report in reports[1:]:
        for key in (
            "observations",
            "public_openapi",
            "direct_call",
            "fixture_sha256",
            "schema_fixture_sha256",
        ):
            assert report[key] == reports[0][key], f"Parity failed: {key}"
    assert reports[1]["lock_sha256"] == reports[2]["lock_sha256"]
    native_schema_differs = (
        reports[0]["native_model_schema"] != reports[2]["native_model_schema"]
    )
    assert native_schema_differs, "The example should expose native schema drift"
    manifest = {
        str(path.relative_to(ROOT)): digest(path)
        for path in sorted(ROOT.rglob("*"))
        if path.is_file()
        and not path.resolve().is_relative_to(args.output.resolve())
        and not any(
            part in {".venv", "__pycache__", "evidence", ".ruff_cache"}
            for part in path.relative_to(ROOT).parts
        )
    }
    summary = {
        "status": "pass",
        "scope": "synthetic in-process FastAPI TestClient execution",
        "stages": [report["stage"] for report in reports],
        "http_cases_per_stage": reports[0]["http_cases"],
        "native_model_schema_differs": native_schema_differs,
        "public_http_and_schema_parity": True,
        "commands": commands,
        "source_sha256": manifest,
    }
    (args.output / "summary.json").write_text(
        json.dumps(summary, indent=2, sort_keys=True) + "\n"
    )
    print("PASS: legacy, prepared, target HTTP/schema/serialization contracts match")
    print(
        "Native model schemas differ; the existing public schema adapter is preserved."
    )

Run the workflow in your repository

  1. Write the brief. Name the module, direct callers, owner, approved versions, contract tests, out-of-scope code, and rollback instructions. Stop if the slice requires a wider dependency upgrade or changes public behavior.
  2. Establish the baseline. Have Codex read AGENTS.md, the brief, official migration guidance, locks, callers, and tests. Record the starting commit and installed versions. Explain or repair failing baseline checks before claiming parity.
  3. Prepare compatibility separately. If shared dependencies couple the module to other code, review that preparation first. Prove that the same fixtures pass against both the original and prepared baselines.
  4. Migrate one slice. Use the starter prompt on this page. Change the module and its direct adapter; preserve unrelated modules and name any compatibility code that remains.
  5. Run the same tests. Compare baseline and final HTTP/schema fixtures without changing expectations. Run affected integration, lint, and type checks, and save output tied to the final source and dependency state.
  6. Review the handoff. Inspect the diff, observed evidence, unresolved differences, remaining bridge, and rollback. Create a draft PR only when repository tools and permissions support it. Leave merging, deployment, and another migration slice to the reviewer.

Record what was verified

Use an evidence record for each criterion:

官方代码示例
Criterion: [behavior and test]
Environment: [setup reference; actual runtime and dependency versions]
Before: [commit/diff ID; command; exit code; observed result; evidence path]
After: [final commit/diff ID; command; exit code; observed result; evidence path]
Status: [pass / fail / blocked / not run]
Limits: [untested behavior, missing prerequisite, or required owner decision]

A successful import, lint check, or regenerated snapshot does not prove API parity. Record intentional differences separately, and rerun checks when the final source changes. When adapting the sample, include your application’s callers and services in the contract tests.