iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / scripts / cloud-rehearsal / start.tsmain at aacbc74

// start.ts — START ONE REHEARSAL of iterate Cloud's sign-up chat against a fake Cloudflare.
// README.md says what a rehearsal is. From the repo's root, the mind is all that it needs:
//
//   node scripts/cloud-rehearsal/start.ts --mind tthq.app
//
// What each of the rest is when it is not given:
//   --scenario "…"   how this rehearsal's Cloudflare differs from the usual start, in a sentence.
//                    Without it, the world is the usual start (rules.ts `startingWorld`).
//   --guide <file>   what the sign-up agent is told. Without it, the mind's own draft when it
//                    has one (apps/cloud-rehearsal/onboarding.md in its config repo, edited in
//                    its Docs app); else iterate Cloud's own guide as it is on GitHub now
//                    (iterate/iterate-config apps/cloud/onboarding.md).
//   --person "First Last <email>"   who plays the new person. Without it, the person the CLI is
//                    signed in to the mind as, by the name in git's user.name.
//   --agent claude|codex|"<command>"   the fake's author. Without it, the first of claude and
//                    codex that does its first task. A command gets the prompt on its stdin.
//   --world <file>   a world.json to start from as it is.
//   --stale-app      start although iterate Cloud's app changed since the rehearsal app was copied.
//
// What a start does, in order:
//   1. checks, before anything runs: the CLI is signed in to the mind; the rehearsal app here
//      (mind-app/) is a copy of iterate Cloud's app as that is now; the mind has this checkout's
//      rehearsal app. Each refusal says what to do;
//   2. makes the run's folder, runs.ignoreme/fake-cf-<time>/, with the usual world;
//   3. finds the fake's author by its first task: turning the scenario into that world, or, with
//      no scenario, saying one word;
//   4. starts the fake's server (serve.ts) on a free port;
//   5. opens a public tunnel, fake-cf-<time>.<mind>, to the server (`iterate tunnel`). Public,
//      because the mind's own Worker calls it and carries no member's sign-in; so every call must
//      start with the run's secret, a random path segment, and the server answers 404 to the rest;
//   6. starts the rehearsal in the mind with one call, `itx.config.cloudRehearsal`: no commit. The
//      app there makes the agent as iterate Cloud makes its own, tells it the guide as a note, and
//      sends its calls to Cloudflare to the tunnel, with the secret. Then it prints the chat's link.
// A start that fails ends the server and the tunnel it started. stop.ts ends them after a start.
// The rehearsal's chat stays in the mind (README.md, "Removing a rehearsal from a mind").
import { spawn, spawnSync } from "node:child_process";
import { randomBytes } from "node:crypto";
import {
  copyFileSync,
  existsSync,
  mkdirSync,
  openSync,
  readFileSync,
  writeFileSync,
} from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { parseArgs } from "node:util";
import { AGENTS, runAgent, scenarioPrompt } from "./ask-agent.ts";
import { startingWorld, World } from "./rules.ts";
import type { RunConfig } from "./serve.ts";

const here = import.meta.dirname;
/** Where a mind keeps its own draft of the guide, in its config repo. */
const GUIDE_IN_MIND = "apps/cloud-rehearsal/onboarding.md";
const repoRoot = resolve(here, "../..");
const { values } = parseArgs({
  options: {
    mind: { type: "string" },
    scenario: { type: "string" },
    guide: { type: "string" },
    person: { type: "string" },
    world: { type: "string" },
    agent: { type: "string" },
    "stale-app": { type: "boolean" },
    /** A list of a real install's routes; iterate-config's, when it is cloned beside this repo or
     *  at ~/src/github.com/iterate/iterate-config. */
    "real-routes": { type: "string" },
  },
});
if (!values.mind)
  throw new Error(
    'usage: start.ts --mind <domain> [--scenario "…"] [--guide <file>] [--person "First Last <email>"] [--agent claude|codex|"<command>"] [--world <file>] [--stale-app]',
  );
const { mind } = values;
const say = (words: string) => console.log(`[${new Date().toISOString().slice(11, 19)}] ${words}`);

// 1. the checks
const whoami = printed("iterate", ["whoami", "--mind", mind]);
const userId = /actor:\s*(user_[0-9a-f]{32})/.exec(whoami)?.[1];
if (!userId) throw new Error(`The CLI is not signed in to ${mind} as a person:\n${whoami}`);
const person = /^\s*(\S+)\s+(.+?)\s*<([^<>\s]+@[^<>\s]+)>\s*$/.exec(
  values.person ||
    `${printed("git", ["config", "user.name"]).trim()} <${/email:\s*"?([^"\s]+@[^"\s]+)/.exec(whoami)?.[1] || ""}>`,
);
if (!person) throw new Error('Who plays the new person? Say it: --person "First Last <email>"');
const [, firstName = "", lastName = "", email = ""] = person;

