mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-31 22:24:16 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - PR CI selects affected suites and test files to reduce feedback time. > - A selected test inherited the parent selection when it launched an independent runner fixture. > - Ordinary source filenames containing config or setup also forced broad coverage. > - AWS runner access must depend on current CI CODEOWNERS, not only a stored numeric roster. > - This pull request fixes both selection problems and verifies owners before AWS allocation. > - Contributors retain GitHub-hosted CI. Authorized maintainers retain AWS test and final verification jobs. ## Linked Issues or Issue Description Refs #18362 and #18348. The selected server run for #18369 failed in `vitest-chat-shards.test.ts` because its temporary fixture inherited `PAPERCLIP_CI_TEST_SELECTION` and attempted `git rev-parse HEAD` outside a Git repository. #18366 could not use graph selection because `session-config-metadata.test.ts` matched the broad filename rule. The AWS setting was already enabled. The reviewed outsider PRs correctly used hosted runners; a maintainer PR used AWS, including final verification. This change strengthens that boundary rather than enabling AWS for outsiders. ## What Changed - Remove selection settings from Vitest child environments after the wrapper validates the selected shard. - Match conventional Vite/Vitest configuration filenames rather than any occurrence of config or setup. Keep graph tracking for actual setup and configuration dependencies. - Bind rerun actor lookup to the exact run attempt. Require the author, event sender and rerun actor to be current CI CODEOWNERS and members of the existing numeric allowlist. Read the resolver and CODEOWNERS from one protected master revision. - Run metadata authorization on GitHub-hosted capacity before any AWS allocation. Keep authorized test and final verification placement on the AWS fleet. - Add a real selected-server regression that launches nested chat fixtures, negative authorization cases, and qualification for a real config-named test. - Update the developer and profiling guides. - Retire eight legacy PR workflow SHA authorizations and one deleted qualification-branch reference from the live `paperclip-public-pr` runner group. The remaining three references are the trusted PR workflow and the existing full-stack/protocol evaluation workflows on master. No active PR run referenced the retired versions. ## Verification - Selection regression tests: 13 passed, including the real nested chat runner. - Routing, planner and profiling tests: 100 passed, including 69 routing cases. - `actionlint` passed for both changed workflows. `git diff --check` passed. - Confirmed protected master still requires CODEOWNER review. A live lookup found four CI owners, with three of six numeric roster entries eligible and three denied by the new owner check. - `pnpm -r typecheck` and `pnpm build` passed. The full local Vitest suite was stopped after repeated embedded PostgreSQL initialization failures; it did not pass. On final revision `0b40ae15b7996603e405edd4157a5c337e0405c7`, both Linux qualification jobs and all required CI gates passed. The main PR workflow completed with 48 successful jobs and one intentional skip, including final verification. [CI run](https://github.com/paperclipai/paperclip/actions/runs/41126881716). Greptile reviewed the final revision at 5/5 with no inline findings. - Shard and workflow contracts: 44 passed. CI first caught an outdated assertion that required the routing job to use AWS; it now requires hosted authorization, and the policy job passes. - A read-only live gate exercise preserved the existing merge-freshness denial when master advanced beyond the available merge ref. It allocated no runner and was not a successful admission proof. ## Risks - The short metadata authorization job now depends on GitHub-hosted queue capacity. This prevents a stale roster from allocating AWS before current CODEOWNERS are checked. Authorized test and final verification jobs still use AWS. - Identity/API failures fall back to hosted CI. No caller can override the trusted owner list with PR contents. - Configuration dependencies still require conservative graph handling. Existing setup dependency, opaque I/O, stale manifest and wrong-lane tests remain in place. - The runner group is restricted to selected repositories and selected workflows. Its workflow allowlist was verified and narrowed through the GitHub settings UI. Legacy pinned callers must update to the current trusted workflow before using AWS; active PR runs used master references. The current PR workflow authorization and evaluation workflow authorizations remain in place. ## Model Used - OpenAI Codex, based on GPT-6. The exact serving variant and context limit are not exposed in this session. Used reasoning, repository inspection, code execution and GitHub tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass — targeted suites passed; the full local suite hit the PostgreSQL startup limitation documented above, and full Linux CI passed - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
128 lines
6.9 KiB
JavaScript
128 lines
6.9 KiB
JavaScript
import { execFileSync } from "node:child_process";
|
|
import { appendFileSync, lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
import { fileURLToPath } from "node:url";
|
|
import path from "node:path";
|
|
import assert from "node:assert/strict";
|
|
import { refineTestPlan, selectionDurations } from "./test-selection-plan.mjs";
|
|
import { productInputs } from "../../.github/scripts/ci-inputs.mjs";
|
|
import { mergeDiff } from "../../.github/scripts/ci-diff.mjs";
|
|
|
|
export function selectionEligibility(plan) {
|
|
if (plan?.version !== 1 || plan.mode !== "enabled" || plan.forceReason) return "Full/shadow/forced task plan";
|
|
if (!Array.isArray(plan.changed) || !plan.changed.length) return "Incomplete comparison";
|
|
const changed = productInputs(plan.changed);
|
|
if (!changed.length) return "Documentation-only diff";
|
|
for (const file of changed) {
|
|
// Business modules can contain "config"/"setup" in their names. The graph
|
|
// separately tracks actual setup and configuration dependencies.
|
|
if (!/^(?:ui\/src|server\/src|cli\/src|packages\/.+\/src)\/.+\.[cm]?[jt]sx?$/.test(file)
|
|
|| /(?:^|\/)(?:vite|vitest)\.(?:config|setup)\.[cm]?[jt]sx?$|\.d\.[cm]?ts$/i.test(file)
|
|
|| file.split("/").includes("..")) return `Broad input: ${file}`;
|
|
try {
|
|
if (!lstatSync(file).isFile()) return `Non-regular source: ${file}`;
|
|
} catch { return `Deleted or missing source: ${file}`; }
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function runnerInventory(group) {
|
|
const args = group === "serialized" ? ["--mode", "serialized", "--shard-index", "0", "--shard-count", "1"]
|
|
: ["--mode", "general", "--group", group,
|
|
...(group === "general-server-without-chat" ? ["--shard-index", "0", "--shard-count", "1"] : [])];
|
|
const env = { ...process.env, GITHUB_WORKFLOW: "PR" };
|
|
delete env.PAPERCLIP_CI_TEST_SELECTION;
|
|
return JSON.parse(execFileSync(process.execPath, ["scripts/run-vitest-stable.mjs", ...args, "--dry-run"],
|
|
{ env, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }));
|
|
}
|
|
|
|
export async function createTestSelection(plan, head) {
|
|
const reason = selectionEligibility(plan);
|
|
if (reason) throw new Error(reason);
|
|
const groups = new Set();
|
|
for (const job of ["general_tests", "verify_serialized_server"]) {
|
|
if (plan.jobs[job].run) for (const entry of plan.jobs[job].matrix.include) groups.add(entry.group ?? "serialized");
|
|
}
|
|
groups.delete("general-chat"); // Keep its line sharding and DB ownership intact.
|
|
const owners = {}, projects = new Set();
|
|
for (const group of groups) {
|
|
const inventory = runnerInventory(group);
|
|
if (group === "serialized" || group === "general-server-without-chat") {
|
|
owners[group] = { "@paperclipai/server": group === "serialized"
|
|
? inventory.selectedSerializedSuites : inventory.selectedGeneralServerSuites };
|
|
projects.add("@paperclipai/server");
|
|
} else {
|
|
owners[group] = Object.fromEntries(inventory.workspaceProjects.map((project) => [project, null]));
|
|
for (const project of inventory.workspaceProjects) projects.add(project);
|
|
}
|
|
}
|
|
const { selectProjectTests } = await import("./vitest-selection-graph.mjs");
|
|
const graphs = [];
|
|
const changed = productInputs(plan.changed);
|
|
for (const project of projects) {
|
|
const graph = await selectProjectTests({ project, changed, onlyOwnChanges: true });
|
|
graphs.push(graph);
|
|
console.log(`${project}: ${graph.selected.length}/${graph.inventory.length} files, ${graph.alwaysRun.length} retained conservatively, ${graph.seconds.toFixed(1)}s`);
|
|
for (const owner of Object.values(owners)) if (owner[project] === null) owner[project] = graph.inventory;
|
|
}
|
|
const covered = new Set(graphs.flatMap((graph) => graph.coveredChanges));
|
|
for (const file of changed) assert.ok(covered.has(file), `Change outside the resolved test graphs: ${file}`);
|
|
const server = graphs.find((graph) => graph.project === "@paperclipai/server");
|
|
if (server) {
|
|
const general = runnerInventory("general-server-without-chat");
|
|
const native = runnerInventory("general-server-native-runner");
|
|
assert.deepEqual([...general.selectedGeneralServerSuites, ...general.selectedSerializedSuites,
|
|
...native.selectedGeneralServerSuites, "server/src/__tests__/chat-channels.integration.test.ts"].sort(),
|
|
server.inventory, "Server inventory must be completely covered by existing lane ownership");
|
|
}
|
|
return { ...refineTestPlan({ plan, head, owners, graphs, durations: selectionDurations() }), graphs };
|
|
}
|
|
|
|
async function main() {
|
|
const plan = JSON.parse(process.env.CI_PLAN || "null");
|
|
const output = (key, value) => {
|
|
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `${key}=${value}\n`);
|
|
};
|
|
if (process.argv.includes("--eligible")) {
|
|
const reason = selectionEligibility(plan);
|
|
console.log(reason ?? "Source diff is eligible for graph selection");
|
|
output("enabled", !reason);
|
|
return;
|
|
}
|
|
const directory = ".ci-test-selection";
|
|
mkdirSync(directory, { recursive: true });
|
|
const git = (...args) => execFileSync("git", args, { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).trim();
|
|
let result;
|
|
try {
|
|
const head = git("rev-parse", "HEAD");
|
|
assert.equal(head, process.env.GITHUB_SHA, "Selection must describe the tested merge commit");
|
|
assert.ok(plan.diff, "Missing trusted merge diff");
|
|
const local = mergeDiff(head, plan.diff.prHead);
|
|
assert.deepEqual(local.diff, plan.diff, "Selection must use the trusted merge parents");
|
|
assert.deepEqual(local.changed, [...new Set(plan.changed)].sort(), "Local diff disagrees with the trusted routing diff");
|
|
assert.equal(git("status", "--porcelain", "--untracked-files=normal"), "", "Source inputs changed during dependency setup");
|
|
process.env.NODE_ENV = "test";
|
|
process.env.VITEST = "true";
|
|
result = await createTestSelection(plan, head);
|
|
writeFileSync(`${directory}/manifest.json`, JSON.stringify(result.manifest));
|
|
writeFileSync(`${directory}/audit.json`, JSON.stringify(result.graphs, null, 2));
|
|
output("selected", "true");
|
|
} catch (error) {
|
|
console.warn(`Using the complete task plan: ${error.message}`);
|
|
result = { plan: { ...plan, testSelectionFallback: error.message } };
|
|
output("selected", "false");
|
|
}
|
|
writeFileSync(`${directory}/plan.json`, JSON.stringify(result.plan));
|
|
if (process.env.GITHUB_STEP_SUMMARY) {
|
|
const stats = result.plan.testSelection?.stats;
|
|
appendFileSync(process.env.GITHUB_STEP_SUMMARY, stats
|
|
? ["### Vitest test selection", "", "| Lane | Test files | Jobs |", "| --- | ---: | ---: |",
|
|
...stats.map((s) => `| ${s.group} | ${s.selected}/${s.total} | ${s.jobs}/${s.beforeJobs} |`), "",
|
|
"Filesystem/process/opaque consumers are retained. Chat and native Runner lanes keep their existing ownership.", ""].join("\n")
|
|
: `### Vitest test selection\n\nFull task plan: ${result.plan.testSelectionFallback}\n`);
|
|
}
|
|
}
|
|
|
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
main().catch((error) => { console.error(error); process.exitCode = 1; });
|
|
}
|