Skip to content

matthewwong525/WongStack / .agents/skills/wong-setup

wong-setup

Unverified

Evaluate or install WongStack from any folder, Cloudflare hosting included, from one token. Installed repos use /wong-sync.

scripts/provision.mjs

View on GitHub
#!/usr/bin/env node
// Cloudflare provisioning for a WongStack repo: the one set of steps setup's runbook (references/cloudflare.md) runs.
// Every step checks before it acts, so a run that stopped runs again from the top. No command prints a token.
import { createHash } from 'node:crypto';
import { chmodSync, existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { isDeepStrictEqual, parseArgs } from 'node:util';
import { isMain } from '../../memory/scripts/lib/cli.mjs';
import { machineId, machineIdFile } from '../../memory/scripts/lib/machine-id.mjs';
import { keyMachine } from '../../../memory/d1/connect.mjs';
import { parseEnv } from '../../memory/scripts/lib/store.mjs';
import { AccessSetupError, CLOUDFLARE_READ_SECRET, accessOrganization, cloudflareReadKey, loginManagementKey, notePreviewKeys, ownerIdentity, provisionAccess, provisionAccessPolicies } from './private-access.mjs';
import { helperConfig } from '../../../loop/routes/artifacts-credential.mjs';
import {
  CloudflareError, PROPAGATION, ProvisionError, accountPolicy, cloudflare, durableEnv, fillConfig, grant, installRunner, orNull, paidPlan, pending,
  readJson, recordComponent, recordFile, recordedBase, retry, run, scopedToken, stateFile, step, wait, widenBy, workerSecrets, writeJson,
} from './lib/cloudflare.mjs';
import { privateDeployment } from '../../../../scripts/lib-access-config.mjs';
import { secretsDir, stagingKeeps } from '../../../../scripts/lib-staging-secrets.mjs';
import { lineProblem, parseConfig, workerName } from '../../../../scripts/lib-wrangler-config.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const FRAGMENTS = join(HERE, '..', '..', 'wong-sync', 'references', 'stack-pack-fragments.md');
const LINE_FILE = 'wrangler.line.jsonc';
const LINE_TEMPLATE = join(HERE, '..', '..', 'wong-sync', 'references', 'wrangler.line.template.jsonc');
/** The one Artifacts namespace every install in an account shares: Cloudflare can not delete a namespace. */
export const NAMESPACE = 'wongstack';
/** Days a check run's snapshot stays in the runner's bucket before the bucket's own rule deletes it. */
export const SNAPSHOT_DAYS = 2;
const ACCOUNT = /^[0-9a-f]{32}$/;
/** The error Cloudflare returns for an R2 call on an account with no R2 subscription. */
export const R2_OFF = 10042;
// Setup owns the shared provisioning steps; these exports preserve the runbook and tests' interface.
export { CloudflareError, PROPAGATION, ProvisionError, cloudflare, run, widenBy };
const isoDate = () => new Date().toISOString().slice(0, 10);

// These groups match references/permission-groups.md, which a test checks. Ids resolve by name; these are the fallback.
/** What the user grants on the token screen. Both must survive every widen. */
export const USER_GRANTS = [
  { name: 'API Tokens Write', scope: 'user', id: '686d18d5ac6c441c867cbf6771e58a0a' },
  { name: 'Account API Tokens Write', scope: 'account', id: '5bc3f8b21c554832afc660159ab75fa4' },
];
/** A normal provision: what the widen grants. R2 is always asked for, since only it can tell whether R2 is on. */
export const NORMAL_PROVISION = [
  { name: 'Workers Scripts Write', scope: 'account', id: 'e086da7e2179491d91ee5f35b3ca210a' },
  { name: 'D1 Write', scope: 'account', id: '09b2857d1c31407795e75e3fed8617a1' },
  { name: 'Account Settings Read', scope: 'account', id: 'c1fde68c7bcc44588cbb6ddbc16d6480' },
  { name: 'Workers CI Read', scope: 'account', id: 'ad99c5ae555e45c4bef5bdf2678388ba' },
  { name: 'Workers CI Write', scope: 'account', id: '2e095cf436e2455fa62c9a9c2e18c478' },
  { name: 'User Details Read', scope: 'user', id: '8acbe5bb0d54464ab867149d7f7cf8ac' },
  { name: 'Workers R2 Storage Write', scope: 'account', id: 'bf7481a1826f439697cb59a20b22293e' },
  { name: 'Access: Apps and Policies Write', scope: 'account', id: '1e13c5124ca64b72b1969a67e8829049' },
  { name: 'Access: Organizations, Identity Providers, and Groups Write', scope: 'account', id: 'bfe0d8686a584fa680f4c53b5eb0de6d' },
  { name: 'Access: Service Tokens Write', scope: 'account', id: 'a1c0fec57cf94af79479a6d827fa518c' },
  { name: 'Zero Trust Write', scope: 'account', id: 'b33f02c6f7284e05a6f20741c0bb0567' },
];
/** The CI deploy token. `when`: always, with a memory bucket, or with custom-domain routes (never set here). */
export const DEPLOY_TOKEN = [
  { name: 'Access: Apps and Policies Read', scope: 'account', when: 'always', id: '7ea222f6d5064cfa89ea366d7c1fee89' },
  { name: 'Workers Scripts Write', scope: 'account', when: 'always', id: 'e086da7e2179491d91ee5f35b3ca210a' },
  { name: 'D1 Write', scope: 'account', when: 'always', id: '09b2857d1c31407795e75e3fed8617a1' },
  { name: 'Account Settings Read', scope: 'account', when: 'always', id: 'c1fde68c7bcc44588cbb6ddbc16d6480' },
  { name: 'Workers R2 Storage Write', scope: 'account', when: 'bucket', id: 'bf7481a1826f439697cb59a20b22293e' },
  { name: 'Workers Routes Write', scope: 'zone', when: 'routes', id: '28f4b596e7d643029c524985477ae49a' },
];
/** The live app's sign-in list key: Access policy writes on this one account, and nothing the deploy token holds. */
export const ACCESS_KEY = [{ name: 'Access: Apps and Policies Write', scope: 'account', id: '1e13c5124ca64b72b1969a67e8829049' }];
const KEY_LINK_STEP = 'because the saved Cloudflare token can not make keys: send the private key link (wiki/development/secrets.md#receive-a-key-through-a-private-link) for a Cloudflare token with Account API Tokens Write, then run `provision.mjs access`';
/** The to-do a report carries when the token could not make that key. Access still opens and saves app choices. */
export const ACCESS_KEY_TODO = `the live app has no key for its sign-in list, ${KEY_LINK_STEP}`;
/** The app's read-only key for Cloudflare look-ups. An allow-list on purpose: a group joins only by being
 * named here, so no Write group and no product that stores data (D1, KV, R2, Queues and the like) is ever in it. */
export const CLOUDFLARE_READ_KEY = [
  { name: 'Account Settings Read', scope: 'account', id: 'c1fde68c7bcc44588cbb6ddbc16d6480' },
  { name: 'Workers Scripts Read', scope: 'account', id: '1a71c399035b4950a1bd1466bbe4f420' },
  { name: 'Workers Tail Read', scope: 'account', id: '05880cd1bdc24d8bae0be2136972816b' },
  { name: 'Workers CI Read', scope: 'account', id: 'ad99c5ae555e45c4bef5bdf2678388ba' },
  { name: 'Account Analytics Read', scope: 'account', id: 'b89a480218d04ceb98b4fe57ca29dc1f' },
  { name: 'Access: Apps and Policies Read', scope: 'account', id: '7ea222f6d5064cfa89ea366d7c1fee89' },
  { name: 'Access: Audit Logs Read', scope: 'account', id: 'b05b28e839c54467a7d6cba5d3abb5a3' },
  { name: 'Billing Read', scope: 'account', id: '7cf72faf220841aabcfdfab81c43c4f6' },
  { name: 'Zone Read', scope: 'zone', id: 'c8fed203ed3043cba015a93ad1616f1f' },
  { name: 'DNS Read', scope: 'zone', id: '82e64a83756745bbbb1c9c2701bf816b' },
  { name: 'Analytics Read', scope: 'zone', id: '9c88f9c5bce24ce7af9a958ba9c504db' },
];
/** The to-do a report carries when the token could not make that key. Everything else in Access still works. */
export const CLOUDFLARE_READ_KEY_TODO = `the app has no read-only Cloudflare key for look-ups, ${KEY_LINK_STEP}`;

// The steps the owner follows on GitHub for the wide key, which lets the app hand the project out and save
// changes to it. `read` is the read-only key it replaces: still enough to hand the project out.
export const CODE_KEY = {
  name: 'WONG_CODE_WRITE',
  read: 'WONG_CODE_READ',
  url: 'https://github.com/settings/personal-access-tokens/new',
  steps: (repository) => [
    `Repository access: Only select repositories, then pick ${repository}`,
    'Repository permissions: set Contents to Read and write, and Pull requests to Read and write',
    'Set three more to Read-only: Actions, Commit statuses, Deployments',
    'Add no other permission, and never Workflows: that one would let a saved change rewrite the checks',
    'Expiration: No expiration, or renew it before it ends',
    'Tap Generate token and copy it',
  ],
};

/** What an Artifacts install adds to the widen: its repository, its check runner, and the read that sees the plan. */
export const ARTIFACTS_PROVISION = [
  { name: 'Artifacts Write', scope: 'account', id: 'f9e1ba803b8d4d52b4d4184825b07a28' },
  { name: 'Workers Containers Write', scope: 'account', id: 'bdbcd690c763475a985e8641dddc09f7' },
  { name: 'Billing Read', scope: 'account', id: '7cf72faf220841aabcfdfab81c43c4f6' },
];
/** What a GitHub install adds: company knowledge's repository and the plan read, never the check runner's container. */
export const KNOWLEDGE_PROVISION = ARTIFACTS_PROVISION.filter((row) => row.name !== 'Workers Containers Write');
/** What a free account is told: every route keeps company knowledge in Cloudflare, which only its paid plan allows. */
export const PAID_PLAN = { needs: 'Workers Paid', cost: 'about $5 a month', neededBy: ['github', 'artifacts'] };
/** The check runner's storage key: the objects of its one bucket, and nothing else. */
export const STORAGE_TOKEN = { name: 'Workers R2 Storage Bucket Item Write', scope: 'com.cloudflare.edge.r2.bucket', id: '2efd5506f9c8494dacb1fa10a3e7d5b6' };

/** A name that Workers and D1 accept: lowercase letters, digits, and `-`, at most 40 characters. */
export function safeName(name) {
  const safe = String(name)
    .toLowerCase()
    .replace(/[^a-z0-9-]+/g, '-')
    .replace(/-+/g, '-')
    .slice(0, 40)
    .replace(/^-|-$/g, '');
  return safe || 'wongstack';
}

/** A `.env` file's `KEY=value` lines, read by the memory scripts' parser; `{}` when it is missing. */
export const readEnv = file => (existsSync(file) ? parseEnv(readFileSync(file, 'utf8')) : {});

/** Every name one base takes. The memory store's database and bucket share a name. */
export const namesFor = (base) => ({
  worker: base,
  staging: `${base}-staging`,
  db: `${base}-db`,
  stagingDb: `${base}-db-staging`,
  memory: `${base}-memory`,
  deploy: `${base}-deploy`,
  knowledge: `${base}-knowledge`,
});

/** What an Artifacts install adds under one base: its repository, its check runner (Worker, Workflow, bucket),
 * and the runner's storage key. */
export const artifactNamesFor = (base) => ({ repo: base, runner: `${base}-checks`, storage: `${base}-checks-storage` });

/** The token grants itself a normal provision's groups, keeping what it has, then waits until the set works.
 * `openWithoutLogin`: an Access probe still refused after the full wait goes in `accessPending`, not a stop. */
export async function widen({ token, api, fetch, account, route = 'github', openWithoutLogin = false, sleep = wait }) {
  const cf = cloudflare(token, { api, fetch });
  const { granted, held } = await grant(cf, [...USER_GRANTS, ...NORMAL_PROVISION, ...(route === 'artifacts' ? ARTIFACTS_PROVISION : KNOWLEDGE_PROVISION)]);
  const probed = account ? [account] : (await step('cloudflare', () => cf('GET', '/accounts?per_page=50'))).map((each) => each.id);
  const accessPending = [];
  for (const id of probed) {
    await step('cloudflare', () => retry(() => cf('GET', `/accounts/${id}/d1/database?per_page=1`), sleep, pending));
    // Artifacts and Containers answer only on a paid account, so the plan read is the one probe here.
    await step('cloudflare', () => retry(() => cf('GET', `/accounts/${id}/subscriptions`), sleep, pending));
    for (const surface of ['apps', 'identity_providers', 'service_tokens']) {
      const probe = () => cf('GET', `/accounts/${id}/access/${surface}?per_page=1`);
      await step('cloudflare', async () => {
        try {
          await (accessPending.length ? probe() : retry(probe, sleep, pending));
        } catch (error) {
          if (!openWithoutLogin || !pending(error)) throw error;
          if (!accessPending.includes(surface)) accessPending.push(surface);
        }
      });
    }
  }
  return {
    granted,
    held,
    probed,
    ...(openWithoutLogin && { accessPending }),
  };
}

/** The accounts the token sees. Zero with a valid token means Account Resources was left unset. */
export async function accounts({ token, api, fetch }) {
  const list = await step('token', () => cloudflare(token, { api, fetch })('GET', '/accounts?per_page=50'));
  return { accounts: list.map(({ id, name }) => ({ id, name })) };
}

/** Which route a new install takes, before anything is created: `artifacts` on Mac or Linux, `github` on Windows,
 * and the plan. With no paid plan seen, `reason` is `free-plan`: every route needs it, so setup stops. */
export async function plan({ token, api, fetch, account, platform = process.platform, sleep = wait }) {
  const route = platform === 'win32' ? 'github' : 'artifacts';
  const seen = await step('cloudflare', () => paidPlan(cloudflare(token, { api, fetch }), account, sleep));
  if (!seen) return { route, reason: 'free-plan', ...PAID_PLAN };
  return { route, ...(route === 'github' && { reason: 'windows' }), plan: seen };
}

/** The account's R2 buckets, or null when R2 is off. Any other failure throws. */
async function r2Buckets(cf, account) {
  try {
    return (await cf('GET', `/accounts/${account}/r2/buckets?per_page=1000`)).buckets ?? [];
  } catch (error) {
    if (error instanceof CloudflareError && (error.codes.includes(R2_OFF) || error.messages.some((m) => /enable R2/i.test(m)))) return null;
    throw error;
  }
}

/** The names an Artifacts install adds under one base, by kind. */
const artifactNameList = (base) => {
  const a = artifactNamesFor(base);
  return [
    { kind: 'repository', name: a.repo },
    { kind: 'worker', name: a.runner },
    { kind: 'bucket', name: a.runner },
    { kind: 'token', name: a.storage },
  ];
};

/** The install's Artifacts repositories by name; none when the shared namespace does not exist yet. */
async function repositories(cf, account) {
  try {
    return await cf('GET', `/accounts/${account}/artifacts/namespaces/${NAMESPACE}/repos?limit=200`);
  } catch (error) {
    if (error instanceof CloudflareError && error.status === 404) return [];
    throw error;
  }
}

/** Each name one base takes, by kind. */
const nameList = (base) => {
  const n = namesFor(base);
  return [
    { kind: 'worker', name: n.worker },
    { kind: 'worker', name: n.staging },
    // The live line's own Worker, which the first publish makes from the stack pack's line fragment.
    { kind: 'worker', name: `${n.worker}-line` },
    { kind: 'database', name: n.db },
    { kind: 'database', name: n.stagingDb },
    { kind: 'database', name: n.memory },
    { kind: 'bucket', name: n.memory },
    { kind: 'token', name: n.deploy },
    { kind: 'repository', name: n.knowledge },
  ];
};

/** Derives the names from the repo, and reports each as free, ours (this repo provisioned it), or taken.
 * `base` is the repo's own base on a rerun, else the first base with every name free. */
export async function names({ token, api, fetch, account, repo, route = 'github', dir = '.', exec = run }) {
  const cf = cloudflare(token, { api, fetch });
  const artifacts = route === 'artifacts';
  const all = (base) => [...nameList(base), ...(artifacts ? artifactNameList(base) : [])];
  const named = (base) => ({ ...namesFor(base), ...(artifacts && artifactNamesFor(base)) });
  const derived = safeName(String(repo).split('/').at(-1));
  const recorded = await recordedBase(dir, exec);
  const existing = await step('cloudflare', async () => {
    const [workers, databases, tokens, buckets, repos] = await Promise.all([
      cf('GET', `/accounts/${account}/workers/scripts`),
      cf('GET', `/accounts/${account}/d1/database?per_page=1000`),
      cf('GET', `/accounts/${account}/tokens?per_page=100`),
      r2Buckets(cf, account),
      repositories(cf, account),
    ]);
    return {
      repository: new Set(repos.map((r) => r.name)),
      worker: new Set(workers.map((w) => w.id)),
      database: new Set(databases.map((d) => d.name)),
      token: new Set(tokens.map((t) => t.name)),
      bucket: new Set((buckets ?? []).map((b) => b.name)),
    };
  });
  const check = (base, ours) => all(base).map((item) => ({ ...item, status: existing[item.kind].has(item.name) ? (ours ? 'ours' : 'taken') : 'free' }));
  if (recorded) return { derived, base: recorded, names: named(recorded), checked: check(recorded, true) };
  const checked = check(derived, false);
  let base = derived;
  for (let n = 2; check(base, false).some((item) => item.status === 'taken'); n++) base = `${derived}-${n}`;
  return { derived, base, names: named(base), checked };
}

/** The database called `name`, made when it does not exist. Returns its id. */
async function database(cf, account, name, note) {
  const found = (await cf('GET', `/accounts/${account}/d1/database?name=${encodeURIComponent(name)}`)).find((d) => d.name === name);
  note(found ? 'reused' : 'created', `database ${name}`);
  return found ? found.uuid : (await cf('POST', `/accounts/${account}/d1/database`, { name })).uuid;
}

/** The account's workers.dev subdomain; an account with none gets one named for the GitHub owner. */
async function subdomain(cf, account, owner, note) {
  const current = await cf('GET', `/accounts/${account}/workers/subdomain`).catch((error) => {
    if (error instanceof CloudflareError && error.status === 404) return {};
    throw error;
  });
  if (current.subdomain) return current.subdomain;
  const slug = safeName(owner);
  for (let n = 1; ; n++) {
    try {
      const made = (await cf('PUT', `/accounts/${account}/workers/subdomain`, { subdomain: n === 1 ? slug : `${slug}-${n}` })).subdomain;
      note('created', `workers.dev subdomain ${made}`);
      return made;
    } catch (error) {
      if (n === 5) throw error;
    }
  }
}

/** The `jsonc` block under the `wrangler.jsonc` heading of the stack pack's fragments. */
export function wranglerFragment(file = FRAGMENTS) {
  const text = readFileSync(file, 'utf8');
  const block = /^## `wrangler\.jsonc`[^\n]*\n[\s\S]*?```jsonc\n([\s\S]*?)```/m.exec(text);
  if (!block) throw new ProvisionError('repo', `${file} has no wrangler.jsonc fragment`);
  return block[1];
}

/** Drops the lines from the one matching `from` through the first after it matching `to`. */
function dropLines(text, from, to) {
  const lines = text.split('\n');
  const start = lines.findIndex((line) => from.test(line));
  if (start < 0) return text;
  const end = lines.findIndex((line, i) => i >= start && to.test(line));
  lines.splice(start, end - start + 1);
  return lines.join('\n');
}

// The app's wrangler config: the fragment, comments kept, every placeholder filled. An open `access` (no Zero Trust
// yet) blanks the Access ids and adds `WORKSPACE_LOGIN: "off"`, the switch the Worker and the deploy check read.
export function wranglerConfig({ base, ids, bucket, access }, fragment = wranglerFragment()) {
  const n = namesFor(base);
  let text = fragment;
  if (!bucket) text = dropLines(text, /\/\/ Only when the memory store has a bucket/, /^\s*\],?\s*$/);
  text = text.replace(/,(\s*\n\s*[}\]])/g, '$1');
  const fill = {
    '<your-worker>': n.worker,
    '<your-db-name>': n.db,
    '<production database_id>': ids.db,
    '<staging database_id>': ids.stagingDb,
    '<memory database_id>': ids.memory,
    '<your-repo>': base,
    '<access team domain>': access?.teamDomain ?? '',
    '<access audience>': access?.audience ?? '',
    '<access app id>': access?.appId ?? '',
    '<staging access audience>': access?.staging?.audience ?? '',
    '<staging access app id>': access?.staging?.appId ?? '',
    '<production Worker id>': access?.workers?.[0]?.id ?? '',
    '<staging Worker id>': access?.workers?.[1]?.id ?? '',
    // The owner Access knows. An open site has no sign-in to know anyone by, so it stays blank there.
    '<owner email>': access?.mode === 'open' ? '' : (access?.ownerEmail ?? ''),
  };
  for (const [placeholder, value] of Object.entries(fill)) text = text.replaceAll(placeholder, value);
  if (access?.mode === 'open') text = text.replace(/^(\s*)"WONG_ENVIRONMENT": "(production|staging)",[ \t]*$/gm, '$&\n$1"WORKSPACE_LOGIN": "off",');
  const left = /<[^<>\n]+>/.exec(text);
  if (left) throw new ProvisionError('repo', `the wrangler fragment has a placeholder this script does not fill: ${left[0]}`);
  return text.endsWith('\n') ? text : `${text}\n`;
}