const app = ["mind.ts", "backend.ts"].map((file) =>
  readFileSync(join(here, "mind-app", `${file}.txt`), "utf8"),
);
const copiedAt = /apps\/cloud\/mind\.ts at ([0-9a-f]{7,40})/.exec(app[0] || "")?.[1];
if (!copiedAt) throw new Error("mind-app/mind.ts.txt does not name the commit it was copied at");
const changedSinceTheCopy: string[] = values["stale-app"]
  ? []
  : JSON.parse(
      printed("gh", [
        "api",
        `repos/iterate/iterate-config/compare/${copiedAt}...main`,
        "--jq",
        '[.files[].filename | select(. == "apps/cloud/mind.ts" or . == "apps/cloud/backend.ts")]',
      ]),
    );
if (changedSinceTheCopy.length > 0)
  throw new Error(
    `iterate Cloud's app changed since the rehearsal app was copied from it at ${copiedAt}: ${changedSinceTheCopy.join(", ")}.\nBring the changes over first (scripts/cloud-rehearsal/README.md, "When iterate Cloud's app changes"), or start with the app as it is: --stale-app`,
  );

// the last check runs in the mind, as a script from the run's folder, which is therefore made here
const stamp = Date.now();
const id = `fake-cf-${stamp}`;
const publicUrl = `https://${id}.${mind}`;
const runDir = join(here, "runs.ignoreme", id);
mkdirSync(join(runDir, "reference"), { recursive: true });
writeFileSync(
  join(runDir, "installed-in-mind.js"),
  `const repo = itx.repos.get("/repos/config");
const tip = await repo.tip();
const installed = await Promise.all(["mind.ts", "backend.ts"].map((file) => repo.readFile("apps/cloud-rehearsal/" + file, { commitOid: tip }).catch(() => null)));
if (JSON.stringify(installed) !== ${JSON.stringify(JSON.stringify(app))}) throw new Error("This mind has no rehearsal app, or not this checkout's. Install it, then start again: node scripts/cloud-rehearsal/install.ts --mind ${mind}");
return "This mind has this checkout's rehearsal app.";`,
);
printed("iterate", ["itx", "run", "--mind", mind, "--file", join(runDir, "installed-in-mind.js")]);

// 2. the run's folder
const scenario = values.scenario || "The usual start: nothing out of the ordinary.";
for (const file of ["rules.ts", "base-rules.ts"])
  copyFileSync(join(here, file), join(runDir, "reference", file));
copyFileSync(join(here, "RULES.md"), join(runDir, "RULES.md"));
writeFileSync(
  join(runDir, "rules.mjs"),
  "// This run's own rules, tried before the shared ones. RULES.md says how to write one.\nexport const rules = [];\n",
);
writeFileSync(join(runDir, "run.jsonl"), "");
if (values.world) copyFileSync(values.world, join(runDir, "world.json"));
else
  writeFileSync(
    join(runDir, "world.json"),
    `${JSON.stringify(startingWorld({ id, scenario, now: stamp, person: { email, firstName, lastName } }), null, 2)}\n`,
  );
say(`The run's folder is ${runDir}`);

// 3. the fake's author, found by its first task
const firstTask =
  values.scenario && !values.world
    ? scenarioPrompt({ scenario, now: new Date().toISOString() })
    : "Answer with the one word: ready.";
const authors = values.agent ? [values.agent] : ["claude", "codex"];
let agentCommand: string[] = [];
for (const author of authors) {
  const command = AGENTS[author] || author.split(/\s+/).filter(Boolean);
  say(`${author} is asked to be the fake's author…`);
  try {
    await runAgent({
      command,
      runDir,
      prompt: firstTask,
      logFile: join(runDir, "agent-0.log"),
      timeoutMs: 300_000,
    });
    agentCommand = command;
    break;
  } catch {
    const lastWords = readFileSync(join(runDir, "agent-0.log"), "utf8").trim().split("\n").at(-1);
    say(`${author} cannot be the author: ${lastWords || "it said nothing"}`);
  }
}
if (agentCommand.length === 0)
  throw new Error(
    `No agent can be the fake's author (tried ${authors.join(", ")}): see ${runDir}/agent-0.log`,
  );
// the author may have changed the world: it must still be one before anything is started
World.parse(JSON.parse(readFileSync(join(runDir, "world.json"), "utf8")));

// 4. the server
const REAL_ROUTES = "apps/cloudflare-simulator/test/real-routes.txt";
const defaultRealRoutes = [
  resolve(repoRoot, "../iterate-config", REAL_ROUTES),
  join(homedir(), "src/github.com/iterate/iterate-config", REAL_ROUTES),
].find((file) => existsSync(file));
if (!values["real-routes"] && !defaultRealRoutes)
  say(
    `No list of a real install's routes: no iterate-config clone beside this repo or at ~/src/github.com/iterate/iterate-config. Only the routes of Cloudflare's spec count (--real-routes <file> names one).`,
  );
