// Measures how long the server's own spawnClaudeProcessGroup blocks the calling thread
// (the synchronous fork in libuv) as the process RSS grows.
import { spawnClaudeProcessGroup } from "/home/user/wt/factory-issue-45664-triage/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts";

const RUNS = Number(process.env.RUNS ?? 25);
const ballast: Buffer[] = [];
const grow = (mb: number) => {
  for (let i = 0; i < mb / 64; i++) {
    const b = Buffer.allocUnsafe(64 * 1024 * 1024);
    b.fill(i & 0xff);
    ballast.push(b);
  }
};

const measure = async (label: string) => {
  const times: number[] = [];
  for (let i = 0; i < RUNS; i++) {
    const t0 = process.hrtime.bigint();
    const child = spawnClaudeProcessGroup({
      command: "/bin/true",
      args: [],
      cwd: "/tmp",
      env: process.env,
      signal: new AbortController().signal,
    } as never);
    const t1 = process.hrtime.bigint();
    times.push(Number(t1 - t0) / 1e6);
    await new Promise((r) => child.once("exit", r));
  }
  times.sort((a, b) => a - b);
  const rss = Math.round(process.memoryUsage().rss / 1048576);
  const med = times[Math.floor(times.length / 2)];
  console.log(
    `${label}\trss=${rss}MB\truns=${RUNS}\tmedian=${med.toFixed(2)}ms\tmin=${times[0].toFixed(2)}\tmax=${times.at(-1)!.toFixed(2)}\tp90=${times[Math.floor(times.length * 0.9)].toFixed(2)}`,
  );
};

await measure("baseline");
for (const step of [1024, 2048, 4096]) {
  grow(step - (ballast.length * 64));
  await measure(`ballast-${step}MB`);
}
process.exit(0);