// The live line's own Worker config, filled from the app's config: its Worker name, and the live database.
// Null when the app config has no database to give it.
export function lineConfig(app, fragment = readFileSync(LINE_TEMPLATE, 'utf8')) {
  const db = app.d1_databases?.find((entry) => entry.binding === 'DB');
  if (!db?.database_id) return null;
  const fill = { '<your-worker>': workerName(app), '<your-db-name>': db.database_name, '<production database_id>': db.database_id };
  let text = fragment;
  for (const [placeholder, value] of Object.entries(fill)) text = text.replaceAll(placeholder, value);
  const left = /<[^<>\n]+>/.exec(text);
  if (left) throw new ProvisionError('repo', `the line fragment has a placeholder this script does not fill: ${left[0]}`);
  return text.endsWith('\n') ? text : `${text}\n`;
}

/** The index of the bracket closing the one at `open`, skipping strings and comments; -1 when it never closes. */
function closeOf(text, open) {
  let depth = 0;
  for (let i = open; i < text.length; i++) {
    const ch = text[i];
    if (ch === '"') {
      for (i++; i < text.length && text[i] !== '"'; i++) if (text[i] === '\\') i++;
    } else if (ch === '/' && text[i + 1] === '/') {
      i = text.indexOf('\n', i);
      if (i < 0) return -1;
    } else if (ch === '/' && text[i + 1] === '*') {
      i = text.indexOf('*/', i) + 1;
      if (i <= 0) return -1;
    } else if (ch === '{' || ch === '[') depth++;
    else if ((ch === '}' || ch === ']') && --depth === 0) return i;
  }
  return -1;
}