/** The first path segment of every call to the fake: the tunnel is public. */
const secret = randomBytes(24).toString("hex");
const fakeUrl = `${publicUrl}/${secret}`;
const config: RunConfig = {
  id,
  publicUrl,
  secret,
  agentCommand,
  specCacheDir: join(here, "cache.ignoreme", "cloudflare-api-spec"),
  realRoutesFile: values["real-routes"] || defaultRealRoutes || null,
};
writeFileSync(join(runDir, "run.json"), `${JSON.stringify(config, null, 2)}\n`);
const detached = (program: string, args: string[], logName: string, cwd: string) => {
  const log = openSync(join(runDir, logName), "a");
  const child = spawn(program, args, {
    cwd,
    detached: true,
    stdio: ["ignore", log, log],
    env: { ...process.env, ITERATE_SKIP_BROWSER_OPEN: "1" },
  });
  child.unref();
  return child.pid;
};
const pids: Record<string, number | undefined> = {};
const writePids = () => writeFileSync(join(runDir, "pids.json"), JSON.stringify(pids));
// A start that throws from here on ends what it started: stop.ts needs a start that worked.
let started = false;
process.on("exit", () => {
  if (started) return;
  for (const pid of Object.values(pids))
    try {
      if (pid) process.kill(pid, "SIGTERM");
    } catch {}
});
pids.server = detached(process.execPath, [join(here, "serve.ts"), runDir], "server.log", repoRoot);
writePids();
say("The fake's server starts (the first run downloads Cloudflare's API spec, about 28 MB)…");
await until("the fake's server listens", 120_000, () => existsSync(join(runDir, "server.json")));
const { port }: { port: number } = JSON.parse(readFileSync(join(runDir, "server.json"), "utf8"));

// 5. the tunnel
pids.tunnel = detached(
  "iterate",
  ["tunnel", String(port), "--name", id, "--public", "--mind", mind],
  "tunnel.log",
  repoRoot,
);
writePids();
await until(
  "the tunnel answers",
  60_000,
  async () => (await fetch(`${fakeUrl}/`).catch(() => null))?.status === 200,
);

// 6. the rehearsal, in the mind
const draftInMind = values.guide ? "" : guideInMind();
if (draftInMind)
  say(`The guide is the mind's own draft: https://docs.${mind}/?doc=${GUIDE_IN_MIND}`);
const guide = guideOf(
  values.guide
    ? readFileSync(values.guide, "utf8")
    : draftInMind ||
        printed("gh", [
          "api",
          "-H",
          "Accept: application/vnd.github.raw",
          "repos/iterate/iterate-config/contents/apps/cloud/onboarding.md",
        ]),
);
writeFileSync(join(runDir, "guide.md"), guide);
say(`The mind ${mind} starts the rehearsal…`);
writeFileSync(
  join(runDir, "start-in-mind.js"),
  `return JSON.stringify(await itx.config.cloudRehearsal(${JSON.stringify({ userId, email, cloudflare: fakeUrl, guide })}));`,
);
const startedInMind = printed("iterate", [
  "itx",
  "run",
  "--mind",
  mind,
  "--file",
  join(runDir, "start-in-mind.js"),
]);
const path = /\/apps\/cloud-rehearsal\/minds\/mind_[a-z2-7]{20}/.exec(startedInMind)?.[0];
if (!path) throw new Error(`The mind ${mind} did not start the rehearsal:\n${startedInMind}`);
started = true;
say(`The chat:             https://dash.${mind}/agents${path}`);
say(`The fake Cloudflare:  ${fakeUrl}/ (the secret path is its key: share it with nobody)`);
say(`Its world and record: ${runDir}/world.json and run.jsonl`);
say(`To stop it:           node scripts/cloud-rehearsal/stop.ts ${id}`);

// ---------------------------------------------------------------------------------------------

/** The guide to rehearse: the file's text above its first `---` line, or all of it. What is under
 *  that line is the author's notes to people, not to the agent. */
function guideOf(text: string) {
  const lines = text.split("\n");
  const rule = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
  return (rule < 0 ? lines : lines.slice(0, rule)).join("\n").trimEnd();
}

/** The mind's own draft of the guide, a file of its config repo, or "" when it has none. People
 *  edit it in the mind's Docs app, so a rehearsal there tries the newest draft. */
function guideInMind() {
  const file = join(runDir, "guide-in-mind.js");
  writeFileSync(
    file,
    `return await itx.repos.get("/repos/config").readFile(${JSON.stringify(GUIDE_IN_MIND)}).catch(() => "");`,
  );
  return printed("iterate", ["itx", "run", "--mind", mind, "--file", file]).trim();
}

/** One command, from the repo's root: what it printed, or a throw. */
function printed(program: string, args: string[]) {
  const result = spawnSync(program, args, {
    cwd: repoRoot,
    encoding: "utf8",
    env: { ...process.env, ITERATE_SKIP_BROWSER_OPEN: "1" },
  });
  if (result.status !== 0)
    throw new Error(
      `${program} ${args.slice(0, 2).join(" ")} failed:\n${result.stdout}\n${result.stderr}`,
    );
  return result.stdout;
}

/** Waits until `check` says yes, looking twice a second. */
async function until(what: string, timeoutMs: number, check: () => boolean | Promise<boolean>) {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    if (await check()) return;
    await new Promise((resolve) => setTimeout(resolve, 500));
  }
  throw new Error(`Gave up after ${timeoutMs / 1000} s: ${what}. See the logs in ${runDir}`);
}