如需查看完整的文档索引,请参阅 llms.txt。在文档页面的 URL 末尾加上 .md 即可查看该页面的 Markdown 版本。
主导航
主题
Codex

Codex 使用场景

根据议题创建经过测试的 pull request

将小功能的开发任务连同验收标准交给 Codex,再逐项审查验证证据。

难度 Intermediate
时间跨度 Long-running

向 Codex 提供范围明确的议题、准备好的云端环境和具体的检查要求。Codex 会交付可供审查的代码变更、测试和文档,并为每项验收标准提供验证证据。

最适合

  • 负责按议题要求实现 API 变更、且工作范围明确的初创公司工程师。
  • 需要对照验证证据审查代码实现的审查者。
  • 已有验收标准和可用测试环境的团队。

目录

    ← 所有使用场景

    根据议题创建经过测试的 pull request

    将小功能的开发任务连同验收标准交给 Codex,再逐项审查验证证据。

    向 Codex 提供范围明确的议题、准备好的云端环境和具体的检查要求。Codex 会交付可供审查的代码变更、测试和文档,并为每项验收标准提供验证证据。

    Intermediate
    Long-running
    准备云端环境

    向 Codex 提供范围明确的议题、准备好的云端环境和具体的检查要求。Codex 会交付可供审查的代码变更、测试和文档,并为每项验收标准提供验证证据。

    Intermediate
    Long-running

    最适合

    • 负责按议题要求实现 API 变更、且工作范围明确的初创公司工程师。
    • 需要对照验证证据审查代码实现的审查者。
    • 已有验收标准和可用测试环境的团队。

    起始提示词

    请使用我为此任务选定并已准备好的云端环境,在 [repository] 中以 [base branch and commit] 为起点,实现 [issue ID and title] 中的需求。 输入材料:[paste or attach the issue, acceptance criteria, relevant files, public success/error schemas, authorization and pagination contract, test fixtures, and approved validation commands]。 代码仓库指令:[AGENTS.md and any relevant nested instructions]。 工作范围:[files or component boundaries]。 排除项:[explicit exclusions]。 必做检查:[focused tests, relevant regression tests, type check, lint, and any required CI checks]。 输出:[create a draft PR in this repository if the available integration supports it and I authorize it here / return a diff and draft PR description]。 先阅读指令和相关代码。确认起始提交,并使用当前环境中可用的执行工具运行现有的基线检查。列出需要新增的测试文件,并标记为待创建。如果基线检查失败、缺少访问权限或某项必做检查无法运行,请在开始实现前说明具体障碍。 先简述计划,再以最小改动满足验收标准。沿用现有的授权、错误处理、分页和测试方式。添加能区分预期行为与原有行为的测试。对于这个分页示例,测试须覆盖时间戳相同的记录分处上一页末尾和下一页开头的情况。使用固定的测试数据,在限定范围内遍历并重放遍历过程。分别测试末页未满和末页恰好填满的情况。验证系统先检查授权,再验证游标。测试无效游标的情况,并检查成功响应和错误响应的模式。更新受影响的 API 文档,使其与实际实现的对外响应完全一致。 实现后,重新运行所有必做检查。针对每项验收标准,指出哪项测试或其他证据能够验证该标准。记录执行的命令、结果、测试时的提交或工作树状态,以及未运行的检查。区分原有的失败项和新出现的失败项。绝不能将未运行的检查标记为通过。 交付代码差异或已获授权的草稿 PR,并附上简明的变更摘要、逐项列出验收标准及对应证据的表格、剩余风险和审查者需要采取的操作。不得合并、部署、使用生产数据、更改权限、添加新依赖或扩大约定范围。如果接口约定与代码仓库的实际情况冲突,或实现需求必须更改模式,请暂停并等待决定。
    请使用我为此任务选定并已准备好的云端环境,在 [repository] 中以 [base branch and commit] 为起点,实现 [issue ID and title] 中的需求。 输入材料:[paste or attach the issue, acceptance criteria, relevant files, public success/error schemas, authorization and pagination contract, test fixtures, and approved validation commands]。 代码仓库指令:[AGENTS.md and any relevant nested instructions]。 工作范围:[files or component boundaries]。 排除项:[explicit exclusions]。 必做检查:[focused tests, relevant regression tests, type check, lint, and any required CI checks]。 输出:[create a draft PR in this repository if the available integration supports it and I authorize it here / return a diff and draft PR description]。 先阅读指令和相关代码。确认起始提交,并使用当前环境中可用的执行工具运行现有的基线检查。列出需要新增的测试文件,并标记为待创建。如果基线检查失败、缺少访问权限或某项必做检查无法运行,请在开始实现前说明具体障碍。 先简述计划,再以最小改动满足验收标准。沿用现有的授权、错误处理、分页和测试方式。添加能区分预期行为与原有行为的测试。对于这个分页示例,测试须覆盖时间戳相同的记录分处上一页末尾和下一页开头的情况。使用固定的测试数据,在限定范围内遍历并重放遍历过程。分别测试末页未满和末页恰好填满的情况。验证系统先检查授权,再验证游标。测试无效游标的情况,并检查成功响应和错误响应的模式。更新受影响的 API 文档,使其与实际实现的对外响应完全一致。 实现后,重新运行所有必做检查。针对每项验收标准,指出哪项测试或其他证据能够验证该标准。记录执行的命令、结果、测试时的提交或工作树状态,以及未运行的检查。区分原有的失败项和新出现的失败项。绝不能将未运行的检查标记为通过。 交付代码差异或已获授权的草稿 PR,并附上简明的变更摘要、逐项列出验收标准及对应证据的表格、剩余风险和审查者需要采取的操作。不得合并、部署、使用生产数据、更改权限、添加新依赖或扩大约定范围。如果接口约定与代码仓库的实际情况冲突,或实现需求必须更改模式,请暂停并等待决定。

    把一个范围小、要求明确的议题交给 Codex,让它交付一项可供队友审查的改动,包括实现代码、测试、文档,以及证明实现符合要求的验证结果。在同一个已准备好的云端环境中完成任务,确保编写代码和运行验证时使用相同的代码仓库配置。

    1. 在网页版或桌面应用中,选择工作位置 > 云端,然后选择一个已发布的环境。

    2. 如需新建环境,请选择创建环境,选择所需的 GitHub 代码仓库,然后让 Codex 准备运行时、依赖项和隔离的测试服务。

    3. 查看环境配置报告,解决检查发现的问题,然后在启动新任务前选择发布。

    如果依赖项或服务配置发生变化,请编辑可复用的环境,测试后选择重新发布,然后在新任务中验证改动。

    刷新代码仓库不会重新运行安装或启动命令,已有任务会保留各自的状态。

    请分别配置需要访问的网络目的地和测试凭据。允许连接某个目的地并不会授予服务访问权限。

    如果无法运行必需的检查,请先完成环境配置,再使用此工作流。

    适用场景

    选择一项有书面契约、完成条件明确的功能,例如新增 API 端点、添加验证规则,或为现有服务补充一项小功能。一个 pull request 应能涵盖整个议题,相关检查也应能在无需访问生产环境的情况下运行。

    本示例为项目的活动流添加分页。这个可运行的 TypeScript 示例包含身份验证、项目访问控制、带签名的游标,以及已有的项目详情路由。示例在内存中使用固定的测试记录,因此您无需连接数据库或外部服务即可检查分页契约。

    运行示例

    下载示例,解压后打开其中的 issue-to-tested-pr 文件夹。请使用 Node 22.6 或更高版本。示例使用标准库,无需安装软件包或提供 API 密钥。

    node --version
    node --experimental-strip-types api.ts
    node --experimental-strip-types test.ts --seeded
    node --experimental-strip-types test.ts
    node --experimental-strip-types reproduce.ts ./evidence

    node --experimental-strip-types api.ts 会启动本地 HTTP 服务器,请求第一页,打印该页事件的公开 ID,然后关闭服务器。

    使用 --seeded 运行测试时,程序会按设计以非零退出码结束,因为仅依据时间戳续页会跳过两个与第一页最后一个事件时间戳相同的事件。修正后,续页依据改为由时间戳和 ID 组成的元组,同一组测试即可通过。

    只有在预置缺陷版本测试失败且修正版本测试通过时,复现命令才会成功。

    修正后,使用 limit=2 遍历活动流会通过三次请求依次返回以下三页。

    [evt_105, evt_104]
    [evt_103, evt_102]
    [evt_101]

    前两页各有一个用于获取下一页的游标,最后一页返回 next_cursor: null。

    预置缺陷版本先返回 [evt_105, evt_104],随后返回 [evt_101],漏掉了 evt_103 和 evt_102。

    成功复现时,修正版本会通过全部 36 项测试,预置缺陷版本则会有三个断言失败,暴露出分页缺陷。

    要验证您的环境,请将文件放入选定的代码仓库,准备并发布一个使用受支持的 Node 运行时的环境,然后在新的云任务中运行上述命令并记录结果。

    reproduce.ts 会将 red.log、green.log、observed-http.json 和 run-manifest.json 保存到指定的证据目录。清单中列出了运行时、命令、退出码、预置缺陷、修正内容,以及源文件的 SHA-256 哈希值。

    清单不会记录会话 Token 或签名密钥。有关示例的配置方法和公开契约,请阅读 README.md 和 openapi.json。

    查看可运行的示例

    TypeScript 代码片段摘自 ZIP 压缩包。

    使用随附的数据库测试数据运行所选语言的完整文件。

    游标与排序的实现
    创建示例 API
    import { createFixtures } from "./fixtures.ts";
    type Fixtures = ReturnType<typeof createFixtures>;
    type EventKey = { created_at: string; id: string };
    
    export function createApi({
      sessions,
      projects,
      events,
      signingKey,
      seededBug = false,
    }: Fixtures & { seededBug?: boolean }) {
      return createServer((request, response) => {
        const send = (status: number, body: unknown) => {
          response.writeHead(status, { "content-type": "application/json" });
          response.end(JSON.stringify(body));
        };
        const fail = (code: string) => {
          const [status, message] = errors[code];
          send(status, { error: { code, message } });
        };
        // Authenticate, then authorize. Malformed parameters must not change these results.
        const authorization = request.headers.authorization ?? "";
        const bearer = /^Bearer ([A-Za-z0-9_-]+)$/.exec(authorization);
        const tenantId = bearer ? sessions.get(bearer[1]) : undefined;
        if (!tenantId) return fail("unauthenticated");
    
        const url = new URL(request.url ?? "/", "http://127.0.0.1");
        const route = /^\/v1\/projects\/([^/]+)(\/events)?$/.exec(url.pathname);
        let projectId;
        try {
          projectId = route ? decodeURIComponent(route[1]) : undefined;
        } catch {
          return fail("not_found");
        }
        const project = projectId ? projects.get(projectId) : undefined;
        if (
          request.method !== "GET" ||
          !route ||
          !project ||
          project.tenant_id !== tenantId
        ) {
          return fail("not_found");
        }
        // Existing project-detail behavior remains independent of pagination parameters.
        if (!route[2]) return send(200, { id: projectId, name: project.name });
    
        const rawLimit = url.searchParams.get("limit");
        const limit = rawLimit === null ? 25 : Number(rawLimit);
        if (
          url.searchParams.getAll("limit").length > 1 ||
          (rawLimit !== null && !/^\d+$/.test(rawLimit)) ||
          !Number.isInteger(limit) ||
          limit < 1 ||
          limit > 100
        ) {
          return fail("invalid_limit");
        }
        let cursor: EventKey | undefined;
        if (url.searchParams.has("cursor")) {
          try {
            if (url.searchParams.getAll("cursor").length !== 1)
              throw new Error("Invalid cursor");
            cursor = decodeCursor(
              url.searchParams.get("cursor"),
              tenantId,
              projectId,
              signingKey
            );
          } catch {
            return fail("invalid_cursor");
          }
        }
    
        const matching = events
          .filter(
            (event) =>
              event.tenant_id === tenantId && event.project_id === projectId
          )
          .sort(compareEvents)
          .filter((event) => {
            if (!cursor) return true;
            // Deliberate baseline defect: timestamp-only continuation loses tied rows.
            if (seededBug)
              return (
                timestampValue(event.created_at) < timestampValue(cursor.created_at)
              );
            return compareEvents(event, cursor) > 0;
          });
        const selected = matching.slice(0, limit);
        const items = selected.map(({ id, created_at, type, summary }) => ({
          id,
          created_at,
          type,
          summary,
        }));
        const nextCursor =
          matching.length > limit
            ? encodeCursor(
                selected[selected.length - 1],
                tenantId,
                projectId,
                signingKey
              )
            : null;
        return send(200, { items, next_cursor: nextCursor });
      });
    }
    
    export async function startApi(
      fixtures: Fixtures,
      options: { seededBug?: boolean } = {}
    ) {
      const server = createApi({ ...fixtures, ...options });
      await new Promise((resolve, reject) => {
        server.once("error", reject);
        server.listen(0, "127.0.0.1", () => resolve(undefined));
      });
      const address = server.address();
      if (!address || typeof address === "string")
        throw new Error("No listening address");
      return {
        baseUrl: `http://127.0.0.1:${address.port}`,
        close: () =>
          new Promise((resolve, reject) =>
            server.close((error) => (error ? reject(error) : resolve(undefined)))
          ),
      };
    }
    预置记录与项目访问测试数据
    创建测试数据
    export function createFixtures() {
      const tokenA = randomBytes(24).toString("base64url");
      const tokenB = randomBytes(24).toString("base64url");
      const sessions = new Map([
        [tokenA, "tenant_a"],
        [tokenB, "tenant_b"],
      ]);
      const projects = new Map([
        ["feed", { tenant_id: "tenant_a", name: "Activity feed" }],
        ["empty", { tenant_id: "tenant_a", name: "Empty feed" }],
        ["exact", { tenant_id: "tenant_a", name: "Four events" }],
        ["large", { tenant_id: "tenant_a", name: "Large feed" }],
        ["precision", { tenant_id: "tenant_a", name: "Precise timestamps" }],
        ["other", { tenant_id: "tenant_a", name: "Another project" }],
        ["private", { tenant_id: "tenant_b", name: "Private project" }],
      ]);
      const event = (
        id: string,
        created_at: string,
        project_id: string,
        tenant_id = "tenant_a"
      ) => ({
        id,
        created_at,
        project_id,
        tenant_id,
        type: "deployment",
        summary: `Synthetic event ${id}`,
        internal_note: "This field must never enter the HTTP response.",
        raw_payload: { synthetic: true },
      });
      const feed = [
        event("evt_105", "2026-01-15T12:00:03.123456Z", "feed"),
        event("evt_104", "2026-01-15T12:00:02.123456Z", "feed"),
        event("evt_103", "2026-01-15T12:00:02.123456Z", "feed"),
        event("evt_102", "2026-01-15T12:00:02.123456Z", "feed"),
        event("evt_101", "2026-01-15T12:00:01.123456Z", "feed"),
      ];
      const events = [
        ...feed,
        ...feed.slice(0, 4).map((item) => ({ ...item, project_id: "exact" })),
        ...Array.from({ length: 105 }, (_, index) =>
          event(
            `large_${String(index).padStart(3, "0")}`,
            new Date(Date.UTC(2026, 0, 15, 12, 0, index))
              .toISOString()
              .replace(".000Z", ".123456Z"),
            "large"
          )
        ),
        // Reverse ID order makes timestamp precision observable in the tests.
        event("precise_a", "2026-01-15T12:00:00.123999Z", "precision"),
        event("precise_z", "2026-01-15T12:00:00.123001Z", "precision"),
        event("other_1", "2026-01-15T12:00:00.123456Z", "other"),
        event("other_2", "2026-01-15T11:59:59.123456Z", "other"),
        event("private_1", "2026-01-15T12:00:00.123456Z", "private", "tenant_b"),
        event("private_2", "2026-01-15T11:59:59.123456Z", "private", "tenant_b"),
      ];
      return {
        sessions,
        projects,
        events,
        signingKey: randomBytes(32),
        tokenA,
        tokenB,
      };
    }
    HTTP 契约与回归测试
    测试示例 API
    test("five-event traversal crosses a timestamp tie and replays the same continuation", async () => {
      const expected = ["evt_105", "evt_104", "evt_103", "evt_102", "evt_101"];
      const pages = await traverse("feed", 2, expected);
      assert.deepEqual(pages.map(ids), [
        ["evt_105", "evt_104"],
        ["evt_103", "evt_102"],
        ["evt_101"],
      ]);
      assert.equal(pages.length, 3);
      assert.ok(pages[0].next_cursor);
      assert.ok(pages[1].next_cursor);
      assert.equal(pages[2].next_cursor, null);
      const replay = await request("feed", {
        limit: "2",
        cursor: pages[0].next_cursor,
      });
      assert.deepEqual(replay.body.items, pages[1].items);
      const next = await request("feed", {
        limit: "2",
        cursor: replay.body.next_cursor,
      });
      assert.deepEqual(next.body.items, pages[2].items);
      assert.equal(next.body.next_cursor, null);
      console.log(
        JSON.stringify({
          fixture: "five-event-tie",
          pages: pages.map(ids),
          requests: pages.length,
          replay: ids(replay.body),
        })
      );
    });
    
    test("the same tie group traverses correctly with limit three", async () => {
      const pages = await traverse("feed", 3, [
        "evt_105",
        "evt_104",
        "evt_103",
        "evt_102",
        "evt_101",
      ]);
      assert.deepEqual(pages.map(ids), [
        ["evt_105", "evt_104", "evt_103"],
        ["evt_102", "evt_101"],
      ]);
    });
    
    test("timestamp ordering and continuation preserve submillisecond precision", async () => {
      const pages = await traverse("precision", 1, ["precise_a", "precise_z"]);
      assert.equal(pages[0].items[0].created_at, "2026-01-15T12:00:00.123999Z");
      assert.equal(pages[1].items[0].created_at, "2026-01-15T12:00:00.123001Z");
    });
    
    test("omitted, minimum, and maximum limits return 25, 1, and 100 of 105 events", async () => {
      for (const [parameters, expected] of [
        [{}, 25],
        [{ limit: "1" }, 1],
        [{ limit: "100" }, 100],
      ] as [Record<string, string>, number][]) {
        const result = await request("large", parameters);
        assert.equal(result.status, 200);
        assert.equal(result.body.items.length, expected);
        assert.ok(result.body.next_cursor);
      }
      const pages = await traverse(
        "large",
        100,
        Array.from(
          { length: 105 },
          (_, index) => `large_${String(104 - index).padStart(3, "0")}`
        )
      );
      assert.deepEqual(
        pages.map((page) => page.items.length),
        [100, 5]
      );
    });
    
    test("invalid and repeated limits return the documented generic error", async (context) => {
      for (const limit of [
        "0",
        "101",
        "-1",
        "1.5",
        "many",
        "",
        "1e2",
        "Infinity",
      ]) {
        await context.test(`limit ${JSON.stringify(limit)}`, async () => {
          const result = await request("feed", { limit });
          assert.equal(result.status, 400);
          assert.deepEqual(
            result.body,
            expectedError(
              "invalid_limit",
              "Limit must be an integer from 1 through 100."
            )
          );
        });
      }
      const repeated = await request("feed", [
        ["limit", "1"],
        ["limit", "2"],
      ]);
      assert.equal(repeated.status, 400);
    });
    
    test("empty, partial, and exactly full final pages have no continuation", async () => {
      assert.deepEqual((await request("empty")).body, {
        items: [],
        next_cursor: null,
      });
      const partial = await traverse("feed", 2, [
        "evt_105",
        "evt_104",
        "evt_103",
        "evt_102",
        "evt_101",
      ]);
      assert.equal(partial.at(-1).items.length, 1);
      const exact = await traverse("exact", 2, [
        "evt_105",
        "evt_104",
        "evt_103",
        "evt_102",
      ]);
      assert.deepEqual(
        exact.map((page) => page.items.length),
        [2, 2]
      );
      assert.equal(exact[1].next_cursor, null);
    });
    
    test("authentication precedes malformed and wrong-scope cursor or limit validation", async () => {
      const privateCursor = (
        await request("private", { limit: "1" }, fixtures.tokenB)
      ).body.next_cursor;
      for (const token of [null, "invalid_session"]) {
        for (const parameters of [
          { cursor: "broken" },
          { cursor: privateCursor },
          { limit: "0", cursor: "broken" },
        ] as Record<string, string>[]) {
          const result = await request("feed", parameters, token);
          assert.equal(result.status, 401);
          assert.deepEqual(result.body, unauthenticated);
        }
      }
    });
    
    test("inaccessible and nonexistent projects return identical 404 before cursor validation", async () => {
      const ownCursor = (await request("feed", { limit: "1" })).body.next_cursor;
      for (const project of ["private", "missing"]) {
        for (const parameters of [
          {},
          { cursor: "broken" },
          { cursor: ownCursor },
          { limit: "0", cursor: "broken" },
        ] as Record<string, string>[]) {
          const result = await request(project, parameters);
          assert.equal(result.status, 404);
          assert.deepEqual(result.body, notFound);
        }
      }
    });
    
    test("a valid cursor from another project in the same tenant is invalid on an authorized feed", async () => {
      const cursor = (await request("other", { limit: "1" })).body.next_cursor;
      assert.ok(cursor);
      const result = await request("feed", { cursor });
      assert.equal(result.status, 400);
      assert.deepEqual(result.body, invalidCursor);
    });
    
    test("a valid cursor from another tenant is invalid on an authorized feed", async () => {
      const cursor = (await request("private", { limit: "1" }, fixtures.tokenB))
        .body.next_cursor;
      assert.ok(cursor);
      const result = await request("feed", { cursor });
      assert.equal(result.status, 400);
      assert.deepEqual(result.body, invalidCursor);
    });
    
    test("undecodable, empty, tampered, and repeated cursor tokens return the same closed error", async () => {
      const cursor = (await request("feed", { limit: "1" })).body.next_cursor;
      const [payload, signature] = cursor.split(".");
      const tampered = `${payload}.${signature[0] === "A" ? "B" : "A"}${signature.slice(1)}`;
      for (const token of [
        "broken",
        "",
        "%%%.___",
        "a.b.c",
        "x".repeat(2049),
        tampered,
      ]) {
        const result = await request("feed", { cursor: token });
        assert.equal(result.status, 400);
        assert.deepEqual(result.body, invalidCursor);
      }
      const result = await request("feed", [
        ["cursor", cursor],
        ["cursor", cursor],
      ]);
      assert.equal(result.status, 400);
      assert.deepEqual(result.body, invalidCursor);
    });
    
    test("signed structurally invalid payloads and unsupported versions are rejected", async (context) => {
      const valid = {
        version: 1,
        tenant_id: "tenant_a",
        project_id: "feed",
        created_at: "2026-01-15T12:00:02.123456Z",
        id: "evt_104",
      };
      const missing: Partial<typeof valid> = { ...valid };
      delete missing.id;
      const cases: [string, unknown][] = [
        ["missing ID", missing],
        ["number ID", { ...valid, id: 104 }],
        ["empty ID", { ...valid, id: "" }],
        ["number timestamp", { ...valid, created_at: 0 }],
        ["invalid date", { ...valid, created_at: "2026-02-30T12:00:00Z" }],
        ["unsupported version", { ...valid, version: 2 }],
        ["extra field", { ...valid, extra: true }],
        ["wrong tenant type", { ...valid, tenant_id: 1 }],
        ["wrong project type", { ...valid, project_id: null }],
        ["null payload", null],
        ["array payload", []],
        ["invalid JSON", "not-json"],
      ];
      for (const [name, payload] of cases) {
        await context.test(name, async () => {
          const result = await request("feed", { cursor: signFixture(payload) });
          assert.equal(result.status, 400);
          assert.deepEqual(result.body, invalidCursor);
        });
      }
    });
    
    test("every serialized event omits stored tenant, project, and raw payload fields", async () => {
      const result = await request("feed", { limit: "100" });
      assert.equal(result.status, 200);
      for (const item of result.body.items) {
        assert.deepEqual(Object.keys(item).sort(), [
          "created_at",
          "id",
          "summary",
          "type",
        ]);
      }
      assert.ok(
        fixtures.events.some((event) => event.internal_note && event.raw_payload)
      );
    });
    
    test("the schema oracle rejects extra, missing, incorrectly typed, and malformed public fields", () => {
      const schema = specification.components.schemas.EventPage;
      const page = {
        items: [
          {
            id: "evt_1",
            created_at: "2026-01-15T12:00:00.123456Z",
            type: "deployment",
            summary: "Synthetic",
          },
        ],
        next_cursor: null,
      };
      assert.ok(conforms(page, schema));
      assert.equal(conforms({ ...page, tenant_id: "tenant_a" }, schema), false);
      assert.equal(
        conforms(
          { ...page, items: [{ ...page.items[0], raw_payload: {} }] },
          schema
        ),
        false
      );
      assert.equal(conforms({ items: page.items }, schema), false);
      assert.equal(conforms({ ...page, next_cursor: "" }, schema), false);
      assert.equal(
        conforms({ ...page, items: [{ ...page.items[0], id: 1 }] }, schema),
        false
      );
      assert.equal(
        conforms(
          { ...page, items: [{ ...page.items[0], created_at: "yesterday" }] },
          schema
        ),
        false
      );
      const errorSchema = specification.components.schemas.InvalidCursor;
      assert.equal(
        conforms(
          { error: { ...invalidCursor.error, stack: "internal" } },
          errorSchema
        ),
        false
      );
      assert.equal(
        conforms(
          { error: { ...invalidCursor.error, message: "tenant_a" } },
          errorSchema
        ),
        false
      );
    });
    
    test("the existing project-detail route preserves access and ignores pagination parameters", async () => {
      const own = await request(
        "feed",
        { cursor: "broken", limit: "0" },
        fixtures.tokenA,
        true
      );
      assert.equal(own.status, 200);
      assert.deepEqual(own.body, { id: "feed", name: "Activity feed" });
      const inaccessible = await request("private", {}, fixtures.tokenA, true);
      assert.equal(inaccessible.status, 404);
      assert.deepEqual(inaccessible.body, notFound);
      const unauthenticatedResult = await request("feed", {}, null, true);
      assert.equal(unauthenticatedResult.status, 401);
      assert.deepEqual(unauthenticatedResult.body, unauthenticated);
    });
    
    test("OpenAPI declares operation, limit boundaries, signed cursor, and response statuses", () => {
      assert.equal(specification.openapi, "3.1.0");
      const operation = specification.paths["/v1/projects/{project_id}/events"].get;
      assert.equal(operation.operationId, "listProjectEvents");
      const limit = operation.parameters.find(
        (parameter: { name: string }) => parameter.name === "limit"
      ).schema;
      assert.deepEqual(limit, {
        type: "integer",
        minimum: 1,
        maximum: 100,
        default: 25,
      });
      assert.deepEqual(Object.keys(operation.responses).sort(), [
        "200",
        "400",
        "401",
        "404",
      ]);
      assert.equal(
        specification.components.securitySchemes.session.scheme,
        "bearer"
      );
    });
    采集验证证据
    复现问题
    mkdirSync(output, { recursive: true });
    const states = [];
    for (const [name, arguments_] of [
      ["red", ["--seeded"]],
      ["green", []],
    ]) {
      const result = spawnSync(
        process.execPath,
        [
          "--experimental-strip-types",
          resolve(directory, "test.ts"),
          ...arguments_,
        ],
        {
          cwd: directory,
          encoding: "utf8",
          timeout: 30_000,
        }
      );
      writeFileSync(
        resolve(output, `${name}.log`),
        `${result.stdout ?? ""}${result.stderr ?? ""}`
      );
      states.push({
        name,
        command: `node --experimental-strip-types test.ts${arguments_.length ? " --seeded" : ""}`,
        exit_code: result.status,
        signal: result.signal,
        error: result.error?.message ?? null,
      });
    }
    const sources = Object.fromEntries(
      readdirSync(directory, { withFileTypes: true })
        .filter((entry) => entry.isFile())
        .map((entry) => [
          entry.name,
          createHash("sha256")
            .update(readFileSync(resolve(directory, entry.name)))
            .digest("hex"),
        ])
    );
    const observed = { red: await observe(true), green: await observe(false) };
    writeJson("observed-http.json", observed);
    writeJson("run-manifest.json", {
      execution: "Synthetic loopback HTTP fixture; no external service",
      recorded_at: new Date().toISOString(),
      node: process.version,
      minimum_node: "22.6.0",
      dependencies: "Node standard library only; no install step",
      baseline:
        "Deliberately seeded timestamp-only continuation; not a historical customer defect",
      correction:
        "Descending timestamp-and-ID tuple continuation using full fractional precision",
      source_sha256: sources,
      states,
    });
    if (
      states[0].exit_code === null ||
      states[0].exit_code === 0 ||
      states[1].exit_code !== 0
    ) {
      throw new Error(
        "Expected the unchanged tests to fail on the seeded baseline and pass on the corrected implementation. Inspect red.log and green.log."
      );
    }
    console.log(
      JSON.stringify(
        {
          execution: "synthetic-loopback-http",
          red_exit: states[0].exit_code,
          green_exit: states[1].exit_code,
          green_pages: observed.green.pages.map((page) =>
            page.body.items.map((item: { id: string }) => item.id)
          ),
          evidence_directory: output,
        },
        null,
        2
      )
    );

    准备任务材料

    只有在 Codex 能读取议题内容时,议题链接才有用。如果 Codex 无法访问来源,请粘贴相关内容或将其作为附件提供。请随起始提示词提供以下信息。

    输入 示例议题
    议题与预期结果 API-142:添加 GET /v1/projects/{project_id}/events,让客户可以分页浏览活动流。
    代码仓库与基准版本 将示例文件夹放入您选择的代码仓库,然后记录为任务选定的分支和确切提交。
    相关代码 示例中的 api.ts、fixtures.ts、test.ts 和 openapi.json,以及您代码仓库中的 AGENTS.md。
    现有实现约定 先验证身份并检查项目访问权限,再验证分页参数。使用带签名的游标和文档规定的公开错误响应结构。将议题用于自己的代码仓库时,请沿用仓库现有的辅助函数。
    测试配置 为两个租户准备固定的内存测试项目,其中租户 A 有六个项目。测试数据还涵盖跨页的同时间戳事件、带小数秒的时间戳、空末页和恰好填满的末页,以及用于检查条数限制的 105 个事件。
    验证 node --experimental-strip-types test.ts --seeded(预期失败)、node --experimental-strip-types test.ts(修正版本)和 node --experimental-strip-types reproduce.ts ./evidence。如果使用您自己的服务,请补充该服务实际使用的类型检查、代码静态检查、回归测试和 CI 命令。
    范围 实现端点,编写针对性测试,并更新该端点的 OpenAPI 文档。范围不包括新增依赖项、迁移数据库、开发前端、部署或重新设计身份验证与授权机制。
    交付物 如果可用的代码仓库集成支持创建草稿 PR,且您已授权创建,请交付草稿 PR。否则交付代码差异和 PR 描述草稿。

    运行示例前,请准备 Node 22.6 或更高版本。测试会自行创建测试会话和游标签名密钥,并将临时 HTTP 服务器绑定到回环接口。如果使用您自己的服务,还需准备该服务的依赖项、测试配置和隔离服务。分派此议题前,请确认服务的游标辅助函数可以将游标绑定到已验证身份的租户和所请求的项目。

    定义 API 契约

    开始实现前,请确认以下示例契约适用于您的代码仓库。成功响应的状态码为 HTTP 200,响应体的结构严格为 { items, next_cursor }。

    每一项恰好包含四个必填的公开字段,分别是 id(非空字符串)、created_at(采用 RFC 3339 格式的 UTC 时间戳字符串)、type(非空字符串)和 summary(字符串)。items 是由这些对象组成的数组。next_cursor 是一个不透明的非空字符串或 null。

    响应字段不包括内部租户或项目键、数据库元数据、原始事件载荷或凭据。在 OpenAPI 中说明响应字段的类型、哪些字段必填、是否允许 null,以及各对象仅允许包含哪些字段。对照该模式验证序列化后的 HTTP 响应体。

    事件按 created_at DESC, id DESC 排序,保留时间戳的小数秒精度,ID 按字典序降序排列。续页时,游标按这一顺序从最后一个已返回元组之后的位置开始。

    默认每页 25 条,有效的条数限制为 1 到 100 之间的十进制整数,包含两端。重复传入 limit 或 cursor 参数均无效。仅当还有其他符合条件的事件时,才返回非 null 的游标。

    无论最后一页未填满还是恰好填满,都返回 next_cursor: null。对于有权访问但没有事件的项目,返回 items: [] 和 next_cursor: null。

    示例为每个游标签名,并将其绑定到已验证身份的租户和所请求的项目。请先验证身份并确认对所请求项目的访问权限,再验证条数限制或游标,以免参数错误泄露其他租户的项目是否存在。

    会话缺失或无效时返回 401。项目不可访问或不存在时,均返回相同的通用 404 响应。确认访问权限后,先检查条数限制,再检查游标。

    如果游标格式有误、遭到篡改、结构无效,或与租户或项目不匹配,则返回 HTTP 400,错误代码为 invalid_cursor。即使游标对同一租户的另一个项目或对另一个租户有效,将它用于当前有权访问的项目时也属于无效游标。

    对于无权访问的项目,提供游标不得改变授权结果。示例中的版本 1 游标不会过期。使用不支持的版本时,游标无效。

    示例中每个错误响应体的结构都严格为 { error: { code, message } },其中两个字段均为必填字符串,且不允许有额外字段。

    使用以下通用错误响应。

    • 400 invalid_cursor / Invalid cursor.
    • 400 invalid_limit / Limit must be an integer from 1 through 100.
    • 401 unauthenticated / Authentication required.
    • 404 not_found / Project not found.

    任何错误响应体都不得包含解码后的游标内容、租户或项目标识符、原始错误或堆栈跟踪。如果实际代码仓库规定了不同的错误响应结构或代码,请以其已批准的约定为准,并在修改共享辅助函数前解决契约差异。

    遍历和重放断言使用固定的测试数据,期间没有并发写入。使用游标逐页请求时,应按约定顺序返回每个事件且只返回一次。对于非空活动流,遍历最多需要 ceil(event_count / limit) 次请求。对于空活动流,一次请求即可结束。

    只要测试数据保持不变,使用相同的请求参数重放有效游标就应返回相同的条目和续页位置。生成的签名 Token 无需逐字节相同。

    此契约不保证游标只能使用一次,也不保证按快照分页或在活动流发生变化后仍返回相同结果。请记录代码仓库现有的活动流一致性策略。如果尚无此策略,而议题又要求按快照分页,请暂停实施,等待产品决策。

    使用步骤

    1. 选择议题并准备环境。 确认上述契约适用于实际代码仓库。选择准备好的云端环境和预期的基准提交。在任务中直接提供议题材料。启动此工作流无需由议题跟踪系统自动触发。

    2. 运行起始提示词。 将提示词中方括号内的输入替换为您的代码仓库、议题材料、范围限制和检查项。选择让 Codex 返回代码差异,还是在获得授权后创建草稿 PR。本页的起始提示词包含完整的交付说明。

    3. 建立基线。 Codex 应先阅读代码仓库说明并运行已批准的基线检查,再编辑代码。

      对于示例,请运行 node --experimental-strip-types test.ts。--seeded 用于单独演示预置缺陷引发的测试失败。

      对于您自己的服务,请运行现有的回归测试、类型检查和代码静态检查。新端点的专项测试文件可能尚不存在,请将其记录为待创建的测试。如果现有检查失败或测试服务不可用,请先解决这些问题,再判断后续结果是否由新功能引起。

    4. 实现并验证契约。 让 Codex 使用现有的访问控制和游标辅助函数,实现端点,添加下列验收测试,并更新端点的 API 文档。在可行的情况下,新测试应在原始代码上失败,并在改动后通过。将这些结果与最终验证记录一起保存。在可下载的示例中,--seeded 会启用一个特意预置的缺陷以供对照。请将这种对照与您代码仓库中的基线检查失败区分开来。

    5. 审查改动及其验证证据。 结合代码差异、验收检查、检查输出和剩余风险进行审查。如果 Codex 在获得授权后创建了草稿 PR,请确认其基准版本和待合并版本正确。如果 PR 工具不可用,请使用返回的代码差异和描述,按常规流程准备 PR。在草稿 PR 中列出所有尚未解决的检查项,在这些问题解决前不要将其标记为可合并。

    6. 处理审查反馈并按常规流程合并。 在同一任务中将需要处理的具体意见交给 Codex,然后重新运行受影响的检查。合并前,由审查者确认必需的 CI 检查已通过并批准最终提交。

    必需的验收测试

    以下测试将议题限定在可分派的范围内,并为审查提供具体标准。您可以根据测试运行器调整测试名称,但应保留每项测试所验证的行为。

    稳定遍历

    预置五个固定事件。其中 evt_105 的时间戳最新,evt_104、evt_103 和 evt_102 具有相同的中间时间戳,evt_101 的时间戳最早。

    使用 limit=2 时,各页必须依次为 [evt_105, evt_104]、[evt_103, evt_102]、[evt_101]。具有相同时间戳的这组事件必须分布在第一页和第二页。

    断言事件顺序完全正确,ID 无重复或遗漏,前两页的游标均非 null,第三页的游标为 null。如果遍历超过三次请求,则测试失败。

    保持测试数据不变,使用相同的条数限制重放第一页返回的续页游标,断言返回的第二页条目和续页位置均与之前相同。

    每页条数的默认值和边界值

    预置超过 100 个事件。断言未提供 limit 参数时返回 25 条,使用 limit=1 时返回一条,使用 limit=100 时返回 100 条。

    无效的条数限制

    断言传入 0、101、-1、小数或 many 这样的字符串时均返回 HTTP 400,并沿用现有的验证错误响应结构。

    空页与末页

    断言有权访问但没有事件的项目返回 items: [] 和 next_cursor: null。使用 limit=2 时,断言五个事件会产生仅含一条记录的第三页,四个事件会产生包含两条记录的第二页,两种情况下末页的游标均为 null。末页恰好填满时,无需再发起一次请求来获取空页。

    身份验证

    断言会话缺失或无效时,响应状态码为 401,响应体符合约定的模式。即使请求携带格式错误的游标或来自其他作用域的游标,也应如此。游标验证不得覆盖身份验证结果。

    租户隔离

    以租户 A 的身份通过验证后,请求租户 B 的项目或一个不存在的项目。断言两种情况均返回约定的同一通用 404 响应体,且不包含事件数据,即使请求携带格式错误或不匹配的游标也应如此。必须先检查访问权限,再验证游标。

    游标作用域

    请求租户 A 中有权访问的项目,分别使用(1)来自租户 A 另一个项目的有效签名游标,以及(2)为租户 B 签发的有效签名游标。

    断言两种情况均返回相同的 HTTP 400 invalid_cursor 响应体,且不包含事件数据或作用域详情。请将这两种情况与请求无权访问的项目分开测试,后者必须返回 404。

    格式错误或遭到篡改的游标

    对于有权访问的项目,断言以下三类 Token 均导致 HTTP 400 invalid_cursor:辅助函数无法解码的 Token、签名被修改的 Token,以及已签名但缺少必需游标字段或字段类型错误的 Token。请使用专为测试准备的隔离签名数据。

    如果共享辅助函数支持版本控制或 Token 过期,请覆盖相应的不受支持版本或已过期 Token。断言响应符合约定的通用错误模式,且不包含解码后的内容、标识符、原始错误或堆栈跟踪。

    现有行为

    示例使用已获授权的请求、未经授权的请求和针对无权访问项目的请求,检查现有的项目详情路由。在您自己的服务中,请运行既有的回归测试套件、类型检查和代码静态检查。

    公开响应模式

    对照约定的 OpenAPI 模式验证实际的 HTTP 200、400、401 和 404 响应体。断言必需的键均存在、条目字段类型和时间戳格式正确、游标是否允许 null 与约定一致,且任何层级的对象都没有额外属性。

    在存储的事件中预置内部字段,验证序列化后的条目不包含这些字段。同时验证每个错误响应仅包含已批准的通用错误代码和消息。

    文档

    核实 OpenAPI 操作及其示例与实现一致,包括参数、成功和错误响应的确切模式、授权检查的优先顺序、排序、末页规则,以及固定测试数据下重放和一致性保证的适用范围。如果代码仓库提供 API 规范验证,请运行该验证。

    交付结果示例

    共享验证记录

    请按以下格式为每项验收标准记录证据,并根据实际观察到的输出填写。如果新测试在基线版本中尚不存在,应将“尚无此测试”与“现有检查失败”区分开来。

    验收标准与对应测试:[specific behavior and test location]
    环境:[published setup reference; runtime, database and dependency versions]
    改动前:[revision + test-only diff ID; command; exit code; observed assertion; log path]
    改动后:[final revision or base + diff ID; command; exit code; observed assertion; log path]
    状态:[pass / fail / blocked / not run]
    验证局限与审查者待办事项:[untested behavior, blocker, or decision required]

    将失败和通过的测试记录分别关联到实际受测的代码状态,包括为在原始版本上运行测试而单独添加的测试改动。交付时附上日志、响应测试数据和最终差异。仅列出文件名和测试名无法证明测试确实运行过。受测版本发生变化时,请更新证据。受阻或尚未运行的检查不得计为通过。

    PR 描述应让审查者能从每项结论找到对应的证据。请使用以下交付模板,并用实际观察到的结果替换每个方括号字段。

    标题:为项目事件添加游标分页
    议题:API-142
    基准版本:[branch and commit]
    受测代码状态:[head commit, or base commit plus attached diff identifier]
    
    改动内容
    - 使用现有的项目访问控制辅助函数添加项目事件端点。
    - 复用作用域限定于租户和项目的签名游标。
    - 添加契约测试并更新对应的 OpenAPI 操作定义。
    
    验收证据
    - [One row per criterion above: test, observed result, and log reference.]
    
    验证结果
    - 改动前:[command, result, and log reference for each baseline check]。
    - 针对原始代码运行新测试:[result, or not run with reason]。
    - 改动后:[command, result, and log reference for each required check]。
    - CI:[check links and actual states, or not available]。
    - 剩余检查:[specific checks and blockers, or none with supporting evidence]。
    
    审查重点
    - [Highest-risk behavior and unresolved criteria.]
    
    剩余风险与回滚方式
    - [Observed limitations; distinguish them from untested assumptions.]
    - [How this change can be reverted and whether any callers depend on it.]

    根据审查意见继续修改

    针对审查发现的具体问题,给出明确的后续提示词。例如:

    请在当前改动中处理这条审查意见:
    “使用 limit=3 重新遍历这五个事件。断言第一页返回 [evt_105, evt_104, evt_103],
    第二页返回 [evt_102, evt_101],且第二页的续页游标为 null。”
    
    请添加这项回归测试。只有当该测试暴露出故障时,才修改实现代码。
    重新运行该端点的专项测试,以及受此次改动影响的其他必需检查。
    在验证记录表中更新受测代码状态和实际结果。
    保持原有范围。不得合并,也不得部署。

    如果 Codex 无法直接访问审查意见,请提供意见原文。审查者应核实意见指出的行为问题是否已经解决。

    何时停止

    • 基线检查失败或无法运行。 返回出问题的检查项和环境配置详情。请先修复环境,或就基线达成一致并记录下来,再继续。
    • 契约与现有行为冲突。 指出冲突、受影响的调用方,以及解决冲突所需的最小决策。不得擅自更改契约。
    • 改动需要迁移、新增依赖项或重新设计身份验证与授权机制。 说明原因,在扩大范围前先拆分议题或重新界定范围。
    • 实现后测试仍然失败。 报告失败用例,此时改动尚不具备合并条件。不得为了通过检查而删除断言或放宽授权限制。
    • 代码仓库的写入集成不可用。 返回代码差异、PR 描述草稿和验证证据。队友可以接手完成代码仓库中的交付操作。

    复用工作流

    审查者接受首次交付结果后,将议题材料和验收清单保存到团队的议题模板中。将长期适用的代码仓库说明,例如测试命令和 API 契约的存放位置,记录在 AGENTS.md 或现有的贡献指南中。

    相关使用场景