// The text with the object entry `key` inside the first block `scope` opens removed, with its comma, keeping every
// comment. Null when that block holds no such entry.
function withoutEntry(text, key, scope) {
  const block = scope.exec(text);
  const end = block ? closeOf(text, block.index + block[0].length - 1) : -1;
  const entry = new RegExp(`"${key}"\\s*:\\s*\\{`, 'g');
  entry.lastIndex = block?.index ?? 0;
  const found = end >= 0 && entry.exec(text);
  if (!found || found.index > end) return null;
  let to = closeOf(text, found.index + found[0].length - 1) + 1;
  if (to <= 0) return null;
  let head = text.slice(0, found.index).replace(/[ \t]*$/, '');
  const comma = /^[ \t]*,/.exec(text.slice(to));
  if (comma) to += comma[0].length;
  else head = head.replace(/,(\s*)$/, '$1');
  const tail = text.slice(to);
  return head + (head.endsWith('\n') ? tail.replace(/^[ \t]*\n/, '') : tail);
}

const isLine = (binding) => binding.class_name === 'Line';
const LINE_ENVS = [undefined, 'local'];

// Points the app config at the line's Worker as LIVE_LINE, none in env.staging, with line-2: Cloudflare refuses the
// class drop while a binding keeps the name LINE. Returns `updated`, `current`, or false with the file restored.
function lineInConfig(file) {
  const before = readFileSync(file, 'utf8');
  const config = parseConfig(file);
  const want = (env) => `${workerName(config)}-line${env ? `-${env}` : ''}`;
  const staging = (parsed) => parsed.env?.staging?.durable_objects?.bindings ?? [];
  const pointed = (parsed) => !staging(parsed).some(isLine) && LINE_ENVS.every((env) => {
    const at = env ? parsed.env?.[env] : parsed;
    if (env && !at) return true;
    const bindings = at.durable_objects?.bindings ?? [];
    return bindings.length === 1 && bindings[0].name === 'LIVE_LINE' && bindings[0].script_name === want(env);
  }) && parsed.migrations?.some((m) => m.tag === 'line-2' && m.deleted_classes?.includes('Line'));
  if (pointed(config)) return 'current';
  let text = before;
  if (staging(config).length && staging(config).every(isLine)) text = withoutEntry(text, 'durable_objects', /"staging"\s*:\s*\{/) ?? text;
  let seen = 0;
  text = text.replace(/\{\s*"name"\s*:\s*"LINE"\s*,\s*"class_name"\s*:\s*"Line"\s*\}/g,
    () => `{ "name": "LIVE_LINE", "class_name": "Line", "script_name": "${want(LINE_ENVS[seen++])}" }`);
  if (!/"tag"\s*:\s*"line-2"/.test(text)) text = text.replace(/(\{\s*"tag"\s*:\s*"line-1"\s*,\s*"new_sqlite_classes"\s*:\s*\["Line"\]\s*\})/, '$1, { "tag": "line-2", "deleted_classes": ["Line"] }');
  writeFileSync(file, text);
  try {
    if (pointed(parseConfig(file))) return 'updated';
  } catch {
    // Falls through to restore the file.
  }
  writeFileSync(file, before);
  return false;
}

// Drops the line config's env.staging, a test line from before previews lost theirs, keeping its comments. An unknown
// shape restores the file, and the line check after it leaves the to-do.
function lineFileCurrent(file, note) {
  const before = readFileSync(file, 'utf8');
  if (!parseConfig(file).env?.staging) return;
  const text = withoutEntry(before, 'staging', /"env"\s*:\s*\{/);
  if (!text) return;
  writeFileSync(file, text);
  try {
    if (!parseConfig(file).env?.staging) return void note('updated', `app/${LINE_FILE} without its test line`);
  } catch {
    // Falls through to restore the file.
  }
  writeFileSync(file, before);
}

/** The to-do left when the app config can not be pointed at the line's own Worker by script. */
export const LINE_TODO = "point app/wrangler.jsonc's live line at its own Worker, as the stack pack's wrangler.jsonc fragment shows: a LIVE_LINE binding with its script_name at the top level and in env.local, none in env.staging, and migration line-2";

/** The to-do left when another project's Worker already holds the line's name: nothing will deploy over it. */
export const lineClashTodo = (name) => `this Cloudflare account already has a Worker named ${name} that this install has no record of making, so the live line was left alone rather than overwrite it: don't save the update until it's settled. If it is this install's, list it under components.liveLine.workers in .claude/.wong-stack.json and run provisioning again; if it is another project's, this app's line needs that name free`;

// Writes the live line's settings; the first publish makes its Worker, before the app, and setup deploys nothing. A
// Worker already holding the line's name is this install's only when the install record lists it; any other clashes.
async function liveLine(dir, config, { cf, account, note, todo }) {
  const file = join(dir, 'app', LINE_FILE);
  if (!/"class_name"\s*:\s*"Line"/.test(readFileSync(config, 'utf8'))) return;
  const name = existsSync(file) ? workerName(parseConfig(file)) : `${workerName(parseConfig(config))}-line`;
  const recorded = readJson(recordFile(dir))?.components?.liveLine?.workers ?? [];
  const held = (await step('cloudflare', () => cf('GET', `/accounts/${account}/workers/scripts`))).map((each) => each.id);
  if (held.includes(name) && !recorded.includes(name)) return void todo.push(lineClashTodo(name));
  if (!existsSync(file)) {
    const text = lineConfig(parseConfig(config));
    if (!text) return void todo.push(LINE_TODO);
    writeFileSync(file, text);
    note('created', `app/${LINE_FILE}`);
  } else lineFileCurrent(file, note);
  const pointed = lineInConfig(config);
  if (pointed === 'updated') note('updated', "app/wrangler.jsonc's live line");
  if (!pointed) return void todo.push(LINE_TODO);
  const line = parseConfig(file);
  const problem = lineProblem(line, parseConfig(config));
  if (problem) return void todo.push(`fix app/${LINE_FILE}: ${problem}`);
  recordComponent(dir, 'liveLine', { workers: [workerName(line)] }, note);
}

/** Adds the bucket binding before the top-level `env` key of an existing config. False when there is none. */
function addBucketBinding(file, bucket) {
  const text = readFileSync(file, 'utf8');
  const env = /^([ \t]+)"env"\s*:/m.exec(text);
  if (!env) return false;
  const indent = env[1];
  const unit = indent.startsWith('\t') ? '\t' : indent;
  const block = `${indent}"r2_buckets": [\n${indent}${unit}{ "binding": "MEMORY_BUCKET", "bucket_name": "${bucket}" }\n${indent}],\n`;
  writeFileSync(file, text.slice(0, env.index) + block + text.slice(env.index));
  return true;
}

/** Turns an open config private in place, keeping its comments: fills each environment's four `CF_ACCESS_*` vars and
 * drops `WORKSPACE_LOGIN`. Restores the file and returns false unless it parses to exactly the private config. */
function closeOpenConfig(file, access) {
  const before = readFileSync(file, 'utf8');
  const values = {
    CF_ACCESS_TEAM_DOMAIN: [access.teamDomain, access.teamDomain],
    CF_ACCESS_AUD: [access.audience, access.staging?.audience],
    CF_ACCESS_APP_ID: [access.appId, access.staging?.appId],
    CF_ACCESS_WORKER_ID: [access.workers?.[0]?.id, access.workers?.[1]?.id],
  };
  let text = before.replace(/^[ \t]*"WORKSPACE_LOGIN"\s*:\s*"[^"\n]*",?[ \t]*\n/gm, '');
  for (const [key, [production, staging]] of Object.entries(values)) {
    let seen = 0;
    text = text.replace(new RegExp(`("${key}"\\s*:\\s*)"[^"\\n]*"`, 'g'), (_, head) => `${head}"${[production, staging][seen++] ?? ''}"`);
    if (seen !== 2) return false;
  }
  writeFileSync(file, text);
  try {
    const config = parseConfig(file);
    const [production, staging] = ['production', 'staging'].map((environment) => privateDeployment(config, environment));
    const expected = (deployment, app, worker) => deployment.appId === app?.appId && deployment.audience === app?.audience && deployment.teamDomain === access.teamDomain && deployment.workerId === worker?.id;
    if (expected(production, access, access.workers?.[0]) && expected(staging, access.staging, access.workers?.[1])) return true;
  } catch {
    // Falls through to restore the file.
  }
  writeFileSync(file, before);
  return false;
}

/** Sets one text var in production's and staging's vars of an existing config, in place, comments kept: `value`, or
 * a `[production, staging]` pair. Returns `updated`, `current`, or false when the config has neither place twice. */
function setVar(file, name, value) {
  const before = readFileSync(file, 'utf8');
  const values = Array.isArray(value) ? value : [value, value];
  let seen = 0;
  const next = () => values[seen++];
  let text = before.replace(new RegExp(`("${name}"\\s*:\\s*)"[^"\\n]*"`, 'g'), (_, head) => `${head}"${next()}"`);
  if (!seen) text = before.replace(/^([ \t]*)"WONG_ENVIRONMENT": "(?:production|staging)",[ \t]*$/gm, (line, indent) => `${line}\n${indent}"${name}": "${next()}",`);
  if (seen !== 2) return false;
  if (text === before) return 'current';
  writeFileSync(file, text);
  return 'updated';
}
const setOwnerEmail = (file, email) => setVar(file, 'WONG_OWNER_EMAIL', email);

/** `owner/name` from a GitHub remote address, or null for any other address. */
export const githubRepo = (url) => /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec(String(url ?? '').trim())?.[1] ?? null;

// Adds one binding, `entry` under `key`, to production alone in an existing config, comments kept, and drops a staging
// copy: previews never hold the project's write reach. Returns `updated`, `current`, or false with no safe place.
function addCodeBinding(file, key, entry, comment) {
  const ours = (each) => Object.entries(entry).every(([name, value]) => each[name] === value);
  const state = () => {
    const config = parseConfig(file);
    return { live: Boolean(config[key]?.some(ours)), other: Boolean(config[key] && !config[key].some(ours)), staging: config.env?.staging?.[key] };
  };
  const now = state();
  if (now.live && !now.staging) return 'current';
  if (now.other || (now.staging && !now.staging.every(ours))) return false;
  const before = readFileSync(file, 'utf8');
  const line = `"${key}": [{ ${Object.entries(entry).map(([name, value]) => `"${name}": "${value}"`).join(', ')} }],`;
  let text = before;
  if (!now.live) text = text.replace(/^([ \t]+)"env"\s*:/m, (match, indent) => `${indent}// ${comment}\n${indent}${line}\n${match}`);
  if (now.staging) {
    const lines = text.split('\n');
    const start = lines.findIndex((each) => /^\s*"staging"\s*:\s*\{\s*$/.test(each));
    const at = lines.findIndex((each, index) => start >= 0 && index > start && new RegExp(`^\\s*"${key}"\\s*:\\s*\\[.*\\],?\\s*$`).test(each));
    if (at >= 0) lines.splice(at, 1);
    text = lines.join('\n');
  }
  writeFileSync(file, text);
  try {
    const after = state();
    if (after.live && !after.staging) return 'updated';
  } catch {
    // Falls through to restore the file.
  }
  writeFileSync(file, before);
  return false;
}

// The config half of `projectCode`, calling nothing: the project's name in both Workers' vars and, on Cloudflare, the
// repository and check-runner bindings on the live app alone. `scripts/check-target-app.mjs` builds configs with it.
export function codeInConfig(config, repository, artifacts, runner) {
  const named = repository && existsSync(config) ? setVar(config, 'WONG_CODE_REPOSITORY', repository) : false;
  const bound = named && artifacts ? addCodeBinding(config, 'artifacts', ARTIFACTS_BINDING, "The project's own repository, which Connect your assistant hands out. wiki/stack/employee-project.md") : false;
  const checks = bound && runner ? addCodeBinding(config, 'workflows', { binding: 'CODE_CHECKS', name: runner, script_name: runner, class_name: 'Checks' }, "The check runner's runs, which the app reads for a change saved through it. wiki/stack/employee-project.md") : false;
  return { named, bound, checks };
}

const ARTIFACTS_BINDING = { binding: 'ARTIFACTS', namespace: NAMESPACE };

// Names company knowledge's repository in both Workers' vars and binds the live app alone to the namespace, on either
// route: `ready`, or `missing` with a to-do when the config has no safe place. Changes nothing already right.
function knowledgeInConfig(config, repository, { note, todo }) {
  const named = existsSync(config) ? setVar(config, 'WONG_KNOWLEDGE_REPOSITORY', repository) : false;
  const bound = named ? addCodeBinding(config, 'artifacts', ARTIFACTS_BINDING, "The project's and company knowledge's repositories. wiki/stack/company-knowledge.md") : false;
  if (named === 'updated') note('updated', 'app/wrangler.jsonc WONG_KNOWLEDGE_REPOSITORY');
  if (bound === 'updated') note('updated', 'app/wrangler.jsonc ARTIFACTS');
  if (named && bound) return 'ready';
  todo.push(`add "WONG_KNOWLEDGE_REPOSITORY": "${repository}" to production and staging, and the "artifacts" binding ARTIFACTS for the ${NAMESPACE} namespace to production alone, in app/wrangler.jsonc, as wiki/stack/company-knowledge.md describes`);
  return 'missing';
}

/** The to-do left when a project kept in Cloudflare can be handed out but not yet saved to. */
const saveTodo = (runner) =>
  runner
    ? `add the "workflows" binding CODE_CHECKS for the check runner ${runner} to production alone in app/wrangler.jsonc, so people can save changes through the app, as wiki/stack/employee-project.md describes`
    : 'the install record names no check runner, so people can not save changes through the app yet: run `provision.mjs provision --route artifacts` again, which records it, then `provision.mjs access`';

// Tells the app which project Connect hands out and whether people can save to it: `status` and `save`, each
// `ready` or `missing`, judged on the live app; changes nothing already right. wiki/stack/employee-project.md
async function projectCode(cf, { account, config, repository, artifacts, runner, worker, note, todo }) {
  const { named, bound, checks } = codeInConfig(config, repository, artifacts, runner);
  if (named === 'updated') note('updated', 'app/wrangler.jsonc WONG_CODE_REPOSITORY');
  if (bound === 'updated') note('updated', 'app/wrangler.jsonc ARTIFACTS');
  if (checks === 'updated') note('updated', 'app/wrangler.jsonc CODE_CHECKS');
  if (!named || (artifacts && !bound)) {
    todo.push(`add "WONG_CODE_REPOSITORY" to production and staging${artifacts ? `, and the "artifacts" binding ARTIFACTS for the ${NAMESPACE} namespace to production alone,` : ''} in app/wrangler.jsonc, as wiki/stack/employee-project.md describes`);
    return { status: 'missing', save: 'missing' };
  }
  if (artifacts) {
    if (!checks) todo.push(saveTodo(runner));
    return { status: 'ready', save: checks ? 'ready' : 'missing', kept: 'cloudflare', repository };
  }
  const held = await orNull(() => cf('GET', `/accounts/${account}/workers/scripts/${worker}/secrets`));
  const all = (...names) => Boolean(held?.some((secret) => names.includes(secret.name)));
  if (all(CODE_KEY.name)) return { status: 'ready', save: 'ready', kept: 'github', repository };
  return { status: all(CODE_KEY.name, CODE_KEY.read) ? 'ready' : 'missing', save: 'missing', kept: 'github', repository, key: CODE_KEY.name, url: CODE_KEY.url, steps: CODE_KEY.steps(repository) };
}

/** Notes the owner email in an existing config, or leaves a to-do when the config has no place for it. */
function ownerEmailInConfig(config, email, { note, todo }) {
  const result = setOwnerEmail(config, email);
  if (result === 'updated') note('updated', 'app/wrangler.jsonc WONG_OWNER_EMAIL');
  if (!result) todo.push('add "WONG_OWNER_EMAIL" with the owner sign-in email to the production and staging vars in app/wrangler.jsonc');
}

/** The two `db:migrate:*` scripts, filled with the literal database names, after `build:app`. */
function migrateScripts(dir, n, note) {
  const file = join(dir, 'app', 'package.json');
  const pkg = readJson(file);
  if (!pkg) return;
  const scripts = {
    'db:migrate:staging': `wrangler d1 migrations apply ${n.stagingDb} --remote --env staging`,
    'db:migrate:prod': `wrangler d1 migrations apply ${n.db} --remote`,
  };
  if (Object.entries(scripts).every(([key, value]) => pkg.scripts?.[key] === value)) return;
  const entries = Object.entries(pkg.scripts ?? {}).filter(([key]) => !(key in scripts));
  const at = entries.findIndex(([key]) => key === 'build:app') + 1 || entries.length;
  entries.splice(at, 0, ...Object.entries(scripts));
  pkg.scripts = Object.fromEntries(entries);
  writeJson(file, pkg);
  note('updated', 'app/package.json db:migrate scripts');
}

/** The read-only key's record; an older record's `waiting` list drops off, as staging never takes the key now. */
const recordReadKey = (dir, key, note) => recordComponent(dir, 'cloudflareReadKey', { waiting: undefined, ...key }, note);

/** The read-only key's two policies: its account groups on the account, its zone groups on every zone in it. */
const readKeyPolicies = (account, groups) => [
  ...accountPolicy(account, groups, CLOUDFLARE_READ_KEY.filter((row) => row.scope === 'account')),
  ...accountPolicy(account, groups, CLOUDFLARE_READ_KEY.filter((row) => row.scope === 'zone'), { 'com.cloudflare.api.account.zone.*': '*' }),
];

/** The CI deploy token: made when missing, given any group it lacks, and its value rolled into the GitHub
 * secret when the secret is missing. The value goes straight to `gh` on stdin. */
const deployToken = scopedToken;

// The deploy token's GitHub secret. Only the current deploy.yml and site.yml read it; a commit from before them reads
// the old name at job level, where a branch's own code runs, so the old secret is deleted once the new one is set.
const DEPLOY_SECRET = 'CLOUDFLARE_DEPLOY_TOKEN';
const OLD_DEPLOY_SECRET = 'CLOUDFLARE_API_TOKEN';

/** The first workflow file in `dir` that reads `secrets.<name>`, repo-relative, or null. */
function workflowReading(dir, name) {
  const folder = join(dir, '.github', 'workflows');
  if (!existsSync(folder)) return null;
  const reads = new RegExp(`secrets\\.${name}\\b`);
  const file = readdirSync(folder).sort().find((entry) => /\.ya?ml$/.test(entry) && reads.test(readFileSync(join(folder, entry), 'utf8')));
  return file ? `.github/workflows/${file}` : null;
}

/** The runner's Wrangler config: the pack's template with every placeholder filled, comments dropped. */
export function runnerConfig({ account, repo, runner }, template) {
  return fillConfig(template, { '<runner>': runner, '<account id>': account, '<namespace>': NAMESPACE, '<repo>': repo }, 'check runner');
}

/** A repository of this install in the shared namespace, made when missing, owned by `state[key]`. A same-named one
 * it did not make stops. */
async function repository(cf, account, name, { key = 'delivery', description = 'A WongStack install', state, checkpoint, note, sleep }) {
  const spaces = `/accounts/${account}/artifacts/namespaces`;
  if (!(await retry(() => orNull(() => cf('GET', `${spaces}/${NAMESPACE}`)), sleep, pending))) {
    await cf('POST', spaces, { namespace: NAMESPACE });
    note('created', `Artifacts namespace ${NAMESPACE}`);
  }
  const repos = `${spaces}/${NAMESPACE}/repos`;
  const found = await orNull(() => cf('GET', `${repos}/${name}`));
  const resumed = state[key]?.creating === name;
  const ours = resumed || (found?.id !== undefined && state[key]?.repoId === found.id);
  if (found && !ours) throw new ProvisionError('cloudflare', `this account already has a repository named ${name} that this install did not make; pick another name`);
  if (found && !resumed) note('reused', `repository ${name}`);
  else if (!found) {
    state[key] = { creating: name };
    checkpoint();
  }
  const repo = found ?? (await cf('POST', repos, { name, default_branch: 'main', description }));
  if (!found || resumed) {
    // Creating a repository returns a ready-made token. Nothing keeps it, so it is revoked.
    for (const made of await cf('GET', `${repos}/${name}/tokens?state=active&per_page=100`)) await cf('DELETE', `${spaces}/${NAMESPACE}/tokens/${made.id}`);
    note('created', `repository ${name}`);
  }
  if (state[key]?.repoId !== repo.id) state[key] = { repoId: repo.id };
  checkpoint();
  return repo.remote ?? `https://${account}.artifacts.cloudflare.net/git/${NAMESPACE}/${name}.git`;
}

/** Seconds the token that pushes company knowledge's first commit lives. */
const START_SECONDS = 300;

// Company knowledge's first commit, an empty one on main, pushed from a scratch folder with a five-minute token for
// that repository alone, sent in Git's environment, never an argument. A main that exists is never pushed to.
async function knowledgeStart(cf, account, name, remote, { exec, env, note }) {
  const tokens = `/accounts/${account}/artifacts/namespaces/${NAMESPACE}/tokens`;
  const made = await cf('POST', tokens, { repo: name, scope: 'write', ttl: START_SECONDS });
  const basic = Buffer.from(`x:${String(made.plaintext).split('?')[0]}`).toString('base64');
  const folder = mkdtempSync(join(tmpdir(), 'wong-knowledge-'));
  const header = { GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'http.extraHeader', GIT_CONFIG_VALUE_0: `Authorization: Basic ${basic}` };
  const git = (args, input) => exec('git', ['-C', folder, ...args], { env: { ...env, ...header, GIT_TERMINAL_PROMPT: '0' }, input });
  try {
    await git(['init', '-q', '--bare']);
    if ((await git(['ls-remote', remote, 'refs/heads/main'])).stdout.trim()) return;
    const tree = (await git(['mktree'], '')).stdout.trim();
    const head = (await git([...(await author(git)), 'commit-tree', tree, '-m', 'Start company knowledge'])).stdout.trim();
    await git(['push', remote, `${head}:refs/heads/main`]);
    note('created', `the first, empty commit on ${name}'s main`);
  } finally {
    rmSync(folder, { recursive: true, force: true });
    // A failed revoke stops nothing: the token ends in five minutes anyway.
    if (made.id) await cf('DELETE', `${tokens}/${made.id}`).catch(() => {});
  }
}

/** Company knowledge's repository, on either route: made or reused, started with one empty commit, and recorded. */
async function knowledgeRepository(cf, { account, name, dir, env, exec, state, checkpoint, note, sleep }) {
  const description = "A WongStack install's company knowledge";
  const remote = await step('cloudflare', () => repository(cf, account, name, { key: 'knowledge', description, state, checkpoint, note, sleep }));
  if (!state.knowledge.started) {
    await step('cloudflare', () => knowledgeStart(cf, account, name, remote, { exec, env, note }));
    state.knowledge.started = true;
    checkpoint();
  }
  recordComponent(dir, 'knowledge', { namespace: NAMESPACE, repo: name }, note);
  return { namespace: NAMESPACE, repo: name };
}

/** The runner's bucket, made when missing, with the rule that deletes old snapshots. */
async function snapshotBucket(cf, account, name, buckets, note) {
  if (!buckets) throw new ProvisionError('cloudflare', 'the check runner keeps its working files in R2 storage, which is off on this account; turn R2 on, then run setup again');
  if (buckets.some((b) => b.name === name)) note('reused', `bucket ${name}`);
  else {
    await cf('POST', `/accounts/${account}/r2/buckets`, { name });
    note('created', `bucket ${name}`);
  }
  const rule = { id: 'delete-old-snapshots', enabled: true, conditions: { prefix: '' }, deleteObjectsTransition: { condition: { type: 'Age', maxAge: SNAPSHOT_DAYS * 86_400 } } };
  await cf('PUT', `/accounts/${account}/r2/buckets/${name}/lifecycle`, { rules: [rule] });
}

/** The runner's storage key: an account token for the one bucket's objects. Its id and the SHA-256 of
 * its value are the pair R2 takes, and go straight into the runner's secrets. */
async function storageToken(cf, account, name, bucket, groups, { secretSet, setKeys, note }) {
  const group = groups.find((each) => each.name === STORAGE_TOKEN.name && each.scopes?.includes(STORAGE_TOKEN.scope));
  if (!group) throw new ProvisionError('token', `Cloudflare lists no permission group named ${STORAGE_TOKEN.name}`);
  const base = `/accounts/${account}/tokens`;
  const found = (await cf('GET', `${base}?per_page=100`)).find((t) => t.name === name);
  if (found && secretSet) return note('reused', `storage key ${name}`);
  const policies = [{ effect: 'allow', resources: { [`com.cloudflare.edge.r2.bucket.${account}_default_${bucket}`]: '*' }, permission_groups: [{ id: group.id }] }];
  const made = found ? { id: found.id, value: await cf('PUT', `${base}/${found.id}/value`, {}) } : await cf('POST', base, { name, policies });
  await setKeys(made.id, createHash('sha256').update(made.value).digest('hex'));
  note(found ? 'updated' : 'created', `storage key ${name}`);
}

/** Points `origin` at the repository and Git at the credential helper. An origin set elsewhere stops. */
async function gitRemote(git, account, remote) {
  const origin = (await git(['remote', 'get-url', 'origin']).catch(() => ({ stdout: '' }))).stdout.trim();
  if (origin && origin !== remote) throw new ProvisionError('repo', 'origin already points at another repository; this install keeps its repository in Cloudflare');
  if (!origin) await git(['remote', 'add', 'origin', remote]);
  for (const [key, value] of helperConfig(account)) await git(['config', '--replace-all', key, value]);
}

/** Git's `-c` arguments naming setup as the author where this computer names no one. */
async function author(git) {
  const has = (key) => git(['config', key]).then(() => true, () => false);
  return [...((await has('user.name')) ? [] : ['-c', 'user.name=WongStack setup']), ...((await has('user.email')) ? [] : ['-c', 'user.email=setup@wongstack.invalid'])];
}

/** Main's first commit, an empty one, so a first change has a main to be published onto. A folder
 * with no commit yet starts from it. Never touches a file or an existing commit. */
async function firstPush(git, note, todo) {
  let head = (await git(['ls-remote', 'origin', 'refs/heads/main'])).stdout.split(/\s/)[0];
  const born = await git(['rev-parse', '--verify', '--quiet', 'HEAD']).then(() => true, () => false);
  if (!head && born) return void todo.push('this folder already has commits: push its main to the new repository with `git push origin main`');
  if (!head) {
    const tree = (await git(['mktree'], '')).stdout.trim();
    head = (await git([...(await author(git)), 'commit-tree', tree, '-m', 'Start the project'])).stdout.trim();
    await git(['push', 'origin', `${head}:refs/heads/main`]);
    note('created', 'the first, empty commit on main');
  }
  if (!born) {
    await git(['fetch', 'origin', 'main']);
    await git(['update-ref', 'HEAD', head]);
  }
}

/** The Artifacts route's delivery, in place of the GitHub secrets: the repository, the runner's bucket, `origin`,
 * the check runner deployed with its two keys, the install record, and main's first commit. Safe to run again. */
async function artifactsDelivery(cf, { account, base, token, groups, buckets, deployRows, dir, env, exec, state, checkpoint, note, todo, sleep }) {
  const n = artifactNamesFor(base);
  const git = (args, input) => exec('git', ['-C', dir, ...args], { env, input });
  const remote = await step('cloudflare', () => repository(cf, account, n.repo, { state, checkpoint, note, sleep }));
  await step('cloudflare', () => snapshotBucket(cf, account, n.runner, buckets, note));
  recordComponent(dir, 'delivery', { route: 'artifacts', accountId: account, namespace: NAMESPACE, repo: n.repo, remote, runner: n.runner, workflow: n.runner, bucket: n.runner }, note);
  await step('repo', () => gitRemote(git, account, remote));

  const folder = join(dir, 'scripts', 'check-runner');
  const text = await step('repo', () => runnerConfig({ account, ...n }, readFileSync(join(folder, 'wrangler.template.jsonc'), 'utf8')));
  await installRunner({ folder, shown: 'scripts/check-runner', text, token, account, env, exec, note });
  note('updated', `check runner ${n.runner}`);

  const { held, put } = await workerSecrets(cf, account, n.runner);
  await step('cloudflare', () => deployToken(cf, account, namesFor(base).deploy, deployRows, groups, { secretSet: held.has('CF_TOKEN'), setSecret: (value) => put('CF_TOKEN', value), note, sentTo: 'the check runner' }));
  await step('cloudflare', () => storageToken(cf, account, n.storage, n.runner, groups, {
    secretSet: held.has('R2_ACCESS_KEY_ID') && held.has('R2_SECRET_ACCESS_KEY'),
    setKeys: async (id, secret) => {
      await put('R2_ACCESS_KEY_ID', id);
      await put('R2_SECRET_ACCESS_KEY', secret);
    },
    note,
  }));
  await step('repo', () => firstPush(git, note, todo));
  return { route: 'artifacts', remote, runner: n.runner, monthlyCost: 'about $5 a month for Cloudflare\'s paid plan; check runs beyond what the plan includes are billed by use', pullRequests: false };
}

/** Saves an Access checker token in the primary and this worktree's git-ignored .env, under `prefix`. */
const accessCredentials = (dir, envFile, exec, env) => async ({ client_id, client_secret }, prefix) => {
  if (![client_id, client_secret].every(value => typeof value === 'string' && /^[a-zA-Z0-9_.=-]+$/.test(value))) {
    throw new ProvisionError('access', 'Cloudflare did not return safe verification credentials; run private setup again');
  }
  for (const file of new Set([envFile, join(dir, '.env')])) {
    await step('repo', () => exec('git', ['-C', dirname(file), 'check-ignore', '-q', '.env'], { env }));
    let text = existsSync(file) ? readFileSync(file, 'utf8') : '';
    for (const [key, value] of Object.entries({ [`${prefix}_CLIENT_ID`]: client_id, [`${prefix}_CLIENT_SECRET`]: client_secret })) {
      text = text.split('\n').filter(line => !new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`).test(line)).join('\n');
      text = `${text}${text && !text.endsWith('\n') ? '\n' : ''}${key}=${value}\n`;
    }
    writeFileSync(file, text, { mode: 0o600 });
    chmodSync(file, 0o600);
  }
};

const hasKey = (env, localId) => keyMachine(env.CLOUDFLARE_MEMORY_TOKEN) === localId;
export const KEY_OFF_TODO = 'turn the open-site memory key off: run `node .claude/skills/memory/scripts/memory.mjs migrate-people`, then remove CLOUDFLARE_MEMORY_TOKEN from .env';

/** Drops the open-site memory key's line from `file`, keeping every other line and the file's 0600 mode. */
function removeMemoryKey(file) {
  const text = readFileSync(file, 'utf8');
  writeFileSync(file, text.split('\n').filter(line => !/^\s*(?:export\s+)?CLOUDFLARE_MEMORY_TOKEN\s*=/.test(line)).join('\n'), { mode: 0o600 });
  chmodSync(file, 0o600);
}

/** Stops with `plan` unless the account is on the paid plan, which every install's company knowledge needs. */
async function paidOrStop(cf, account, sleep) {
  if (await step('cloudflare', () => paidPlan(cf, account, sleep))) return;
  throw new ProvisionError('plan', 'this Cloudflare account is not on the Workers Paid plan (about $5 a month), which every install needs to keep company knowledge in Cloudflare; turn it on, then run this again');
}

/** Everything after the one billable ask, under `base`. `keepConfig` leaves an installed repo's committed files alone.
 * `openWithoutLogin` goes on without Access when Cloudflare refuses Zero Trust; a site already private never opens. */
export async function provision({ token, api, fetch, account, repo, base, route = 'github', ownerEmail, teammateEmails, dir = '.', today = isoDate(), keepConfig = false, openWithoutLogin = false, sleep = wait, exec = run, env = process.env, types = bindingTypes }) {
  const cf = cloudflare(token, { api, fetch });
  const n = namesFor(base);
  const report = { base, names: n, r2: false, created: [], reused: [], updated: [], todo: [] };
  const note = (list, what) => report[list].push(what);
  const git = (args) => exec('git', ['-C', dir, ...args], { env });
  const envFile = durableEnv(dir);
  const needsKey = !hasKey(readEnv(envFile), machineId(machineIdFile(env)));
  const loginEmail = ownerIdentity(ownerEmail ?? (await git(['config', 'user.email']).catch(() => ({ stdout: '' }))).stdout);
  // Every install keeps company knowledge in Cloudflare, which needs the paid plan: look before anything is made.
  await paidOrStop(cf, account, sleep);
  const provisionStateFile = await stateFile(dir, exec);
  const state = readJson(provisionStateFile, {});
  if (state.account && (state.account !== account || state.repo !== repo || state.base !== base)) {
    throw new ProvisionError('access', 'private provisioning state belongs to another account or repository');
  }
  Object.assign(state, { base, account, repo });
  const checkpoint = () => writeJson(provisionStateFile, state);
  await step('repo', checkpoint);

  const wasPrivate = Boolean(state.access?.appId || readJson(recordFile(dir))?.components?.access?.appId);
  try {
    report.access = await accessOrganization(cf, { account, base, note });
    report.access.ownerEmail = loginEmail;
    report.access.humanLogin = 'unverified';
  } catch (error) {
    // A flaky connection or a Cloudflare outage is not a refusal: only a refusal opens the site.
    const status = error.cause?.status;
    const transient = status !== undefined && (status === 0 || status === 429 || status >= 500);
    if (!openWithoutLogin || wasPrivate || !(error instanceof AccessSetupError) || transient) throw error;
    report.access = { mode: 'open', reason: 'zero-trust-onboarding', onboardingUrl: `https://one.dash.cloudflare.com/${account}/`, ownerEmail: loginEmail, humanLogin: 'none' };
  }
  const open = report.access.mode === 'open';
  const groups = await step('cloudflare', () => cf('GET', '/user/tokens/permission_groups?per_page=1000'));
  const recordedBucket = readJson(recordFile(dir))?.components?.memory?.bucket ?? null;

  // The memory store: is R2 on, the database, then the bucket.
  const buckets = await step('cloudflare', () => r2Buckets(cf, account));
  report.r2 = buckets !== null;
  const memoryId = await step('cloudflare', () => database(cf, account, n.memory, note));
  let bucket = null;
  if (buckets && (!keepConfig || recordedBucket)) {
    bucket = n.memory;
    if (buckets.some((b) => b.name === bucket)) note('reused', `bucket ${bucket}`);
    else {
      await step('cloudflare', () => cf('POST', `/accounts/${account}/r2/buckets`, { name: bucket }));
      note('created', `bucket ${bucket}`);
    }
  }
  const sub = await step('cloudflare', () => subdomain(cf, account, String(repo).split('/')[0], note));
  if (!open) Object.assign(report.access, await provisionAccess(cf, {
    account, appName: `WongStack ${repo} (${base})`, names: n, subdomain: sub, state, checkpoint, note, today,
    adoptExisting: readJson(recordFile(dir))?.components?.memory?.accountId === account
      && readJson(recordFile(dir))?.components?.memory?.worker === `https://${n.worker}.${sub}.workers.dev/_memory`,
  }));
  await step('repo', () => exec('git', ['-C', dirname(envFile), 'check-ignore', '-q', '.env'], { env }));
  if (!open) report.access = await provisionAccessPolicies(cf, {
    account, ownerEmail: loginEmail, teammateEmails, access: report.access, state, checkpoint, note,
    credentials: readEnv(envFile),
    saveCredentials: accessCredentials(dir, envFile, exec, env),
  });
  if (!keepConfig) {
    const record = readJson(recordFile(dir), {});
    if (!isDeepStrictEqual(record.components?.access, report.access)) {
      writeJson(recordFile(dir), { ...record, components: { ...record.components, access: report.access } });
      note('updated', '.claude/.wong-stack.json components.access');
    }
  }
  const worker = `https://${n.worker}.${sub}.workers.dev/_memory`;
  recordComponent(dir, 'memory', { accountId: account, databaseId: memoryId, database: n.memory, bucket, worker }, note);
  // `sub` was read back from the account; never copy an upstream installation's origin.
  recordComponent(dir, 'companyApi', { origin: `https://${n.worker}.${sub}.workers.dev` }, note);

  // The schema, retried while a new database or a widened token takes effect. Memory uses the owner's company
  // sign-in; only an app with no sign-in yet keeps an admin key in .env.
  const memory = join(dir, '.claude', 'skills', 'memory', 'scripts', 'memory.mjs');
  const admin = { cwd: dir, env: { ...env, CLOUDFLARE_API_TOKEN: token } };
  await step('cloudflare', () => retry(() => exec('node', [memory, 'migrate'], admin), sleep, () => true));
  if (open && needsKey) {
    await step('cloudflare', () => exec('node', [memory, 'member', 'admin'], admin));
    note('created', 'admin machine memory key in .env');
  } else if (open) note('reused', 'admin memory key in .env');

  // The app's databases and config.
  const db = await step('cloudflare', () => database(cf, account, n.db, note));
  const stagingDb = await step('cloudflare', () => database(cf, account, n.stagingDb, note));
  const config = join(dir, 'app', 'wrangler.jsonc');
  if (!keepConfig) {
    if (!existsSync(config)) {
      writeFileSync(config, wranglerConfig({ base, ids: { db, stagingDb, memory: memoryId }, bucket, access: report.access }));
      note('created', 'app/wrangler.jsonc');
    } else {
      if (!open && /"WORKSPACE_LOGIN"/.test(readFileSync(config, 'utf8'))) {
        if (closeOpenConfig(config, report.access)) note('updated', 'app/wrangler.jsonc: private login on, WORKSPACE_LOGIN removed');
        else report.todo.push('fill the CF_ACCESS_* vars from components.access and remove WORKSPACE_LOGIN in app/wrangler.jsonc');
      }
      // Access knows its owner, and each environment its own app, only on a private site; an open config stays as is.
      if (!open && !/"WORKSPACE_LOGIN"/.test(readFileSync(config, 'utf8'))) {
        ownerEmailInConfig(config, loginEmail, { note, todo: report.todo });
        accessInConfig(config, report.access, { note, todo: report.todo });
      }
      if (bucket && !readFileSync(config, 'utf8').includes('MEMORY_BUCKET')) {
        if (addBucketBinding(config, bucket)) note('updated', 'app/wrangler.jsonc MEMORY_BUCKET');
        else report.todo.push(`add MEMORY_BUCKET for ${bucket} to app/wrangler.jsonc`);
      }
    }
    migrateScripts(dir, n, note);
    await liveLine(dir, config, { cf, account, note, todo: report.todo });
  }
  // Private now, so the open-site key goes off in the store and out of .env: memory takes the company sign-in.
  // migrate-people turns keys off only once the install record has the sign-in, which --keep-config never writes.
  if (!open && hasKey(readEnv(envFile), machineId(machineIdFile(env)))) {
    if (keepConfig) report.todo.push(KEY_OFF_TODO);
    else {
      await step('cloudflare', () => exec('node', [memory, 'migrate-people'], admin));
      removeMemoryKey(envFile);
      note('updated', 'memory key turned off; memory uses the company sign-in');
    }
  }

  const rows = DEPLOY_TOKEN.filter((row) => row.when === 'always' || (row.when === 'bucket' && bucket));
  report.memory = { database: n.memory, bucket, worker };
  report.urls = { production: `https://${n.worker}.${sub}.workers.dev`, previews: `https://<branch>-${n.staging}.${sub}.workers.dev` };
  // What Access needs last, on either route: the live app's own key.
  // The deploy token is never reused and gains no Access write.
  const accessKey = async () => {
    if (open) return;
    report.accessKey = await step('cloudflare', () => loginManagementKey(cf, {
      account, name: `${n.worker}-access`, worker: n.worker, policyId: report.access.humanPolicyId,
      staging: { appId: report.access.staging.appId, policyId: report.access.staging.humanPolicyId },
      recorded: readJson(recordFile(dir))?.components?.accessKey,
      policies: () => accountPolicy(account, groups, ACCESS_KEY), state, checkpoint, note,
    }));
    if (report.accessKey.status === 'missing') report.todo.push(ACCESS_KEY_TODO);
    recordComponent(dir, 'accessKey', report.accessKey, note);
    // The Cloudflare look-up key waits for sign-in too: only then does the live Worker exist, with an owner for levels.
    report.cloudflareReadKey = await step('cloudflare', () => cloudflareReadKey(cf, {
      account, name: `${n.worker}-cloudflare-read`, worker: n.worker,
      policies: () => readKeyPolicies(account, groups), state, checkpoint, note,
    }));
    if (report.cloudflareReadKey.status === 'missing') report.todo.push(CLOUDFLARE_READ_KEY_TODO);
    recordReadKey(dir, report.cloudflareReadKey, note);
    if (state.stagingHeld) report.todo.push(PREVIEW_KEYS_TODO);
    // Which project Connect hands out: named for both Workers, bound on the live one when Cloudflare keeps it. Like the
    // owner email, it waits while the config is still open.
    if (!keepConfig && !/"WORKSPACE_LOGIN"/.test(readFileSync(config, 'utf8'))) report.codeKey = await step('cloudflare', () => projectCode(cf, {
      account, config, repository: route === 'artifacts' ? artifactNamesFor(base).repo : githubRepo(`https://github.com/${repo}`),
      artifacts: route === 'artifacts', runner: artifactNamesFor(base).runner, worker: n.worker, note, todo: report.todo,
    }));
    if (report.codeKey) report.knowledge.config = knowledgeInConfig(config, report.knowledge.repo, { note, todo: report.todo });
  };
  const knowledge = async () => {
    report.knowledge = await knowledgeRepository(cf, { account, name: n.knowledge, dir, env, exec, state, checkpoint, note, sleep });
  };
  // The first save then carries types that match this config, not a stray change at publish.
  const refreshTypes = async () => {
    if (keepConfig || !existsSync(config)) return;
    const warning = await types(join(dir, 'app'), exec, env);
    if (warning) (report.warnings ??= []).push(warning);
  };
  if (route === 'artifacts') {
    report.delivery = await artifactsDelivery(cf, { account, base, token, groups, buckets, deployRows: rows, dir, env, exec, state, checkpoint, note, todo: report.todo, sleep });
    await knowledge();
    await accessKey();
    await refreshTypes();
    return report;
  }

  // The deploy token and the two GitHub secrets.
  const gh = (args, input) => exec('gh', [...args, '-R', repo], { cwd: dir, env, input });
  const secrets = (await step('cloudflare', () => gh(['secret', 'list']))).stdout;
  const listed = (name) => new RegExp(`^${name}\\s`, 'm').test(secrets);
  await step('cloudflare', () =>
    deployToken(cf, account, n.deploy, rows, groups, {
      secretSet: listed(DEPLOY_SECRET),
      setSecret: (value) => gh(['secret', 'set', DEPLOY_SECRET], value),
      note,
    }),
  );
  // The roll already made the old secret's value dead. A workflow here that still names it is the person's to
  // rename first; deleting a secret a file still reads can't be undone, so that waits for a rerun.
  if (listed(OLD_DEPLOY_SECRET)) {
    const reader = workflowReading(dir, OLD_DEPLOY_SECRET);
    if (reader) report.todo.push(`${reader} still reads the old GitHub secret ${OLD_DEPLOY_SECRET}, whose value no longer works: make it read ${DEPLOY_SECRET}, then run this step again to delete the old secret`);
    else {
      await step('cloudflare', () => gh(['secret', 'delete', OLD_DEPLOY_SECRET]));
      note('updated', `GitHub secret ${OLD_DEPLOY_SECRET} deleted: the deploy token is ${DEPLOY_SECRET} now`);
    }
  }
  if (!listed('CLOUDFLARE_ACCOUNT_ID')) {
    await step('cloudflare', () => gh(['secret', 'set', 'CLOUDFLARE_ACCOUNT_ID'], account));
    note('created', 'GitHub secret CLOUDFLARE_ACCOUNT_ID');
  }

  await knowledge();
  await accessKey();
  await refreshTypes();
  return report;
}

/** Regenerates `app/worker-configuration.d.ts` as CI's `wong_regenerate_types` does; returns a warning, never throws */
export async function bindingTypes(app, exec = run, env = process.env) {
  try {
    if (!existsSync(join(app, 'node_modules'))) await exec('npm', ['ci', '--no-audit', '--no-fund'], { cwd: app, env });
    await exec('npx', ['--no-install', 'wrangler', 'types'], { cwd: app, env });
    return null;
  } catch (error) {
    return `the app's binding types were not refreshed (${error.message}); run \`npx wrangler types\` in app/ before the first save`;
  }
}

/** Writes each environment's own Access app id and audience; a to-do when the config has no place for them. */
function accessInConfig(config, access, { note, todo }) {
  const results = [['CF_ACCESS_AUD', 'audience'], ['CF_ACCESS_APP_ID', 'appId']].map(([name, field]) => [name, setVar(config, name, [access[field], access.staging[field]])]);
  for (const [name, result] of results) if (result === 'updated') note('updated', `app/wrangler.jsonc ${name}`);
  if (results.some(([, result]) => !result)) todo.push("set each environment's CF_ACCESS_AUD and CF_ACCESS_APP_ID in app/wrangler.jsonc from components.access and its staging");
}

/** Leaves staging only the `keeps` names, by `secrets:push`'s rule, noting the rest before the first delete. A delete
 * refused while a newer preview is uploaded (10215) retries through Wrangler as a new version. */
async function pruneStaging(cf, { account, worker, token, keeps, dir, exec, env, note, state, checkpoint }) {
  const secrets = `/accounts/${account}/workers/scripts/${worker}/secrets`;
  const held = ((await orNull(() => cf('GET', secrets))) ?? []).map((secret) => secret.name);
  const removed = held.filter((name) => !keeps.includes(name));
  notePreviewKeys(state, removed);
  checkpoint();
  for (const name of removed) {
    await cf('DELETE', `${secrets}/${name}`).catch(async (error) => {
      if (error.status === 404) return;
      if (!error.codes?.includes(10215)) throw error;
      const args = ['--no-install', 'wrangler', 'versions', 'secret', 'delete', name, '--env', 'staging'];
      await exec('npx', args, { cwd: join(dir, 'app'), env: { ...env, CLOUDFLARE_API_TOKEN: token, CLOUDFLARE_ACCOUNT_ID: account } });
    });
    note('updated', `${worker}: removed ${name}, which app/.dev.vars.staging does not declare`);
  }
}

/** The to-do for keys staging held: branch code could read them, and preview versions made before keep their copies. */
const PREVIEW_KEYS_TODO = "previews held the live app's keys before they got their own sign-in: run `provision.mjs access`, which removes them from previews and names those to change";
const rotateTodo = (names) => `previews held ${names.join(', ')}, which unpublished changes could read, and preview links made before now keep their copies until each key changes: rotate the GitHub key and every business key among them, then run \`npm run secrets:push\``;

// What Access needs on an older install: previews on their own sign-in, apart from the live app's, the owner's email
// in both Workers' vars, the two keys, staging left with only its own file's keys, and the project's name.
export async function accessSetup({ token, api, fetch, account, ownerEmail, makeKnowledge = false, dir = '.', exec = run, env = process.env, sleep = wait }) {
  const cf = cloudflare(token, { api, fetch });
  const report = { created: [], reused: [], updated: [], todo: [] };
  const note = (list, what) => report[list].push(what);
  const { access, delivery, knowledge: recorded } = readJson(recordFile(dir))?.components ?? {};
  const [worker, staging] = (access?.workers ?? []).map((each) => each.name);
  if (!access?.appId || !access.humanPolicyId || !worker || !staging) throw new ProvisionError('repo', 'this repo has no private sign-in on record; run provision first');
  const email = ownerIdentity(ownerEmail ?? access.ownerEmail);
  const provisionStateFile = await stateFile(dir, exec);
  const state = readJson(provisionStateFile, {});
  const checkpoint = () => writeJson(provisionStateFile, state);
  // The record names what this install owns, so a clone with no provisioning state still finds the same apps.
  const { appId, audience, workers, humanPolicyId, machinePolicyId, serviceTokenId } = access;
  if (state.access?.appId !== appId) state.access = { appId, audience, workers, humanPolicyId, machinePolicyId, serviceTokenId };
  state.access.staging ??= access.staging;
  state.workers ??= {};
  for (const each of workers) state.workers[each.name] ??= { name: each.name, id: each.id };
  const root = `/accounts/${account}`;
  const { name: appName } = await step('cloudflare', () => cf('GET', `${root}/access/apps/${appId}`));
  const { subdomain } = await step('cloudflare', () => cf('GET', `${root}/workers/subdomain`));
  await step('cloudflare', () => provisionAccess(cf, { account, appName, names: { worker, staging }, subdomain, state, checkpoint, note, today: isoDate(), adoptExisting: true }));
  const envFile = durableEnv(dir);
  const done = await step('cloudflare', () => provisionAccessPolicies(cf, {
    account, ownerEmail: email, access: { ...access, ...state.access }, state, checkpoint, note, keepLiveChecker: true,
    credentials: readEnv(envFile), saveCredentials: accessCredentials(dir, envFile, exec, env),
  }));
  recordComponent(dir, 'access', { ...done, ownerEmail: email }, note);
  const config = join(dir, 'app', 'wrangler.jsonc');
  if (existsSync(config)) {
    ownerEmailInConfig(config, email, { note, todo: report.todo });
    if (!/"WORKSPACE_LOGIN"/.test(readFileSync(config, 'utf8'))) accessInConfig(config, done, { note, todo: report.todo });
  }
  const keeps = stagingKeeps(secretsDir(join(dir, 'app'), dir).dir);
  await step('cloudflare', () => pruneStaging(cf, { account, worker: staging, token, keeps, dir, exec, env, note, state, checkpoint }));
  // Named from what staging held at the split, so a rerun after a stop still names them; setup rolls its own read key.
  const exposed = (state.stagingHeld ?? []).filter((name) => name !== CLOUDFLARE_READ_SECRET && !keeps.includes(name));
  if (exposed.length) report.todo.push(rotateTodo(exposed));
  const key = await step('cloudflare', () => loginManagementKey(cf, {
    account, name: `${worker}-access`, worker, policyId: done.humanPolicyId, staging: { appId: done.staging.appId, policyId: done.staging.humanPolicyId },
    recorded: readJson(recordFile(dir))?.components?.accessKey, state, note, checkpoint,
    policies: async () => accountPolicy(account, await cf('GET', '/user/tokens/permission_groups?per_page=1000'), ACCESS_KEY),
  }));
  if (key.status === 'missing') report.todo.push(ACCESS_KEY_TODO);
  const readKey = await step('cloudflare', () => cloudflareReadKey(cf, {
    account, name: `${worker}-cloudflare-read`, worker, state, note, checkpoint,
    policies: async () => readKeyPolicies(account, await cf('GET', '/user/tokens/permission_groups?per_page=1000')),
  }));
  if (readKey.status === 'missing') report.todo.push(CLOUDFLARE_READ_KEY_TODO);
  const artifacts = delivery?.route === 'artifacts';
  const origin = artifacts ? '' : (await exec('git', ['-C', dir, 'remote', 'get-url', 'origin']).catch(() => ({ stdout: '' }))).stdout;
  const codeKey = await step('cloudflare', () => projectCode(cf, {
    account, config, repository: artifacts ? delivery.repo : (githubRepo(origin) ?? githubRepo(`https://github.com/${state.repo}`)),
    artifacts, runner: delivery?.workflow, worker, note, todo: report.todo,
  }));
  // An install from before company knowledge gets its repository only when asked: it needs the paid plan.
  if (!recorded && makeKnowledge) await paidOrStop(cf, account, sleep);
  const made = !recorded && makeKnowledge ? await knowledgeRepository(cf, { account, name: namesFor(worker).knowledge, dir, env, exec, state, checkpoint, note, sleep }) : null;
  const knowledge = recorded ?? made;
  if (knowledge) knowledge.config = knowledgeInConfig(config, knowledge.repo, { note, todo: report.todo });
  recordComponent(dir, 'accessKey', key, note);
  recordReadKey(dir, readKey, note);
  if (state.stagingHeld) {
    delete state.stagingHeld;
    checkpoint();
  }
  return { ...report, ownerEmail: email, accessKey: key, cloudflareReadKey: readKey, codeKey, ...(knowledge && { knowledge }) };
}

const USAGE = `usage: provision.mjs <command> [--dir <repo>] [--account <id>] [--route github|artifacts]
  widen                                   grant the token a normal provision's groups, then wait until they work
  accounts                                list the accounts the token sees
  plan                                    say which route a new install takes, artifacts on Mac or Linux, else github,
                                          and the plan; reason free-plan means every route stops; creates nothing
  names --repo <owner/name>               derive the names; report each as free, ours, or taken, and the first free base
  provision --repo <owner/name> --base <base> [--owner-email <email>] [--keep-config] [--open-without-login]
                                          make or reuse the memory store, databases, config, and deploy token;
                                          --open-without-login goes on, open, when Zero Trust needs onboarding
  access [--owner-email <email>] [--knowledge]
                                          on an installed repo with sign-in on: give previews their own sign-in, with
                                          the same people and their own checker in .env (CF_ACCESS_STAGING_*), apart
                                          from the live app's; write each Worker's own Access ids to app/wrangler.jsonc;
                                          let memory and git past the sign-in wall; put the owner's email in both
                                          Workers' vars; leave staging only app/.dev.vars.staging's keys; give the live app
                                          its own key for both sign-in lists and the read-only key for Cloudflare
                                          look-ups. It also names the project Connect your assistant hands out:
                                          codeKey's status is ready or missing, and its save says whether people can
                                          save changes through the app. On GitHub a missing one comes with the
                                          owner's steps for the one key that does both, which Access asks for later.
                                          It binds company knowledge on record; --knowledge makes it when missing
Both routes make company knowledge's repository and need the paid plan. --route artifacts keeps the project in
Cloudflare with no GitHub: widen adds its groups, names checks its names, and provision makes the repository and
the check runner in place of the GitHub secrets.
--dir is the target repo (default: here). The token is CLOUDFLARE_API_TOKEN and the account CLOUDFLARE_ACCOUNT_ID,
from the environment or the target's .env. Each command prints one JSON report, never a token.`;

const NEEDS = { widen: [], accounts: [], plan: ['account'], names: ['account', 'repo'], provision: ['account', 'repo', 'base'], access: ['account'] };

/** Runs one command and returns the exit code: 0 done, 1 stopped (with a JSON reason), 2 usage. */
export async function cli(argv, { env = process.env, out = console.log, err = console.error, fetch, sleep } = {}) {
  let parsed;
  try {
    parsed = parseArgs({
      args: argv,
      options: { dir: { type: 'string' }, account: { type: 'string' }, route: { type: 'string' }, repo: { type: 'string' }, base: { type: 'string' }, 'owner-email': { type: 'string' }, 'keep-config': { type: 'boolean' }, 'open-without-login': { type: 'boolean' }, knowledge: { type: 'boolean' }, help: { type: 'boolean' } },
      allowPositionals: true,
      strict: true,
    });
  } catch (error) {
    err(`${error.message}\n${USAGE}`);
    return 2;
  }
  const { values, positionals } = parsed;
  if (values.help) {
    out(USAGE);
    return 0;
  }
  const [command, ...extra] = positionals;
  if (!(command in NEEDS) || extra.length) {
    err(command ? `unknown command: ${[command, ...extra].join(' ')}\n${USAGE}` : USAGE);
    return 2;
  }
  if (!['github', 'artifacts', undefined].includes(values.route)) {
    err(`--route is github or artifacts\n${USAGE}`);
    return 2;
  }
  const dir = resolve(values.dir ?? '.');
  const fileEnv = readEnv(join(dir, '.env'));
  const token = env.CLOUDFLARE_API_TOKEN || fileEnv.CLOUDFLARE_API_TOKEN;
  const options = { ...values, account: values.account || env.CLOUDFLARE_ACCOUNT_ID || fileEnv.CLOUDFLARE_ACCOUNT_ID };
  const missing = NEEDS[command].filter((key) => !options[key]);
  if (missing.length) {
    err(`${command} needs ${missing.map((key) => `--${key}`).join(' and ')}\n${USAGE}`);
    return 2;
  }
  const stop = (reason, cause) => {
    out(JSON.stringify({ error: { reason, cause } }, null, 2));
    err(`provision: ${cause}`);
    return 1;
  };
  if (!token) return stop('token', 'CLOUDFLARE_API_TOKEN is not set in the environment or the target .env');
  if (options.account && !ACCOUNT.test(options.account)) return stop('token', 'the account id is not 32 hex characters');
  const common = { token, api: env.WONG_CLOUDFLARE_API, fetch, account: options.account, repo: options.repo, route: values.route ?? 'github', dir, env, ...(sleep && { sleep }) };
  const commands = {
    widen: () => widen(common),
    accounts: () => accounts(common),
    plan: () => plan(common),
    names: () => names(common),
    provision: () => provision({ ...common, base: safeName(options.base), ownerEmail: values['owner-email'], keepConfig: Boolean(values['keep-config']), openWithoutLogin: Boolean(values['open-without-login']) }),
    access: () => accessSetup({ ...common, ownerEmail: values['owner-email'], makeKnowledge: Boolean(values.knowledge) }),
  };
  try {
    out(JSON.stringify(await commands[command](), null, 2));
    return 0;
  } catch (error) {
    return stop(error.reason ?? 'cloudflare', error.message);
  }
}

if (isMain(import.meta.url)) process.exitCode = await cli(process.argv.slice(2));
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall