如需完整的文件索引,請參閱 llms.txt。在文件頁面的網址末尾加上 .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 文件,確保文件所述內容與公開 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 文件,確保文件所述內容與公開 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,瞭解範例的設定方式與對外契約。

    檢視可執行範例

    以下片段摘自下載檔案。請先解壓縮 ZIP 檔,再執行完整檔案。

    游標與排序的實作
    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 契約與迴歸測試
    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。若使用自己的服務,請補上實際使用的型別檢查、lint、迴歸測試與 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 則按字典序降冪排列。游標必須依此順序,從最後一筆已傳回的時間戳記與 ID 有序對之後接續讀取,不得再次包含該筆事件。

    預設每頁 25 筆,有效的筆數上限為 1 至 100 的十進位整數。重複指定筆數上限或游標參數均屬無效。只有在後面還有符合條件的事件時,才傳回非 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 則用來另外示範測試失敗的情況。

      若使用自己的服務,請執行既有的迴歸測試、型別檢查與 lint 檢查。新端點的專用測試檔案可能尚不存在,請將它列為待建立的測試。若既有檢查失敗或測試服務無法使用,請先排除問題,再判斷後續結果是否由這項功能造成。

    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 時傳回 1 筆,limit=100 時傳回 100 筆。

    無效的筆數上限

    驗證 0、101、-1、帶有小數的值,以及 many 之類的字串都會得到 HTTP 400 回應,且回應符合既有的驗證錯誤格式。

    空白頁與最後一頁

    驗證有權存取但沒有事件的專案會傳回 items: [] 和 next_cursor: null。使用 limit=2 時,驗證五筆事件的第三頁只有一筆且游標為 null,而四筆事件的第二頁有兩筆且游標為 null。即使最後一頁恰好填滿,也不應需要額外發出請求來取得空白頁。

    身分驗證

    驗證缺少工作階段或工作階段無效時,回應符合約定的 401 結構描述。即使請求帶有格式錯誤的游標或來自其他範圍的游標,也必須得到相同結果。游標驗證不得改變身分驗證的結果。

    租戶隔離

    以租戶 A 的身分通過驗證,然後請求租戶 B 的專案或不存在的專案。驗證兩者都會傳回相同且符合約定的通用 404 回應主體,且不含事件資料,即使請求帶有格式錯誤或範圍不符的游標也一樣。必須先檢查存取權,再驗證游標。

    游標的適用範圍

    對租戶 A 中有權存取的專案分別發出兩次請求:(1)使用租戶 A 另一個專案的有效簽署游標,(2)使用為租戶 B 簽發的有效簽署游標。

    驗證兩者都會傳回相同的 HTTP 400 invalid_cursor 回應主體,且不含事件資料或適用範圍的詳細資訊。請將這兩種情況與請求無權存取的專案分開測試,後者必須傳回 404。

    格式錯誤或遭竄改的游標

    針對有權存取的專案,驗證下列 Token 都會得到 HTTP 400 invalid_cursor 回應:輔助函式無法解碼的 Token、簽章遭修改的 Token,以及雖已簽署但缺少必要游標欄位或欄位型別錯誤的 Token。請使用獨立的測試用簽署資料。

    如果共用輔助函式支援版本或效期檢查,也應涵蓋版本不受支援或已過期的 Token。驗證回應符合約定的通用錯誤結構描述,且不含解碼後的內容、識別碼、原始錯誤或堆疊追蹤。

    既有行為

    範例會對既有的專案詳細資料路由發出已授權的請求、未授權的請求,以及針對無法存取之專案的請求。若使用自己的服務,請執行既有的迴歸測試套件、型別檢查與 lint 檢查。

    對外回應的結構描述

    依據約定的 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 或既有的貢獻者指南中。

    相關應用案例