@rness/cli 0.6.1 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/fs.ts","../src/core/pm.ts","../src/core/auth.ts","../src/core/device-flow.ts","../src/core/github.ts","../src/core/github-oauth-provider.ts","../src/core/remote.ts","../src/core/git.ts","../src/core/manifest.ts","../src/core/repos.ts","../src/core/terminal.ts","../src/core/transport.ts","../src/core/style.ts","../src/core/workspace.ts","../src/report.ts","../src/core/block.ts","../src/core/frontmatter.ts","../src/core/collect.ts","../src/core/scope.ts","../src/core/context.ts","../src/core/merge.ts","../src/commands/sync.ts","../src/core/progress.ts","../src/core/ui.ts","../src/commands/add.ts","../src/commands/context.ts","../src/version.ts","../src/core/delegate.ts","../src/core/scaffold.ts","../src/core/scaffold-copy.ts","../src/commands/login.ts","../src/core/setup-git.ts","../src/commands/create.ts","../src/core/new-workspace.ts","../src/core/pinned.ts","../src/core/sync-blocks.ts","../src/commands/create-blank.ts","../src/commands/logout.ts","../src/commands/upgrade.ts","../src/core/blocks.ts","../src/core/contract.ts","../src/commands/validate.ts","../src/cli.ts","../src/commands/git-credential.ts","../src/core/catch-up.ts"],"sourcesContent":["import {\n access,\n lstat,\n readFile,\n rename,\n rm,\n writeFile,\n} from 'node:fs/promises'\nimport { basename, dirname, join } from 'node:path'\n\nexport async function exists(p: string): Promise<boolean> {\n try {\n await access(p)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * True when `p` is itself a symbolic link (the link is not followed). False\n * when it does not exist. Callers use it to leave a `CLAUDE.md → AGENTS.md`\n * link alone: reading follows the link and the atomic rename would replace it.\n */\nexport async function isSymlink(p: string): Promise<boolean> {\n try {\n return (await lstat(p)).isSymbolicLink()\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw e\n }\n}\n\n/** File content, or null when the file does not exist; any other error propagates. */\nexport async function readOrNull(p: string): Promise<string | null> {\n try {\n return await readFile(p, 'utf8')\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw e\n }\n}\n\nlet sequence = 0\n\n/** Write to a temporary file in the same directory, then rename over the target. */\nexport async function writeFileAtomic(p: string, text: string): Promise<void> {\n sequence += 1\n const tmp = join(dirname(p), `.${basename(p)}.${process.pid}.${sequence}.tmp`)\n await writeFile(tmp, text, 'utf8')\n try {\n await rename(tmp, p)\n } catch (e) {\n await rm(tmp, { force: true }).catch(() => undefined)\n throw e\n }\n}\n","import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\n\nconst execFileP = promisify(execFile)\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun'\nexport const PACKAGE_MANAGERS: readonly PackageManager[] = [\n 'npm',\n 'pnpm',\n 'yarn',\n 'bun',\n]\n\nexport function isPackageManager(value: string): value is PackageManager {\n return (PACKAGE_MANAGERS as readonly string[]).includes(value)\n}\n\n/** The manager that launched us (`npm_config_user_agent`: `pnpm/12.2.1 npm/? node/…`), else npm. */\nexport function detectPackageManager(\n userAgent: string = process.env['npm_config_user_agent'] ?? ''\n): PackageManager {\n const name = userAgent.split('/')[0] ?? ''\n return isPackageManager(name) ? name : 'npm'\n}\n\nfunction firstLine(text: string): string {\n return (\n text\n .split('\\n')\n .find((l) => l.trim() !== '')\n ?.trim() ?? 'unknown error'\n )\n}\n\nexport async function packageManagerVersion(\n pm: PackageManager\n): Promise<string> {\n try {\n const { stdout } = await execFileP(pm, ['--version'])\n return stdout.trim()\n } catch (e) {\n throw new Error(`${pm} is not available on PATH`, { cause: e })\n }\n}\n\n/**\n * The rness CLI run through `pm`, without a global install: what the next\n * steps of `create` are written with, so they work on the machine that ran it.\n * Inside a workspace the fetched copy hands over to the pinned one. Yarn 1 has\n * no `dlx`, and an unknown yarn may be one: npx comes with Node.\n */\nexport function rnessRunner(\n pm: PackageManager,\n version: string | null\n): string {\n if (pm === 'pnpm') return 'pnpm dlx @rness/cli'\n if (pm === 'bun') return 'bunx @rness/cli'\n if (pm === 'yarn' && Number(version?.split('.')[0]) >= 2)\n return 'yarn dlx @rness/cli'\n return 'npx @rness/cli'\n}\n\n/**\n * The rness command as the user can type it again, for every hint and next\n * step: launched through a package manager — npx, pnpm dlx, yarn dlx, bunx,\n * `pnpm create`, a package script, which all set `npm_config_user_agent` —\n * that manager's runner; else the `rness` they typed, a global install.\n */\nexport function rnessCommand(env: NodeJS.ProcessEnv = process.env): string {\n const agent = env['npm_config_user_agent'] ?? ''\n if (agent === '') return 'rness'\n const pm = detectPackageManager(agent)\n const [name, version] = (agent.split(' ')[0] ?? '').split('/')\n return rnessRunner(pm, name === pm ? (version ?? null) : null)\n}\n\nconst BARE_NPM_CODE = /^npm (error|ERR!) code \\S+$/\n\n/**\n * The line of a failed install worth showing. npm leads with its error code\n * (`npm error code ETARGET`) and says what is wrong on the next line\n * (`…No matching version found for @rness/cli@0.4.0.`): that one is kept. The\n * code is shown only when nothing follows it.\n */\nexport function installErrorLine(stderr: string): string {\n const lines = stderr\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l !== '')\n return lines.find((l) => !BARE_NPM_CODE.test(l)) ?? firstLine(stderr)\n}\n\nconst FROZEN: Record<PackageManager, readonly string[]> = {\n npm: ['ci'],\n pnpm: ['install', '--frozen-lockfile'],\n yarn: ['install', '--immutable'],\n bun: ['install', '--frozen-lockfile'],\n}\n\n/** The install that refuses to touch a committed lockfile (spec 0008 §4). */\nexport function frozenArgs(pm: PackageManager): string[] {\n return [...FROZEN[pm]]\n}\n\n/** `<pm> install` in `dir`; output is swallowed, failure is one line. */\nexport async function installDependencies(\n pm: PackageManager,\n dir: string,\n opts: { frozen?: boolean } = {}\n): Promise<void> {\n const args = opts.frozen === true ? frozenArgs(pm) : ['install']\n try {\n await execFileP(pm, args, { cwd: dir, maxBuffer: 16 * 1024 * 1024 })\n } catch (e) {\n const err = e as { stderr?: string; message: string }\n throw new Error(\n `${pm} ${args.join(' ')} failed in ${dir}: ${installErrorLine(err.stderr ?? err.message)}`,\n { cause: e }\n )\n }\n}\n","import { chmod, mkdir, open, readFile, rm, stat } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\nimport {\n RefreshRejected,\n type TokenSet,\n refreshTokenSet,\n} from './device-flow.ts'\nimport { writeFileAtomic } from './fs.ts'\nimport { rnessCommand } from './pm.ts'\n\n// Where the GitHub login lives (spec 0004 §1): one file, readable by its\n// owner only. No keychain: that needs a native dependency.\n\nexport interface StoredLogin {\n login: string\n tokens: TokenSet\n}\n\n/** `$XDG_CONFIG_HOME/rness`, else `~/.config/rness`; `%APPDATA%\\rness` on Windows. */\nexport function configDir(): string {\n const xdg = process.env['XDG_CONFIG_HOME']\n if (xdg !== undefined && xdg !== '') return join(xdg, 'rness')\n const appData = process.env['APPDATA']\n if (process.platform === 'win32' && appData !== undefined && appData !== '')\n return join(appData, 'rness')\n return join(homedir(), '.config', 'rness')\n}\n\nconst authFile = (): string => join(configDir(), 'auth.json')\nconst lockFile = (): string => join(configDir(), 'auth.lock')\n\nfunction isTokenSet(v: unknown): v is TokenSet {\n if (v === null || typeof v !== 'object') return false\n const t = v as Record<string, unknown>\n return typeof t['accessToken'] === 'string' && t['accessToken'] !== ''\n}\n\nexport async function readAuth(): Promise<StoredLogin | null> {\n try {\n const parsed: unknown = JSON.parse(await readFile(authFile(), 'utf8'))\n const entry =\n parsed !== null && typeof parsed === 'object'\n ? (parsed as Record<string, unknown>)['github.com']\n : undefined\n if (entry === null || typeof entry !== 'object') return null\n const { login, tokens } = entry as Record<string, unknown>\n if (typeof login !== 'string' || !isTokenSet(tokens)) return null\n return {\n login,\n tokens: {\n accessToken: tokens.accessToken,\n expiresAt: tokens.expiresAt ?? null,\n refreshToken: tokens.refreshToken ?? null,\n refreshExpiresAt: tokens.refreshExpiresAt ?? null,\n scopes: tokens.scopes ?? '',\n },\n }\n } catch {\n return null\n }\n}\n\nexport async function writeAuth(login: StoredLogin): Promise<void> {\n const dir = configDir()\n await mkdir(dir, { recursive: true, mode: 0o700 })\n const file = authFile()\n await writeFileAtomic(\n file,\n `${JSON.stringify({ 'github.com': login }, null, 2)}\\n`\n )\n await chmod(file, 0o600)\n}\n\nexport async function clearAuth(): Promise<void> {\n await rm(authFile(), { force: true })\n}\n\nexport type TokenSource = 'GITHUB_TOKEN' | 'GH_TOKEN' | 'login'\n\nexport interface ResolvedToken {\n token: string\n source: TokenSource\n /** Known for a stored login only. */\n login: string | null\n}\n\n/** The token the environment provides, which wins over the stored login (CI, scripts). */\nexport function envToken(): ResolvedToken | null {\n for (const source of ['GITHUB_TOKEN', 'GH_TOKEN'] as const) {\n const token = process.env[source]\n if (token !== undefined && token !== '')\n return { token, source, login: null }\n }\n return null\n}\n\n/** Refresh when the access token has less than this left. */\nconst REFRESH_MARGIN_MS = 5 * 60_000\nconst LOCK_WAIT_MS = 10_000\nconst LOCK_STALE_MS = 30_000\n\nexport interface ResolveDeps {\n now?: () => number\n /** One line for the user when the login turns out to be over. */\n notify?: (line: string) => void\n}\n\nconst fresh = (tokens: TokenSet, now: number): boolean =>\n tokens.expiresAt === null || tokens.expiresAt - now > REFRESH_MARGIN_MS\n\n/**\n * Hold `auth.lock` while `work` runs. A refresh token is single-use and git\n * calls `rness git-credential` in parallel: two refreshes at once would\n * invalidate each other. Null when the lock could not be had in time.\n */\nasync function withLock<T>(work: () => Promise<T>): Promise<T | null> {\n await mkdir(configDir(), { recursive: true, mode: 0o700 })\n const file = lockFile()\n const deadline = Date.now() + LOCK_WAIT_MS\n for (;;) {\n try {\n const handle = await open(file, 'wx')\n await handle.close()\n break\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e\n const age = await stat(file).then(\n (s) => Date.now() - s.mtimeMs,\n () => 0\n )\n if (age > LOCK_STALE_MS) await rm(file, { force: true })\n else if (Date.now() > deadline) return null\n else await new Promise<void>((r) => setTimeout(r, 50))\n }\n }\n try {\n return await work()\n } finally {\n await rm(file, { force: true })\n }\n}\n\n/**\n * The GitHub token to act with: `GITHUB_TOKEN`, then `GH_TOKEN`, then the\n * stored login — refreshed when it is about to expire. Null when there is\n * none. A network failure during the refresh never ends the login: an\n * offline `git pull` must not log anyone out.\n */\nexport async function resolveToken(\n deps: ResolveDeps = {}\n): Promise<ResolvedToken | null> {\n const env = envToken()\n if (env !== null) return env\n const now = deps.now ?? Date.now\n const stored = await readAuth()\n if (stored === null) return null\n const answer = (s: StoredLogin): ResolvedToken => ({\n token: s.tokens.accessToken,\n source: 'login',\n login: s.login,\n })\n if (fresh(stored.tokens, now())) return answer(stored)\n\n const refreshed = await withLock(async (): Promise<StoredLogin | null> => {\n // Another process may have renewed it while this one waited.\n const current = await readAuth()\n if (current === null) return null\n if (fresh(current.tokens, now())) return current\n if (current.tokens.refreshToken === null) return null\n try {\n const tokens = await refreshTokenSet(current.tokens.refreshToken, now)\n const next = { login: current.login, tokens }\n await writeAuth(next)\n return next\n } catch (e) {\n if (e instanceof RefreshRejected) {\n await clearAuth()\n ;(deps.notify ?? ((l) => process.stderr.write(`${l}\\n`)))(\n `your GitHub login expired; run ${rnessCommand()} login`\n )\n return null\n }\n // Offline: keep the login, and the token while it is still valid.\n const expiresAt = current.tokens.expiresAt\n return expiresAt !== null && expiresAt > now() ? current : null\n }\n })\n return refreshed === null ? null : answer(refreshed)\n}\n","// GitHub's OAuth device flow (spec 0004 §2): no client secret, no redirect,\n// and it works where there is no local browser. Refreshing a token obtained\n// this way needs no secret either (GitHub documentation, read 2026-09-19).\n\n/** The OAuth App \"Rness\" of the rness-dev organization. Public by nature. */\nconst GITHUB_CLIENT_ID = 'Ov23liv1ia2UWeWttsOK'\nconst GITHUB_WEB = 'https://github.com'\nexport const SCOPES = 'repo read:org'\n\nexport function clientId(): string {\n return process.env['RNESS_GITHUB_CLIENT_ID'] ?? GITHUB_CLIENT_ID\n}\n\n/** `https://github.com`; `RNESS_GITHUB_WEB` overrides it in tests. */\nexport function webBase(): string {\n return (process.env['RNESS_GITHUB_WEB'] ?? GITHUB_WEB).replace(/\\/+$/, '')\n}\n\nexport interface DeviceCode {\n deviceCode: string\n userCode: string\n verificationUri: string\n /** Seconds. */\n expiresIn: number\n interval: number\n}\n\nexport interface TokenSet {\n accessToken: string\n /** Epoch milliseconds; null for a token that does not expire. */\n expiresAt: number | null\n refreshToken: string | null\n refreshExpiresAt: number | null\n scopes: string\n}\n\n/** GitHub said no: the message is one line for the user. */\nexport class LoginError extends Error {}\n/** GitHub refused the refresh token: the login is over. Not a network error. */\nexport class RefreshRejected extends Error {}\n\nfunction reason(e: unknown): string {\n if (e instanceof Error) {\n return e.name === 'TimeoutError' ? 'timed out' : e.message\n }\n return String(e)\n}\n\nasync function post(\n path: string,\n params: Record<string, string>\n): Promise<Record<string, unknown>> {\n let res: Response\n try {\n res = await fetch(`${webBase()}${path}`, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'User-Agent': 'rness-cli',\n },\n body: new URLSearchParams(params).toString(),\n signal: AbortSignal.timeout(15_000),\n })\n } catch (e) {\n throw new Error(`cannot reach github.com: ${reason(e)}`, { cause: e })\n }\n let body: unknown\n try {\n body = await res.json()\n } catch (e) {\n throw new Error(`github.com answered ${res.status} for ${path}`, {\n cause: e,\n })\n }\n if (body === null || typeof body !== 'object')\n throw new Error(`github.com answered an unexpected body for ${path}`)\n return body as Record<string, unknown>\n}\n\nconst str = (v: unknown): string | null => (typeof v === 'string' ? v : null)\nconst num = (v: unknown): number | null =>\n typeof v === 'number' && Number.isFinite(v) ? v : null\n\nfunction tokenSet(body: Record<string, unknown>, now: number): TokenSet | null {\n const accessToken = str(body['access_token'])\n if (accessToken === null) return null\n const expiresIn = num(body['expires_in'])\n const refreshIn = num(body['refresh_token_expires_in'])\n return {\n accessToken,\n expiresAt: expiresIn === null ? null : now + expiresIn * 1000,\n refreshToken: str(body['refresh_token']),\n refreshExpiresAt: refreshIn === null ? null : now + refreshIn * 1000,\n scopes: str(body['scope']) ?? '',\n }\n}\n\nexport async function requestDeviceCode(): Promise<DeviceCode> {\n const id = clientId()\n if (id === '')\n throw new LoginError(\n 'rness has no GitHub client ID yet; set RNESS_GITHUB_CLIENT_ID'\n )\n const body = await post('/login/device/code', {\n client_id: id,\n scope: SCOPES,\n })\n const deviceCode = str(body['device_code'])\n const userCode = str(body['user_code'])\n const verificationUri = str(body['verification_uri'])\n if (deviceCode === null || userCode === null || verificationUri === null) {\n const error = str(body['error'])\n throw new LoginError(\n error === 'device_flow_disabled'\n ? 'the device flow is not enabled on the rness GitHub app'\n : `github.com refused to start the login${error === null ? '' : ` (${error})`}`\n )\n }\n return {\n deviceCode,\n userCode,\n verificationUri,\n expiresIn: num(body['expires_in']) ?? 900,\n interval: num(body['interval']) ?? 5,\n }\n}\n\nexport interface PollDeps {\n sleep?: (ms: number) => Promise<void>\n now?: () => number\n}\n\n/** Ask every `interval` seconds until the user approved, refused, or the code expired. */\nexport async function pollForToken(\n code: DeviceCode,\n deps: PollDeps = {}\n): Promise<TokenSet> {\n const sleep =\n deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))\n const now = deps.now ?? Date.now\n const deadline = now() + code.expiresIn * 1000\n let interval = code.interval\n for (;;) {\n await sleep(interval * 1000)\n const body = await post('/login/oauth/access_token', {\n client_id: clientId(),\n device_code: code.deviceCode,\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n })\n const tokens = tokenSet(body, now())\n if (tokens !== null) return tokens\n const error = str(body['error'])\n if (error === 'authorization_pending') {\n if (now() > deadline)\n throw new LoginError('the code expired before it was approved')\n continue\n }\n if (error === 'slow_down') {\n interval = (num(body['interval']) ?? interval) + 5\n continue\n }\n if (error === 'expired_token')\n throw new LoginError('the code expired before it was approved')\n if (error === 'access_denied')\n throw new LoginError('the login was cancelled on github.com')\n throw new LoginError(`github.com refused the login (${error ?? 'unknown'})`)\n }\n}\n\n/** A new token set for a refresh token. `RefreshRejected` when GitHub says the login is over. */\nexport async function refreshTokenSet(\n refreshToken: string,\n now: () => number = Date.now\n): Promise<TokenSet> {\n const body = await post('/login/oauth/access_token', {\n client_id: clientId(),\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n })\n const tokens = tokenSet(body, now())\n if (tokens !== null) return tokens\n throw new RefreshRejected(str(body['error']) ?? 'refused')\n}\n","import { rnessCommand } from './pm.ts'\n\n/** The public GitHub REST API; `--github-api` overrides it in tests. */\nexport const DEFAULT_GITHUB_API = 'https://api.github.com'\n\n/** Guards against a server that always answers `rel=\"next\"`. */\nexport const MAX_PAGES = 50\nexport const PER_PAGE = 100\n\nconst addLater = (): string =>\n `; add repositories later with ${rnessCommand()} add <repo>`\n\nexport interface OrgRepository {\n name: string\n private: boolean\n archived: boolean\n}\n\nexport interface RepositoryListing {\n repositories: OrgRepository[]\n /**\n * Which endpoint answered. `/users/<name>/repos` lists a personal account's\n * public repositories only, whatever the token; `self` is `/user/repos`, the\n * logged-in user's own account, private repositories included.\n */\n owner: 'org' | 'user' | 'self'\n /** `MAX_PAGES` stopped the listing while GitHub still announced a next page. */\n truncated: boolean\n}\n\nexport interface ListRepositoriesOptions {\n /** Sent as `Authorization: Bearer <token>` when given; without it only public repositories are listed. */\n token?: string | undefined\n apiBase?: string\n /** Per request. */\n timeoutMs?: number\n /**\n * The login the token belongs to, asked only when `owner` turns out not to\n * be an organization: its own account is listed through `/user/repos`.\n */\n self?: () => Promise<string | null>\n}\n\nconst NEXT = /<[^>]*>\\s*;\\s*rel=\"next\"/\n\nfunction isRepository(value: unknown): value is OrgRepository {\n if (value === null || typeof value !== 'object') return false\n const r = value as Record<string, unknown>\n return (\n typeof r['name'] === 'string' &&\n typeof r['private'] === 'boolean' &&\n typeof r['archived'] === 'boolean'\n )\n}\n\nfunction reason(e: unknown): string {\n // undici reports every network failure as `TypeError: fetch failed`; the\n // useful part (ECONNREFUSED, ENOTFOUND, …) is its cause.\n if (e instanceof Error && e.cause instanceof Error) return e.cause.message\n return e instanceof Error ? e.message : String(e)\n}\n\ninterface Page {\n status: number\n headers: Headers\n body: unknown\n}\n\nasync function getPage(\n url: string,\n headers: Record<string, string>,\n timeoutMs: number\n): Promise<Page> {\n const signal = AbortSignal.timeout(timeoutMs)\n let res: Response\n try {\n res = await fetch(url, { headers, signal })\n } catch (e) {\n throw new Error(`cannot reach the GitHub API: ${reason(e)}`, { cause: e })\n }\n if (!res.ok) {\n // Drain the body so the connection is released; its content is not used.\n await res.body?.cancel().catch(() => undefined)\n return { status: res.status, headers: res.headers, body: undefined }\n }\n let text: string\n try {\n text = await res.text()\n } catch (e) {\n throw new Error(`cannot reach the GitHub API: ${reason(e)}`, { cause: e })\n }\n try {\n return { status: res.status, headers: res.headers, body: JSON.parse(text) }\n } catch (e) {\n throw new Error(\n `GitHub API answered invalid JSON for ${new URL(url).pathname}`,\n { cause: e }\n )\n }\n}\n\nfunction httpError(page: Page, path: string): Error {\n const cause = { status: page.status, path }\n if (page.status === 401)\n return new Error('GitHub rejected the token (401)', { cause })\n // GitHub signals a primary rate limit with 403 and no remaining requests,\n // a secondary one with 403 or 429 and `retry-after`.\n if (\n page.status === 429 ||\n (page.status === 403 &&\n (page.headers.get('x-ratelimit-remaining') === '0' ||\n page.headers.has('retry-after')))\n ) {\n return new Error(\n `GitHub API rate limit reached; set GITHUB_TOKEN or add repositories later with ${rnessCommand()} add`,\n { cause }\n )\n }\n return new Error(\n `GitHub API answered ${page.status} for ${path}${addLater()}`,\n { cause }\n )\n}\n\n/**\n * Every repository of the organization `owner` — or, when GitHub knows no\n * such organization, the public ones of the personal account — following the\n * `Link` header page by page, up to `MAX_PAGES`. Errors are one line, each\n * with its `cause`.\n */\nexport async function listRepositories(\n owner: string,\n options: ListRepositoriesOptions\n): Promise<RepositoryListing> {\n const base = (options.apiBase ?? DEFAULT_GITHUB_API).replace(/\\/+$/, '')\n const timeoutMs = options.timeoutMs ?? 15_000\n const headers: Record<string, string> = {\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n 'User-Agent': 'rness-cli',\n }\n if (options.token !== undefined && options.token !== '')\n headers['Authorization'] = `Bearer ${options.token}`\n\n const encoded = encodeURIComponent(owner)\n interface Kind {\n path: string\n query: string\n owner: RepositoryListing['owner']\n }\n const ORG: Kind = {\n path: `/orgs/${encoded}/repos`,\n query: 'type=all',\n owner: 'org',\n }\n const USER: Kind = {\n path: `/users/${encoded}/repos`,\n query: 'type=owner',\n owner: 'user',\n }\n const SELF: Kind = {\n path: '/user/repos',\n query: 'affiliation=owner',\n owner: 'self',\n }\n const url = (k: Kind, n: number): string =>\n `${base}${k.path}?${k.query}&per_page=${PER_PAGE}&page=${n}`\n let kind: Kind = ORG\n const repositories: OrgRepository[] = []\n for (let n = 1; n <= MAX_PAGES; n++) {\n let page = await getPage(url(kind, n), headers, timeoutMs)\n if (n === 1 && page.status === 404) {\n // Not an organization: a personal account answers on /users instead.\n const self = (await options.self?.()) ?? null\n kind = self?.toLowerCase() === owner.toLowerCase() ? SELF : USER\n page = await getPage(url(kind, n), headers, timeoutMs)\n if (page.status === 404) {\n throw new Error(\n `GitHub has no organization or user named \"${owner}\" (or it is not visible to you)${addLater()}`,\n { cause: { status: 404, path: kind.path } }\n )\n }\n }\n if (page.status < 200 || page.status >= 300)\n throw httpError(page, kind.path)\n if (!Array.isArray(page.body) || !page.body.every(isRepository)) {\n throw new Error(\n `GitHub API answered an unexpected body for ${kind.path}`,\n {\n cause: page.body,\n }\n )\n }\n for (const r of page.body)\n repositories.push({\n name: r.name,\n private: r.private,\n archived: r.archived,\n })\n if (!NEXT.test(page.headers.get('link') ?? ''))\n return {\n repositories,\n owner: kind.owner,\n truncated: false,\n }\n }\n return {\n repositories,\n owner: kind.owner,\n truncated: true,\n }\n}\n\nexport interface ApiOptions {\n token: string\n apiBase?: string\n timeoutMs?: number\n}\n\nfunction apiHeaders(token: string): Record<string, string> {\n return {\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n 'User-Agent': 'rness-cli',\n Authorization: `Bearer ${token}`,\n }\n}\n\n/** One authenticated GET whose error body is kept: GitHub explains a 403 there. */\nasync function getJson(\n path: string,\n options: ApiOptions\n): Promise<{ status: number; body: unknown }> {\n const base = (options.apiBase ?? DEFAULT_GITHUB_API).replace(/\\/+$/, '')\n let res: Response\n try {\n res = await fetch(`${base}${path}`, {\n headers: apiHeaders(options.token),\n signal: AbortSignal.timeout(options.timeoutMs ?? 15_000),\n })\n } catch (e) {\n throw new Error(`cannot reach the GitHub API: ${reason(e)}`, { cause: e })\n }\n const body: unknown = await res.json().catch(() => undefined)\n return { status: res.status, body }\n}\n\n/** The login a token belongs to. */\nexport async function getUser(options: ApiOptions): Promise<{ login: string }> {\n const { status, body } = await getJson('/user', options)\n if (status === 401) throw new Error('GitHub rejected the token (401)')\n const login =\n body !== null && typeof body === 'object'\n ? (body as Record<string, unknown>)['login']\n : undefined\n if (status !== 200 || typeof login !== 'string')\n throw new Error(`GitHub API answered ${status} for /user`)\n return { login }\n}\n\n/** The organizations the token's user belongs to (`read:org`), first page of 100. */\nexport async function listUserOrganizations(\n options: ApiOptions\n): Promise<string[]> {\n const { status, body } = await getJson(\n `/user/orgs?per_page=${PER_PAGE}`,\n options\n )\n if (status !== 200 || !Array.isArray(body))\n throw new Error(`GitHub API answered ${status} for /user/orgs`)\n return body\n .map((o: unknown) =>\n o !== null && typeof o === 'object'\n ? (o as Record<string, unknown>)['login']\n : undefined\n )\n .filter((l): l is string => typeof l === 'string')\n}\n\nexport type OrgMembership = 'member' | 'not-member' | 'restricted' | 'unknown'\n\n/**\n * The user's standing in `org`. `restricted`: the organization limits OAuth\n * apps and has not approved this one, so its private repositories are hidden\n * from the token — GitHub says so in the body of a 403.\n */\nexport async function getOrgMembership(\n org: string,\n options: ApiOptions\n): Promise<OrgMembership> {\n const { status, body } = await getJson(\n `/user/memberships/orgs/${encodeURIComponent(org)}`,\n options\n )\n if (status === 200) {\n const state =\n body !== null && typeof body === 'object'\n ? (body as Record<string, unknown>)['state']\n : undefined\n return state === 'active' ? 'member' : 'not-member'\n }\n if (status === 404) return 'not-member'\n if (status === 403) {\n const message =\n body !== null && typeof body === 'object'\n ? String((body as Record<string, unknown>)['message'] ?? '')\n : ''\n if (/OAuth App access restrictions/i.test(message)) return 'restricted'\n }\n return 'unknown'\n}\n\nexport type CreateRepositoryResult =\n | { kind: 'created' }\n /** GitHub said the name is taken (422). */\n | { kind: 'exists' }\n /** Not allowed, in GitHub's words. */\n | { kind: 'refused'; reason: string }\n\n/**\n * Create the private repository `owner/name`: in the organization `owner`,\n * or — when GitHub knows no such organization and `owner` is the token's own\n * account (`self`) — under the user.\n */\nexport async function createRepository(\n owner: string,\n name: string,\n options: ApiOptions & { self?: string | null }\n): Promise<CreateRepositoryResult> {\n const base = (options.apiBase ?? DEFAULT_GITHUB_API).replace(/\\/+$/, '')\n const post = async (\n path: string\n ): Promise<{ status: number; message: string }> => {\n let res: Response\n try {\n res = await fetch(`${base}${path}`, {\n method: 'POST',\n headers: {\n ...apiHeaders(options.token),\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ name, private: true }),\n signal: AbortSignal.timeout(options.timeoutMs ?? 15_000),\n })\n } catch (e) {\n throw new Error(`cannot reach the GitHub API: ${reason(e)}`, { cause: e })\n }\n const body: unknown = await res.json().catch(() => undefined)\n const message =\n body !== null && typeof body === 'object'\n ? String((body as Record<string, unknown>)['message'] ?? '')\n : ''\n return { status: res.status, message }\n }\n let answer = await post(`/orgs/${encodeURIComponent(owner)}/repos`)\n if (\n answer.status === 404 &&\n options.self !== undefined &&\n options.self !== null &&\n options.self.toLowerCase() === owner.toLowerCase()\n )\n answer = await post('/user/repos')\n if (answer.status === 201) return { kind: 'created' }\n if (answer.status === 422) return { kind: 'exists' }\n return {\n kind: 'refused',\n reason:\n answer.message === ''\n ? `GitHub answered ${answer.status}`\n : `${answer.message} (${answer.status})`,\n }\n}\n","import { type ResolvedToken, resolveToken } from './auth.ts'\nimport {\n type CreateRepositoryResult,\n type RepositoryListing,\n createRepository,\n getOrgMembership,\n getUser,\n listRepositories,\n listUserOrganizations,\n} from './github.ts'\nimport type {\n GitCredentials,\n GitProvider,\n Organization,\n OrganizationAccess,\n} from './provider.ts'\n\nconst GITHUB_HTTPS = 'https://github.com/'\n\n/**\n * GitHub as a user: the token of `GITHUB_TOKEN`, `GH_TOKEN` or `rness login`\n * — or none, and then it is GitHub seen anonymously (public repositories).\n */\nexport class GitHubOAuthProvider implements GitProvider {\n readonly #token: ResolvedToken | null\n readonly #apiBase: string | undefined\n #login: Promise<{ login: string } | null> | undefined\n\n get authenticated(): boolean {\n return this.#token !== null\n }\n\n constructor(options: { token: ResolvedToken | null; apiBase?: string }) {\n this.#token = options.token\n this.#apiBase = options.apiBase\n }\n\n #api(token: string): { token: string; apiBase?: string } {\n return this.#apiBase === undefined\n ? { token }\n : { token, apiBase: this.#apiBase }\n }\n\n identity(): Promise<{ login: string } | null> {\n this.#login ??= (async () => {\n const t = this.#token\n if (t === null) return null\n // A stored login knows its name; an environment token has to be asked.\n if (t.login !== null) return { login: t.login }\n try {\n return await getUser(this.#api(t.token))\n } catch {\n return null\n }\n })()\n return this.#login\n }\n\n async listOrganizations(): Promise<Organization[]> {\n if (this.#token === null) return []\n const logins = await listUserOrganizations(this.#api(this.#token.token))\n return logins.map((login) => ({ login }))\n }\n\n async organizationAccess(org: string): Promise<OrganizationAccess> {\n if (this.#token === null) return 'unknown'\n try {\n return await getOrgMembership(org, this.#api(this.#token.token))\n } catch {\n return 'unknown'\n }\n }\n\n async listRepositories(owner: string): Promise<RepositoryListing> {\n return listRepositories(owner, {\n token: this.#token?.token,\n ...(this.#apiBase === undefined ? {} : { apiBase: this.#apiBase }),\n self: async () => (await this.identity())?.login ?? null,\n })\n }\n\n async createRepository(\n owner: string,\n name: string\n ): Promise<CreateRepositoryResult> {\n if (this.#token === null)\n return { kind: 'refused', reason: 'not logged in' }\n return createRepository(owner, name, {\n ...this.#api(this.#token.token),\n self: (await this.identity())?.login ?? null,\n })\n }\n\n credentialsFor(url: string): GitCredentials | null {\n if (this.#token === null || !url.startsWith(GITHUB_HTTPS)) return null\n return { username: 'x-access-token', password: this.#token.token }\n }\n}\n\n/** The CLI's provider: whatever token this machine has, against `apiBase`. */\nexport async function githubProvider(apiBase?: string): Promise<GitProvider> {\n return new GitHubOAuthProvider({\n token: await resolveToken(),\n ...(apiBase === undefined ? {} : { apiBase }),\n })\n}\n","import { spawn } from 'node:child_process'\n\nimport { positional, withCredentials } from './git.ts'\nimport type { GitCredentials } from './provider.ts'\n\nexport const DEFAULT_HOST = 'https://github.com/'\nexport const SSH_HOST = 'git@github.com:'\n\n/** `<host><org>/<repo>.git`; `host` ends with `/` (https, file) or `:` (ssh). */\nexport function repoUrl(host: string, org: string, repo: string): string {\n return `${host}${org}/${repo}.git`\n}\n\nexport type Probe =\n { kind: 'found' } | { kind: 'not-found' } | { kind: 'error'; message: string }\n\nconst AUTH = [\n /authentication failed/i,\n /permission denied/i,\n /could not read username/i,\n /terminal prompts disabled/i,\n]\nconst NOT_FOUND = [\n /repository .*not found/i,\n /does not appear to be a git repository/i,\n]\n\nfunction firstLine(text: string): string {\n return (\n text\n .split('\\n')\n .find((l) => l.trim() !== '')\n ?.trim() ?? 'unknown error'\n )\n}\n\n/**\n * Interpret `git ls-remote --exit-code <url> HEAD`. Auth patterns win over\n * not-found ones: GitHub tells strangers a private repository does not exist,\n * so \"not found\" only counts when nothing points at a credentials problem.\n * Exit 2 is \"no HEAD\" — an empty repository that does exist.\n */\nexport function classifyProbe(\n url: string,\n exitCode: number,\n stderr: string\n): Probe {\n if (exitCode === 0 || exitCode === 2) return { kind: 'found' }\n if (AUTH.some((r) => r.test(stderr)))\n return {\n kind: 'error',\n message: `cannot access ${url}: ${firstLine(stderr)}`,\n }\n if (NOT_FOUND.some((r) => r.test(stderr))) return { kind: 'not-found' }\n return { kind: 'error', message: `cannot reach ${url}: ${firstLine(stderr)}` }\n}\n\n/**\n * How long, after the child has exited, the stderr pipe may still deliver what\n * git wrote before exiting. `'exit'` can precede the last `'data'` event, and\n * an empty stderr would be classified as an unreachable remote — but a\n * grandchild (a credential helper) can hold the pipe open for as long as it\n * likes, so the wait is bounded and `'close'` is never awaited.\n */\nconst STDERR_FLUSH_MS = 200\n\n/**\n * `git ls-remote --exit-code <url> HEAD`, classified (see `classifyProbe`).\n * Never hangs: the child is killed after `timeoutMs`, and the answer never\n * waits on `'close'`, so a credential helper left holding the stderr pipe\n * cannot keep the caller pending. The child stays in this process's group so\n * that Ctrl-C in the terminal reaches it too.\n */\nexport async function probeRemote(\n url: string,\n timeoutMs = 60_000,\n credentials?: GitCredentials | null\n): Promise<Probe> {\n // Before anything spawns, and outside the promise: a url git would read as\n // an option must fail loudly rather than reach the command line.\n positional(url, 'repository url')\n return new Promise<Probe>((resolve) => {\n const auth = withCredentials(credentials)\n const child = spawn(\n 'git',\n [...auth.args, 'ls-remote', '--exit-code', url, 'HEAD'],\n {\n stdio: ['ignore', 'ignore', 'pipe'],\n env: { ...process.env, ...auth.env, GIT_TERMINAL_PROMPT: '0' },\n }\n )\n const chunks: string[] = []\n child.stderr?.setEncoding('utf8')\n child.stderr?.on('data', (chunk: string) => chunks.push(chunk))\n\n let settled = false\n const settle = (probe: Probe): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n // Release the pipe: a grandchild still holding it open would otherwise\n // keep the event loop alive long after the answer is known.\n child.stderr?.destroy()\n resolve(probe)\n }\n const timer = setTimeout(() => {\n // Only the child git itself: a grandchild it orphaned is harmless, and\n // killing a whole process group would mean detaching from ours, which\n // costs the terminal's Ctrl-C.\n child.kill('SIGKILL')\n settle({\n kind: 'error',\n message: `cannot reach ${url}: timed out after ${Math.round(timeoutMs / 1000)}s`,\n })\n }, timeoutMs)\n\n child.on('error', (e: Error) => settle(classifyProbe(url, 1, e.message)))\n child.on('exit', (code) => {\n const finish = (): void =>\n settle(classifyProbe(url, code ?? 1, chunks.join('')))\n const stderr = child.stderr\n if (stderr === null || stderr.readableEnded || stderr.destroyed)\n return finish()\n const flush = setTimeout(finish, STDERR_FLUSH_MS)\n const done = (): void => {\n clearTimeout(flush)\n finish()\n }\n stderr.once('end', done)\n stderr.once('error', done)\n })\n })\n}\n","import { execFile } from 'node:child_process'\nimport { dirname, resolve } from 'node:path'\nimport { promisify } from 'node:util'\n\nimport type { GitCredentials } from './provider.ts'\n\nconst execFileP = promisify(execFile)\n\n// Answers git's `get` with what the environment holds. The token is never in\n// an argument, a URL or a config file: only in the child's environment.\nconst ENV_HELPER =\n '!f() { test \"$1\" = get && printf \"username=%s\\\\npassword=%s\\\\n\" \"$RNESS_GIT_USERNAME\" \"$RNESS_GIT_TOKEN\"; }; f'\n\n/**\n * How one git command is given credentials (spec 0004 §4): the helpers git\n * would otherwise consult are cleared, and one that lives for this command\n * only reads the child's environment. Nothing when there are none.\n */\nexport function withCredentials(\n credentials: GitCredentials | null | undefined\n): {\n args: string[]\n env: Record<string, string>\n} {\n if (credentials === null || credentials === undefined)\n return { args: [], env: {} }\n return {\n args: ['-c', 'credential.helper=', '-c', `credential.helper=${ENV_HELPER}`],\n env: {\n RNESS_GIT_USERNAME: credentials.username,\n RNESS_GIT_TOKEN: credentials.password,\n },\n }\n}\n\nasync function git(\n args: readonly string[],\n cwd?: string,\n credentials?: GitCredentials | null\n): Promise<string> {\n const auth = withCredentials(credentials)\n try {\n const { stdout } = await execFileP('git', [...auth.args, ...args], {\n ...(cwd === undefined ? {} : { cwd }),\n env: {\n ...process.env,\n ...auth.env,\n GIT_TERMINAL_PROMPT: '0',\n // Pin the command to `cwd` itself: without a ceiling, git walks up and\n // a plain directory under `org/` would report — or be pulled into —\n // whatever repository happens to sit above the workspace root. git\n // ignores a relative ceiling entry, hence the resolve().\n ...(cwd === undefined\n ? {}\n : { GIT_CEILING_DIRECTORIES: dirname(resolve(cwd)) }),\n },\n maxBuffer: 16 * 1024 * 1024,\n })\n return stdout\n } catch (e) {\n const err = e as { stderr?: string; message?: string }\n const text =\n err.stderr !== undefined && err.stderr !== ''\n ? err.stderr\n : (err.message ?? 'unknown error')\n const first =\n text.split('\\n').find((l) => l.trim() !== '') ?? 'unknown error'\n throw new Error(`git ${args[0] ?? ''} failed: ${first.trim()}`, {\n cause: e,\n })\n }\n}\n\n/** Reject a value git could parse as an option (e.g. a `rness.json` URL starting with `-`). */\nexport function positional(value: string, what: string): string {\n if (value.startsWith('-'))\n throw new Error(`refusing suspicious ${what}: ${value}`)\n return value\n}\n\n/** `git clone <url> <dir>`; `dir` must not exist. */\nexport async function clone(\n url: string,\n dir: string,\n credentials?: GitCredentials | null\n): Promise<void> {\n await git(\n [\n 'clone',\n '--quiet',\n '--',\n positional(url, 'repository url'),\n positional(dir, 'directory'),\n ],\n undefined,\n credentials\n )\n}\n\n/**\n * True when `git status --porcelain` prints nothing, ignoring the paths in\n * `ignore` (rness-managed files such as `AGENTS.md`/`CLAUDE.md` that sync\n * itself writes into every clone and that should never veto an auto-pull).\n */\nexport async function isClean(\n dir: string,\n ignore: readonly string[] = []\n): Promise<boolean> {\n const pathspec = ignore.map((p) => `:!${p}`)\n return (\n (\n await git(\n [\n 'status',\n '--porcelain',\n ...(pathspec.length > 0 ? ['--', ...pathspec] : []),\n ],\n dir\n )\n ).trim() === ''\n )\n}\n\nexport async function pullFastForward(\n dir: string,\n credentials?: GitCredentials | null\n): Promise<void> {\n await git(['pull', '--ff-only', '--quiet'], dir, credentials)\n}\n\n/** `git remote add origin <url>` then `git push -u origin main`, in `dir`. */\nexport async function publish(\n dir: string,\n url: string,\n credentials?: GitCredentials | null\n): Promise<void> {\n await git(['remote', 'add', 'origin', positional(url, 'repository url')], dir)\n await git(['push', '--quiet', '-u', 'origin', 'main'], dir, credentials)\n}\n\n/** The `origin` URL, or null when `dir` is not a clone with an origin. */\nexport async function originUrl(dir: string): Promise<string | null> {\n try {\n return (await git(['remote', 'get-url', 'origin'], dir)).trim()\n } catch {\n return null\n }\n}\n\n/** `git init -q -b main <dir>` (the directory must exist). */\nexport async function init(dir: string): Promise<void> {\n await git(['init', '-q', '-b', 'main'], dir)\n}\n\n/** `git add -A && git commit -q -m <message>` in `dir`. */\nexport async function commitAll(dir: string, message: string): Promise<void> {\n await git(['add', '-A'], dir)\n await git(['commit', '-q', '-m', message], dir)\n}\n","import { readFile } from 'node:fs/promises'\nimport { basename, join } from 'node:path'\n\nimport { writeFileAtomic } from './fs.ts'\nimport { repoUrl } from './remote.ts'\nimport type { Manifest, RepoEntry, ScopeEntry } from './types.ts'\n\n/**\n * A repository or scope name: what GitHub allows in a repository name, in\n * lowercase — letters, digits, `.`, `_` and `-`. Not `.` or `..` (the name is\n * a directory under `org/`), and no leading `-` (git would read an option).\n */\nexport const NAME = /^(?!\\.{1,2}$)[a-z0-9._][a-z0-9._-]*$/\n\n/**\n * The organization's context repository. It holds the catalogue and is cloned\n * as `<root>/.rness`, so it is never a member of the workspace it defines:\n * `create` does not offer it and `add` refuses it (spec 0009).\n */\nexport const CONTEXT_REPO = '.rness'\n\n/**\n * Names that are never a repository of the workspace, whatever they look like\n * (spec 0009). A leading dot is an ordinary first character — `.github`\n * carries an organization's profile, its templates and its shared workflows —\n * so the rule cannot be a shape: it is this list. Add a name here rather than\n * inventing another filter.\n *\n * - `.rness` — the context repository: it holds the catalogue and is already\n * cloned as `<root>/.rness`.\n * - `.git` — a git directory, were `org/` ever to sit inside a repository.\n * - `node_modules` — an install run one directory too high.\n */\nexport const EXCLUDED_NAMES: ReadonlySet<string> = new Set([\n CONTEXT_REPO,\n '.git',\n 'node_modules',\n])\n\n/**\n * Whether a repository of the organization can become a member of the\n * workspace. Everything active is, but an excluded name; an archived\n * repository is read-only on GitHub, so a block written into it could never be\n * pushed back. `create` filters its listing with this, and counts with it, so\n * the number it announces and the list it offers cannot disagree.\n */\nexport function isMemberRepo(repo: {\n name: string\n archived: boolean\n}): boolean {\n return !repo.archived && !EXCLUDED_NAMES.has(repo.name.toLowerCase())\n}\n\n/**\n * Whether a directory under `org/` is one of the workspace's clones. It must\n * be a name the catalogue could hold: a directory `rness add` could never\n * declare is not reported as an undeclared clone, since the command suggested\n * to bring it in would refuse it.\n */\nexport function isWorkspaceClone(name: string): boolean {\n return NAME.test(name) && !EXCLUDED_NAMES.has(name)\n}\n/** How the rule reads in an error message. */\nexport const NAME_RULE =\n \"lowercase letters, digits, '.', '_' and '-', not starting with '-'\"\n\n/**\n * A GitHub organization (or user) name: alphanumerics and single hyphens, not\n * at either end, at most 39 characters. Used exactly as typed — GitHub\n * resolves names case-insensitively, but the URLs and `rness.json` keep the\n * spelling the user chose.\n */\nexport const ORG_NAME = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/\n\n/** Every top-level key contract 1 defines. */\nconst KEYS = ['contract', 'org', 'repos', 'scopes']\n\nfunction fail(message: string): never {\n throw new Error(`rness.json: ${message}`)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction checkPath(scope: string, path: unknown): string {\n if (typeof path !== 'string' || path === '')\n fail(`scope \"${scope}\" needs a string \"path\"`)\n if (path.startsWith('/')) fail(`scope \"${scope}\" path must be relative`)\n if (path.split('/').includes('..'))\n fail(`scope \"${scope}\" path must not contain \"..\"`)\n if (path.split('/').some((segment) => segment === ''))\n fail(`scope \"${scope}\" path must not contain empty segments`)\n return path\n}\n\nfunction readOrg(value: unknown): string | null {\n if (value === undefined || value === null) return null\n if (typeof value !== 'string' || !ORG_NAME.test(value)) {\n fail(\n `\"org\" must be a GitHub organization name (got ${JSON.stringify(value)})`\n )\n }\n return value\n}\n\n/**\n * The name the workspace goes by — in its blocks and its session titles: the\n * organization, else the root directory's name. A workspace without `org` is\n * a blank one (spec 0012), a normal state rather than a slip to warn about.\n */\nexport function workspaceName(manifest: Manifest, root: string): string {\n return manifest.org ?? basename(root)\n}\n\nfunction readRepos(value: unknown): Record<string, RepoEntry> {\n const raw = value ?? {}\n if (!isRecord(raw)) fail('\"repos\" must be an object')\n const repos: Record<string, RepoEntry> = {}\n for (const [name, entry] of Object.entries(raw)) {\n if (!NAME.test(name))\n fail(`repo name \"${name}\" may only contain ${NAME_RULE}`)\n if (!isRecord(entry) || typeof entry.url !== 'string')\n fail(`repo \"${name}\" needs a string \"url\"`)\n repos[name] = { url: entry.url }\n }\n return repos\n}\n\nfunction readScopes(value: unknown): Record<string, ScopeEntry> {\n const raw = value ?? {}\n if (!isRecord(raw)) fail('\"scopes\" must be an object')\n const scopes: Record<string, ScopeEntry> = {}\n for (const [name, entry] of Object.entries(raw)) {\n if (!NAME.test(name))\n fail(`scope name \"${name}\" may only contain ${NAME_RULE}`)\n if (!isRecord(entry)) fail(`scope \"${name}\" must be an object`)\n const path = checkPath(name, entry.path)\n const ext = entry.extends ?? []\n if (!Array.isArray(ext) || !ext.every((t) => typeof t === 'string')) {\n fail(`scope \"${name}\" extends must be an array of scope names`)\n }\n scopes[name] = { path, extends: ext as string[] }\n }\n for (const [name, entry] of Object.entries(scopes)) {\n for (const target of entry.extends) {\n if (!Object.hasOwn(scopes, target))\n fail(`scope \"${name}\" extends unknown scope \"${target}\"`)\n }\n }\n return scopes\n}\n\n/** Read and validate `<rnessDir>/rness.json`. Every error starts with `rness.json:`. */\nexport async function loadManifest(rnessDir: string): Promise<Manifest> {\n let raw: string\n try {\n raw = await readFile(join(rnessDir, 'rness.json'), 'utf8')\n } catch {\n fail('not found')\n }\n let data: unknown\n try {\n data = JSON.parse(raw)\n } catch (e) {\n fail(`invalid JSON (${e instanceof Error ? e.message : String(e)})`)\n }\n if (!isRecord(data)) fail('must be a JSON object')\n if (data.contract !== 1)\n fail(`unsupported contract: ${JSON.stringify(data.contract)} (expected 1)`)\n // Refuse what this contract does not define: a typo (`scope`, `repo`) or a\n // key from a later contract would otherwise be read as nothing at all.\n for (const key of Object.keys(data)) {\n if (!KEYS.includes(key)) fail(`unknown key ${JSON.stringify(key)}`)\n }\n return {\n contract: 1,\n org: readOrg(data.org),\n repos: readRepos(data.repos),\n scopes: readScopes(data.scopes),\n }\n}\n\n/** Serialise in the contract's key order; atomic write. */\nexport async function writeManifest(\n rnessDir: string,\n manifest: Manifest\n): Promise<void> {\n const repos = Object.entries(manifest.repos).map(\n ([name, r]) =>\n ` ${JSON.stringify(name)}: { \"url\": ${JSON.stringify(r.url)} }`\n )\n const scopes = Object.entries(manifest.scopes).map(([name, s]) => {\n const ext =\n s.extends.length === 0\n ? ''\n : `, \"extends\": [${s.extends.map((e) => JSON.stringify(e)).join(', ')}]`\n return ` ${JSON.stringify(name)}: { \"path\": ${JSON.stringify(s.path)}${ext} }`\n })\n const lines = ['{', ' \"contract\": 1,']\n if (manifest.org !== null)\n lines.push(` \"org\": ${JSON.stringify(manifest.org)},`)\n lines.push(\n ' \"repos\": {',\n repos.join(',\\n'),\n ' },',\n ' \"scopes\": {',\n scopes.join(',\\n'),\n ' }',\n '}'\n )\n const text = `${lines.filter((l) => l !== '').join('\\n')}\\n`\n await writeFileAtomic(join(rnessDir, 'rness.json'), text)\n}\n\nconst FULL_URL = /^(https?:\\/\\/|git@|ssh:\\/\\/|file:\\/\\/)/\n\n/** `web` → `<host><org>/web.git`; `other/api` → `<host>other/api.git`; a full URL is kept. */\nexport function parseRepoSpec(\n spec: string,\n org: string | null,\n host: string\n): { name: string; url: string } {\n let url: string\n if (FULL_URL.test(spec)) {\n url = spec\n } else {\n const parts = spec.split('/')\n if (parts.length === 1) {\n // A blank workspace has no owner to expand a bare name with (spec 0012).\n if (org === null)\n throw new Error(\n 'this workspace has no GitHub organization: give <owner>/<repo> or a git URL'\n )\n url = repoUrl(host, org, spec)\n } else if (\n parts.length === 2 &&\n parts[0] !== undefined &&\n parts[1] !== undefined\n )\n url = repoUrl(host, parts[0], parts[1])\n else\n throw new Error(\n `repository name \"${spec}\" is not a name (use <repo>, <owner>/<repo>, or a URL)`\n )\n }\n const last = url.replace(/\\/+$/, '').split(/[/:]/).at(-1) ?? ''\n const name = last.endsWith('.git') ? last.slice(0, -4) : last\n if (!NAME.test(name))\n throw new Error(`repository name \"${name}\" may only contain ${NAME_RULE}`)\n return { name, url }\n}\n","import { glob, readFile, rm } from 'node:fs/promises'\nimport { join, posix, sep } from 'node:path'\n\nimport { exists } from './fs.ts'\nimport { clone, originUrl } from './git.ts'\nimport { NAME, NAME_RULE, parseRepoSpec, writeManifest } from './manifest.ts'\nimport type { GitCredentials } from './provider.ts'\nimport type { Manifest, ScopeEntry } from './types.ts'\n\nexport interface AddRepositoryInput {\n root: string\n rnessDir: string\n manifest: Manifest\n /** `<repo>`, `<owner>/<repo>`, or a clone URL. */\n spec: string\n /** The owner of a bare `<repo>`; null in a blank workspace, which refuses one. */\n org: string | null\n host: string\n /** Sub-scopes relative to the repository (`apps/web`); each becomes scope `<basename>` extending `<repo>`. */\n scopes: readonly string[]\n /** HTTPS credentials for the URL the spec resolves to, when there are any. */\n credentialsFor?: (url: string) => GitCredentials | null\n}\n\nexport interface AddRepositoryResult {\n manifest: Manifest\n name: string\n url: string\n action: 'cloned' | 'adopted'\n /** Scope names written to the manifest, repository scope first. */\n declared: string[]\n}\n\n/** Clone (or adopt) a repository under `org/` and declare it — manifest written last (spec 0003 §3). */\nexport async function addRepository(\n input: AddRepositoryInput\n): Promise<AddRepositoryResult> {\n const { name, url } = parseRepoSpec(input.spec, input.org, input.host)\n const dir = join(input.root, 'org', name)\n\n // Validate every scope before touching the filesystem: a malformed request\n // must never leave a clone behind that the manifest doesn't know about. Only\n // the per-sub directory-existence check needs the clone (or adoption) to have\n // happened, so it waits until after.\n const repoPath = `org/${name}`\n // The repository scope gets the same protection as a sub-scope: a name\n // already taken by another path is a collision, not something to overwrite.\n // At the same path the entry keeps its `extends` — a hand-added shared\n // parent scope survives every later `add` of the repository.\n const current = input.manifest.scopes[name]\n if (current !== undefined && current.path !== repoPath)\n throw new Error(`scope \"${name}\" already points at ${current.path}`)\n const scopes: Record<string, ScopeEntry> = {\n ...input.manifest.scopes,\n [name]: { path: repoPath, extends: current?.extends ?? [] },\n }\n const subs: { path: string; base: string }[] = []\n for (const sub of input.scopes) {\n const clean = sub.replace(/^\\/+|\\/+$/g, '')\n const segments = clean.split('/')\n if (segments.some((s) => s === '' || s === '.' || s === '..'))\n throw new Error(\n `sub-scope \"${clean}\" must be a relative path inside the repository`\n )\n const base = segments.at(-1) ?? ''\n const path = `org/${name}/${clean}`\n if (!NAME.test(base))\n throw new Error(\n `the last segment of sub-scope \"${clean}\" may only contain ${NAME_RULE}`\n )\n const existing = scopes[base]\n if (existing !== undefined && existing.path !== path)\n throw new Error(`scope \"${base}\" already points at ${existing.path}`)\n scopes[base] = { path, extends: [name] }\n subs.push({ path, base })\n }\n\n let action: AddRepositoryResult['action']\n if (await exists(dir)) {\n const origin = await originUrl(dir)\n if (origin === null)\n throw new Error(`org/${name} exists and is not a git clone`)\n if (origin !== url)\n throw new Error(`org/${name} is a clone of ${origin}, not ${url}`)\n action = 'adopted'\n } else {\n await clone(url, dir, input.credentialsFor?.(url) ?? null)\n action = 'cloned'\n }\n\n const declared = [name]\n for (const { path, base } of subs) {\n if (!(await exists(join(input.root, ...path.split('/'))))) {\n // Only a clone this call just made is ours to remove: it isn't in the\n // manifest yet, so nothing is lost. An adopted directory predates this\n // call and is left alone.\n if (action === 'cloned') await rm(dir, { recursive: true, force: true })\n throw new Error(`${path} does not exist`)\n }\n declared.push(base)\n }\n\n const manifest: Manifest = {\n ...input.manifest,\n repos: { ...input.manifest.repos, [name]: { url } },\n scopes,\n }\n await writeManifest(input.rnessDir, manifest)\n return { manifest, name, url, action, declared }\n}\n\n/** Directories matched by `package.json#workspaces` that hold a `package.json`, POSIX-relative, sorted. */\nexport async function workspaceDirs(repoDir: string): Promise<string[]> {\n let patterns: string[] = []\n try {\n const pkg = JSON.parse(\n await readFile(join(repoDir, 'package.json'), 'utf8')\n ) as { workspaces?: unknown }\n const w = pkg.workspaces\n if (Array.isArray(w))\n patterns = w.filter((p): p is string => typeof p === 'string')\n else if (\n w !== null &&\n typeof w === 'object' &&\n Array.isArray((w as { packages?: unknown }).packages)\n ) {\n patterns = (w as { packages: unknown[] }).packages.filter(\n (p): p is string => typeof p === 'string'\n )\n }\n } catch {\n return []\n }\n const dirs = new Set<string>()\n for (const pattern of patterns) {\n for await (const match of glob(pattern, { cwd: repoDir })) {\n const rel = match.split(sep).join(posix.sep)\n if (await exists(join(repoDir, ...rel.split(posix.sep), 'package.json')))\n dirs.add(rel)\n }\n }\n return [...dirs].sort()\n}\n","import type {\n autocompleteMultiselect,\n cancel,\n confirm,\n intro,\n isCancel,\n log,\n multiselect,\n note,\n outro,\n select,\n spinner,\n text,\n} from '@clack/prompts'\n\n/** The `@clack/prompts` functions the interactive commands use. */\nexport interface Prompts {\n text: typeof text\n confirm: typeof confirm\n multiselect: typeof multiselect\n select: typeof select\n autocompleteMultiselect: typeof autocompleteMultiselect\n isCancel: typeof isCancel\n // The session look (spec 0007 §5b). Optional: a scripted terminal in a\n // test has prompts only, and gets the plain look.\n intro?: typeof intro\n outro?: typeof outro\n cancel?: typeof cancel\n note?: typeof note\n log?: typeof log\n spinner?: typeof spinner\n}\n\n/** What an interactive command needs from the terminal; tests replace it with scripted answers. */\nexport interface Terminal {\n isTty(): boolean\n prompts(): Promise<Prompts>\n}\n\nexport const defaultTerminal: Terminal = {\n isTty: () => process.stdin.isTTY === true && process.stdout.isTTY === true,\n // Lazy: the prompt library stays off every non-interactive path.\n prompts: () => import('@clack/prompts'),\n}\n","import { spawn } from 'node:child_process'\n\nimport { rnessCommand } from './pm.ts'\nimport { DEFAULT_HOST, SSH_HOST } from './remote.ts'\nimport { status } from './style.ts'\n\n/** The two bases a github.com URL can be written with (spec 0005). */\nexport interface Hosts {\n ssh: string\n https: string\n}\n\nexport const GITHUB_HOSTS: Hosts = { ssh: SSH_HOST, https: DEFAULT_HOST }\n\nexport type SshAccess =\n { ok: true; login: string } | { ok: false; reason: string }\n\nexport type DetectSsh = (opts: { interactive: boolean }) => Promise<SshAccess>\n\n/** What a command needs to choose between SSH and HTTPS; tests replace it. */\nexport interface Transport {\n hosts: Hosts\n detect: DetectSsh\n}\n\nconst GREETING = /^Hi ([^!\\s]+)! You've successfully authenticated/m\n\n/** The login in GitHub's `Hi <login>! You've successfully authenticated…`, or null. */\nexport function parseSshGreeting(stderr: string): string | null {\n return GREETING.exec(stderr)?.[1] ?? null\n}\n\nfunction firstLine(text: string): string | null {\n return (\n text\n .split('\\n')\n .find((l) => l.trim() !== '')\n ?.trim() ?? null\n )\n}\n\n/** As in `probeRemote`: what the pipe may still deliver after `'exit'`. */\nconst STDERR_FLUSH_MS = 200\n\n/**\n * `ssh -T git@github.com`: does github.com accept one of the user's keys?\n * GitHub greets an accepted key and exits 1, so the greeting — not the exit\n * code — is the answer.\n *\n * In a terminal `ssh` may ask for a key's passphrase or confirm github.com's\n * host key; it asks on `/dev/tty`, not on stderr, so stderr stays piped and\n * the greeting is still read. Without a terminal `BatchMode=yes` forbids\n * every prompt. Never throws and never hangs: the child is killed at the\n * deadline, and the answer never waits on `'close'`.\n */\nexport async function detectGithubSsh(opts: {\n interactive: boolean\n /** Tests: a fake executable, called by path. */\n command?: string\n timeoutMs?: number\n}): Promise<SshAccess> {\n const timeoutMs = opts.timeoutMs ?? (opts.interactive ? 120_000 : 10_000)\n const args = [\n '-T',\n '-o',\n 'ConnectTimeout=5',\n ...(opts.interactive ? [] : ['-o', 'BatchMode=yes']),\n 'git@github.com',\n ]\n return new Promise<SshAccess>((resolve) => {\n const child = spawn(opts.command ?? 'ssh', args, {\n stdio: [opts.interactive ? 'inherit' : 'ignore', 'ignore', 'pipe'],\n })\n const chunks: string[] = []\n child.stderr?.setEncoding('utf8')\n child.stderr?.on('data', (chunk: string) => chunks.push(chunk))\n\n let settled = false\n const settle = (access: SshAccess): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n child.stderr?.destroy()\n resolve(access)\n }\n const timer = setTimeout(() => {\n child.kill('SIGKILL')\n settle({ ok: false, reason: `timed out after ${timeoutMs / 1000}s` })\n }, timeoutMs)\n\n child.on('error', (e: Error) => settle({ ok: false, reason: e.message }))\n child.on('exit', (code) => {\n const finish = (): void => {\n const stderr = chunks.join('')\n const login = parseSshGreeting(stderr)\n settle(\n login !== null\n ? { ok: true, login }\n : {\n ok: false,\n reason:\n firstLine(stderr) ?? `ssh exited with code ${code ?? '?'}`,\n }\n )\n }\n const stderr = child.stderr\n if (stderr === null || stderr.readableEnded || stderr.destroyed)\n return finish()\n const flush = setTimeout(finish, STDERR_FLUSH_MS)\n const done = (): void => {\n clearTimeout(flush)\n finish()\n }\n stderr.once('end', done)\n stderr.once('error', done)\n })\n })\n}\n\nexport const defaultTransport: Transport = {\n hosts: GITHUB_HOSTS,\n detect: detectGithubSsh,\n}\n\nexport interface SshTest {\n access: SshAccess\n /** SSH works without asking anything: git over SSH will not prompt either. */\n unattended: boolean\n}\n\n/**\n * The SSH test, unattended first (`BatchMode=yes`): when that passes, ssh\n * never asks anything and a progress line may animate while git runs. Only\n * when it fails, and in a terminal, the test runs again letting ssh ask for a\n * passphrase — `announce` says so first.\n */\nexport async function testGithubSsh(\n transport: Transport,\n interactive: boolean,\n announce: () => void\n): Promise<SshTest> {\n const batch = await transport.detect({ interactive: false })\n if (batch.ok || !interactive) return { access: batch, unattended: batch.ok }\n announce()\n return {\n access: await transport.detect({ interactive: true }),\n unattended: false,\n }\n}\n\nconst loggedInAs = (login?: string | null): string =>\n login === undefined || login === null ? '' : `, logged in as ${login}`\n\n/** The outcome of the SSH test as a sentence, for the session look. */\nexport function usingSentence(\n access: SshAccess,\n login?: string | null\n): string {\n return access.ok\n ? `SSH works for github.com (as ${access.login}) — repositories are cloned over SSH`\n : `No SSH access to github.com (${access.reason}) — repositories are cloned over HTTPS${loggedInAs(login)}`\n}\n\n/** Is `url` written with the SSH base? */\nexport function isSshUrl(url: string, hosts: Hosts): boolean {\n return url.startsWith(hosts.ssh)\n}\n\n/** Printed in a terminal before the test, which may ask for a passphrase. */\nexport const CHECKING_LINE = status('checking', 'ssh access to github.com…')\n/** The same as `[verb, rest, sentence]`, for a `Ui`. */\nexport const CHECKING = [\n 'checking',\n 'ssh access to github.com…',\n 'Checking SSH access to github.com — ssh may ask for your passphrase',\n] as const\n\n/** `login`: who rness is logged in as, which is what makes HTTPS reach private repositories. */\nexport function usingRest(access: SshAccess, login?: string | null): string {\n return access.ok\n ? `ssh (github.com as ${access.login})`\n : `https (ssh to github.com unavailable: ${access.reason}${loggedInAs(login)})`\n}\n\nexport function usingLine(access: SshAccess, login?: string | null): string {\n return status('using', usingRest(access, login))\n}\n\n/** Why an SSH workspace cannot be served, and how to fix it. */\n/**\n * A child's `git clone` failed on publickey although the parent's own SSH test\n * passed: the key works but no agent holds it, so git's `ssh` asks again in\n * every child (spec 0008 §2.1).\n */\nexport function agentHintLines(\n platform: NodeJS.Platform = process.platform\n): string[] {\n const mac = platform === 'darwin'\n return [\n 'your key works but is not loaded; ssh asks again in every child:',\n ` ssh-add ${mac ? '--apple-use-keychain ' : ''}~/.ssh/id_ed25519`,\n ` ~/.ssh/config: AddKeysToAgent yes${mac ? ', UseKeychain yes' : ''}`,\n ]\n}\n\nexport function sshWorkspaceLines(reason: string): [string, string] {\n return [\n `this workspace clones over SSH (rness.json) but ssh to github.com fails: ${reason}`,\n 'set up an SSH key: https://docs.github.com/authentication/connecting-to-github-with-ssh',\n ]\n}\n\n/** The user-side escape hatch where `rness.json` is not negotiable. */\nexport const INSTEAD_OF_LINES: [string, string] = [\n 'or make git use HTTPS for github.com on this machine:',\n ' git config --global url.\"https://github.com/\".insteadOf git@github.com:',\n]\n\nexport function httpsFlagLine(spec: string): string {\n return `or clone this repository over HTTPS: ${rnessCommand()} add ${spec} --https`\n}\n","import { styleText } from 'node:util'\n\n// The CLI's look (spec 0007). This module imports `node:util` only, so the\n// lean commands (`context`, `validate`) can use it. Whether a stream gets\n// colour is `util.styleText`'s decision: a terminal, unless NO_COLOR; any\n// stream with FORCE_COLOR. Off a terminal every function returns plain text —\n// the bytes scripts, CI and the tests have always read.\n\nexport type Tone = 'done' | 'idle' | 'info' | 'warn' | 'error'\n\ntype Format = Parameters<typeof styleText>[0]\n\nconst FORMAT: Record<Tone, Format> = {\n done: 'green',\n idle: 'dim',\n info: 'cyan',\n warn: 'yellow',\n error: 'red',\n}\n\n/** https://no-color.org: any non-empty value; FORCE_COLOR, being explicit, wins. */\nfunction noColor(): boolean {\n const off = process.env['NO_COLOR']\n return (\n off !== undefined && off !== '' && process.env['FORCE_COLOR'] === undefined\n )\n}\n\nexport function paint(\n tone: Tone,\n text: string,\n stream: NodeJS.WriteStream = process.stdout\n): string {\n if (noColor()) return text\n return styleText(FORMAT[tone], text, { stream, validateStream: true })\n}\n\nconst IDLE = new Set(['unchanged', 'skipped', 'not cloned', 'current'])\nconst DONE = new Set([\n 'created',\n 'cloned',\n 'adopted',\n 'declared',\n 'installed',\n 'committed',\n 'updated',\n 'upgraded',\n 'pulled',\n 'pushed',\n 'logged in',\n 'logged out',\n 'synced',\n 'listed',\n])\n\n/** What a status verb says about the step: it changed something, it did not, or it is progress. */\nexport function toneOf(verb: string): Tone {\n if (DONE.has(verb)) return 'done'\n if (IDLE.has(verb)) return 'idle'\n if (verb === 'stale') return 'warn'\n return 'info'\n}\n\n/** The width verbs are padded to; a longer verb (`unchanged`) takes its own. */\nconst COLUMN = 8\n\n/**\n * One status line: the verb painted by its tone and padded to the column,\n * then `rest`, untouched — a path stays readable on any background.\n */\nexport function status(\n verb: string,\n rest: string,\n stream: NodeJS.WriteStream = process.stdout\n): string {\n const pad = ' '.repeat(Math.max(0, COLUMN - verb.length))\n return `${paint(toneOf(verb), verb, stream)}${pad} ${rest}`\n}\n\nexport function bold(\n text: string,\n stream: NodeJS.WriteStream = process.stdout\n): string {\n if (noColor()) return text\n return styleText('bold', text, { stream, validateStream: true })\n}\n\n/**\n * Backgrounds for a badge. `intro` opens a session; the others close one, so\n * the verdict is legible at a glance without reading the words.\n */\nconst BACKGROUND: Record<BadgeTone, Format> = {\n intro: ['bgCyan', 'black', 'bold'],\n done: ['bgGreen', 'black', 'bold'],\n idle: ['bgCyan', 'black', 'bold'],\n info: ['bgCyan', 'black', 'bold'],\n warn: ['bgYellow', 'black', 'bold'],\n error: ['bgRed', 'white', 'bold'],\n}\n\nexport type BadgeTone = Tone | 'intro'\n\n/**\n * Text on a coloured background — the intro of a session, or its verdict.\n * Without colour it is the bare text: padding only makes sense around a\n * background.\n */\nexport function badge(\n text: string,\n tone: BadgeTone | NodeJS.WriteStream = 'intro',\n stream: NodeJS.WriteStream = process.stdout\n): string {\n // The stream used to be the second argument; callers that pass one still\n // get the intro badge they asked for before tones existed.\n const [t, s] =\n typeof tone === 'string'\n ? ([tone, stream] as const)\n : (['intro', tone] as const)\n if (noColor()) return text\n const padded = ` ${text} `\n const painted = styleText(BACKGROUND[t], padded, {\n stream: s,\n validateStream: true,\n })\n return painted === padded ? text : painted\n}\n\n/** Grey, for what is read after the rest: a box of next steps. */\nexport function grey(\n text: string,\n stream: NodeJS.WriteStream = process.stdout\n): string {\n if (noColor()) return text\n return styleText('gray', text, { stream, validateStream: true })\n}\n\n/**\n * Can this terminal draw characters beyond ASCII? The rule `@clack/prompts`\n * follows for its own symbols: everywhere but the Linux console and the\n * legacy Windows console.\n */\nexport function unicode(): boolean {\n if (process.platform !== 'win32') return process.env['TERM'] !== 'linux'\n return (\n process.env['WT_SESSION'] !== undefined ||\n process.env['TERM_PROGRAM'] === 'vscode'\n )\n}\n\n/** A private repository, said with a padlock; a public one says nothing. */\nexport const PRIVATE_MARK = '🔒'\n\n/** `warning: …` for stderr, the prefix painted. */\nexport function warn(text: string): string {\n return `${paint('warn', 'warning:', process.stderr)} ${text}`\n}\n\n// `rness`, rendered once with cfonts' \"tiny\" font and kept as a constant: one\n// fixed word does not need a font engine at run time.\nconst WORD = [' █▀█ █▄ █ █▀▀ █▀▀ █▀▀', ' █▀▄ █ ▀█ ██▄ ▄▄█ ▄▄█']\n\nconst FROM = [63, 185, 80] as const // green\nconst TO = [57, 197, 207] as const // cyan\n\n/**\n * The only hand-written escape sequences of the code base: `util.styleText`\n * has no 24-bit colour. A left-to-right gradient, one colour per column.\n */\nfunction gradient(line: string): string {\n const chars = [...line]\n const last = Math.max(1, chars.length - 1)\n const painted = chars.map((ch, i) => {\n if (ch === ' ') return ch\n const [r, g, b] = FROM.map((from, c) =>\n Math.round(from + (((TO[c] ?? from) - from) * i) / last)\n )\n return `\\x1b[38;2;${r};${g};${b}m${ch}`\n })\n return `${painted.join('')}\\x1b[39m`\n}\n\n/**\n * The banner, or `''` where it has no place: a pipe, a file, CI. Shown on a\n * terminal (and with FORCE_COLOR); the gradient only where the terminal says\n * it has true colour, plain green otherwise, no colour under NO_COLOR.\n */\nexport function banner(\n version: string,\n stream: NodeJS.WriteStream = process.stdout\n): string {\n const forced =\n process.env['FORCE_COLOR'] !== undefined &&\n process.env['FORCE_COLOR'] !== '0'\n if (stream.isTTY !== true && !forced) return ''\n const coloured = paint('done', 'x', stream) !== 'x'\n const trueColour =\n coloured &&\n typeof stream.hasColors === 'function' &&\n stream.hasColors(2 ** 24)\n const word = WORD.map((line) =>\n trueColour ? gradient(line) : paint('done', line, stream)\n )\n return [\n '',\n ...word,\n '',\n ` ${bold(`rness v${version}`, stream)}`,\n ` ${paint('idle', 'Context for AI coding agents, across an organization’s repositories', stream)}`,\n '',\n '',\n ].join('\\n')\n}\n","import { readdir } from 'node:fs/promises'\nimport { dirname, join, parse, resolve } from 'node:path'\n\nimport { exists } from './fs.ts'\nimport { isWorkspaceClone } from './manifest.ts'\nimport type { Workspace } from './types.ts'\n\n/** Walk up from `startDir`: a directory holding `.rness/rness.json` is the root. Only when none exists anywhere above does a directory that itself holds `rness.json` count — a standalone checkout of the context repository (CI): that directory is `.rness/`, its parent the root. */\nexport async function findWorkspace(startDir: string): Promise<Workspace> {\n const start = resolve(startDir)\n const { root: fsRoot } = parse(start)\n const ancestors: string[] = []\n for (let dir = start; ; dir = dirname(dir)) {\n ancestors.push(dir)\n if (dir === fsRoot) break\n }\n for (const dir of ancestors) {\n if (await exists(join(dir, '.rness', 'rness.json')))\n return { root: dir, rnessDir: join(dir, '.rness') }\n }\n for (const dir of ancestors) {\n if (await exists(join(dir, 'rness.json')))\n return { root: dirname(dir), rnessDir: dir }\n }\n throw new Error(`no rness workspace found above ${startDir}`)\n}\n\n/** The repositories cloned under `<root>/org`, by name (spec 0009 §3). */\nexport async function clonesIn(root: string): Promise<Set<string>> {\n try {\n const entries = await readdir(join(root, 'org'), { withFileTypes: true })\n return new Set(\n entries\n .filter((e) => e.isDirectory() && isWorkspaceClone(e.name))\n .map((e) => e.name)\n )\n } catch {\n return new Set()\n }\n}\n","import { paint } from './core/style.ts'\n\n/**\n * Shared CLI error contract: one line on stderr, and — only under\n * `RNESS_DEBUG=1` — the stack trace instead of the plain message (the stack\n * already starts with `Error: <message>`, so printing both would repeat it).\n */\nexport function reportError(e: unknown): number {\n const debug = process.env['RNESS_DEBUG'] === '1'\n if (debug && e instanceof Error && e.stack) {\n process.stderr.write(`${e.stack}\\n`)\n } else {\n const message = e instanceof Error ? e.message : String(e)\n process.stderr.write(`${paint('error', message, process.stderr)}\\n`)\n }\n return 1\n}\n","import { createHash } from 'node:crypto'\n\nimport type { Context } from './types.ts'\n\nexport const BEGIN = '<!-- BEGIN rness -->'\nexport const END = '<!-- END rness -->'\n/** Blocks above this size are written with a warning (spec 0003 §4.2). */\nexport const BLOCK_SIZE_WARNING = 32 * 1024\n\nexport interface BlockInput {\n /** Scope name, or null for the workspace-root global block. */\n scope: string | null\n org: string\n /** Path segments between the scope directory and the workspace root (`org/web` → 2; root → 0). */\n depth: number\n context: Context\n}\n\nexport interface RenderedBlock {\n /** The whole block, LF line endings, no trailing newline. */\n text: string\n hash: string\n bytes: number\n}\n\nexport interface BlockHeader {\n /** The CLI version a 0.2–0.4 header named; null for the current form. */\n version: string | null\n scope: string\n hash: string\n}\n\n// The header names no CLI version (spec 0006 §1): nothing read it, and it\n// made every upgrade rewrite every block. The 0.2–0.4 form still parses, so a\n// block written by an older CLI stays current as long as its hash is.\nconst HEADER =\n /^<!-- rness (?:(\\S+) )?· scope: (\\S+) · contract: 1 · hash: ([0-9a-f]{12}) · generated: run `rness sync`, never edit inside this block -->$/\n\nfunction toLf(s: string): string {\n return s.replace(/\\r\\n?/g, '\\n')\n}\n\n/** SHA-256 of the LF-normalised body, first 12 hex characters. */\nexport function blockHash(body: string): string {\n return createHash('sha256')\n .update(toLf(body), 'utf8')\n .digest('hex')\n .slice(0, 12)\n}\n\nfunction intro(scope: string | null, org: string, depth: number): string {\n if (scope === null) {\n return [\n `This is the root of rness workspace \\`${org}\\`. Full context lives in \\`.rness/\\` —`,\n 'start at its `AGENTS.md`, then task-relevant `adr/`, `specs/`, `plans/`; live: `rness context`.',\n 'Every `org/<repo>/` carries its own block with the rules that apply there.',\n ].join('\\n')\n }\n const rel = `${'../'.repeat(depth)}.rness/`\n return [\n `This directory is scope \\`${scope}\\` of rness workspace \\`${org}\\`. Full context lives in`,\n `\\`${rel}\\` — start at its \\`AGENTS.md\\`, then task-relevant \\`adr/\\`, \\`specs/\\`, \\`plans/\\`;`,\n `live: \\`rness context --scope ${scope}\\`. If \\`.rness/\\` is not reachable, this is a`,\n 'standalone clone: the rules below are all you have.',\n ].join('\\n')\n}\n\nfunction header(scope: string | null, hash: string): string {\n return `<!-- rness · scope: ${scope ?? 'global'} · contract: 1 · hash: ${hash} · generated: run \\`rness sync\\`, never edit inside this block -->`\n}\n\n/** Render the block for one scope (or the root) from an already resolved context. */\nexport function renderBlock({\n scope,\n org,\n depth,\n context,\n}: BlockInput): RenderedBlock {\n const standards =\n context.collections.find((c) => c.name === 'standards')?.files ?? []\n const rules =\n standards.length === 0\n ? ['_No standards apply to this scope yet._']\n : standards.map(\n (f) => `<!-- rness: standards/${f.rel} -->\\n${toLf(f.content).trim()}`\n )\n const body = `${intro(scope, org, depth)}\\n\\n## Rules\\n${rules.join('\\n\\n')}`\n const hash = blockHash(body)\n const text = [BEGIN, header(scope, hash), body, END].join('\\n')\n return { text, hash, bytes: Buffer.byteLength(text, 'utf8') }\n}\n\n/** Parse the header line of a block; null when the line is not a rness header. */\nexport function parseHeader(line: string): BlockHeader | null {\n const m = HEADER.exec(line.trimEnd())\n if (m === null) return null\n return { version: m[1] ?? null, scope: m[2] ?? '', hash: m[3] ?? '' }\n}\n\n/** The hashed body of a block given its lines (BEGIN, header, body…, END). */\nexport function bodyOf(blockLines: string[]): string {\n return blockLines.slice(2, -1).join('\\n')\n}\n\n/**\n * Is this block (BEGIN, header, body…, END) what a fresh render would write?\n * By hash, never by text: the header's hash is the fresh one, and the body\n * still hashes to it — a hand edit inside the block breaks the second half.\n */\nexport function isCurrentBlock(\n blockLines: string[],\n freshHash: string\n): boolean {\n const header = parseHeader(blockLines[1] ?? '')\n return (\n header !== null &&\n header.hash === freshHash &&\n blockHash(bodyOf(blockLines)) === freshHash\n )\n}\n","import { parse } from 'yaml'\n\nimport type { Fields } from './types.ts'\n\n// The inner group is optional so that `---\\n---\\n` (an empty block with no line\n// between the fences) is still recognised as front matter.\nconst FRONT_MATTER = /^---\\r?\\n(?:([\\s\\S]*?)\\r?\\n)?---(?:\\r?\\n|$)/\n\nfunction fail(message: string): never {\n throw new Error(`front matter: ${message}`)\n}\n\n/** Strip a leading UTF-8 BOM so `---` is still recognised as the first thing in the file. */\nfunction stripBom(source: string): string {\n return source.startsWith('') ? source.slice(1) : source\n}\n\n/**\n * Parse the leading `---` block as YAML (1.2 core schema: `2026-09-07` stays a\n * string, `1` becomes a number). Returns null when there is no block, `{}`\n * for an empty block, and throws a `front matter:`-prefixed error when the\n * YAML is invalid or is not a mapping.\n */\nexport function parseFrontMatter(source: string): Fields | null {\n const match = stripBom(source).match(FRONT_MATTER)\n if (match === null) return null\n const block = match[1] ?? ''\n if (block.trim() === '') return {}\n let doc: unknown\n try {\n // 'error': suppress the printed YAMLWarning (e.g. an unresolved `!!tag`)\n // without silencing real parse errors — `logLevel: 'silent'` would do that too.\n doc = parse(block, { logLevel: 'error' })\n } catch (e) {\n fail(\n e instanceof Error\n ? (e.message.split('\\n')[0] ?? 'invalid YAML').replace(/:$/, '')\n : 'invalid YAML'\n )\n }\n if (doc === null || doc === undefined) return {}\n if (typeof doc !== 'object' || Array.isArray(doc))\n fail('block must be a mapping of keys to values')\n return doc as Fields\n}\n\n/**\n * The document text with its leading `---` block removed, along with the blank\n * lines that separated it from the body. Purely textual: a block whose YAML is\n * invalid is still stripped, so a broken file never leaks `---` fences into a\n * rendered block. Returns the (BOM-stripped) source unchanged when there is no\n * front matter.\n */\nexport function stripFrontMatter(source: string): string {\n const text = stripBom(source)\n const match = text.match(FRONT_MATTER)\n if (match === null) return text\n return text.slice(match[0].length).replace(/^(?:[ \\t]*\\r?\\n)+/, '')\n}\n\nexport function extractTitle(source: string): string | null {\n return (\n stripBom(source)\n .match(/^# (.+)$/m)?.[1]\n ?.trim() ?? null\n )\n}\n","import { glob, readFile } from 'node:fs/promises'\nimport { join, posix, sep } from 'node:path'\n\nimport {\n extractTitle,\n parseFrontMatter,\n stripFrontMatter,\n} from './frontmatter.ts'\nimport type { MarkdownItem } from './types.ts'\n\nfunction toPosix(rel: string): string {\n return rel.split(sep).join(posix.sep)\n}\n\n/**\n * Every `*.md` under `dir`, recursively, sorted by `rel`. A missing directory\n * yields []. A file whose front matter fails to parse is kept with\n * `fields: null` and the error in `fieldsError`, so one broken file cannot\n * hide a whole collection.\n */\nexport async function collectMarkdown(dir: string): Promise<MarkdownItem[]> {\n const rels: string[] = []\n for await (const rel of glob('**/*.md', { cwd: dir })) rels.push(toPosix(rel))\n const items = await Promise.all(\n rels.map(async (rel): Promise<MarkdownItem> => {\n const path = join(dir, ...rel.split(posix.sep))\n const body = await readFile(path, 'utf8')\n let fields: MarkdownItem['fields'] = null\n let fieldsError: string | null = null\n try {\n fields = parseFrontMatter(body)\n } catch (e) {\n fieldsError = e instanceof Error ? e.message : String(e)\n }\n return {\n path,\n rel,\n fields,\n fieldsError,\n title: extractTitle(body),\n body,\n content: stripFrontMatter(body),\n }\n })\n )\n return items.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0))\n}\n","import type { Manifest } from './types.ts'\n\nfunction isPrefix(prefix: string, target: string): boolean {\n return prefix === target || target.startsWith(`${prefix}/`)\n}\n\n/** The scope whose `path` is the longest path-segment prefix of `relDir`; null = global. */\nexport function resolveScope(\n manifest: Manifest,\n relDir: string\n): string | null {\n let best: string | null = null\n let bestLen = -1\n for (const [name, entry] of Object.entries(manifest.scopes)) {\n if (isPrefix(entry.path, relDir) && entry.path.length > bestLen) {\n best = name\n bestLen = entry.path.length\n }\n }\n return best\n}\n\n/** `scope` then its transitive `extends`, nearest first, de-duplicated. Throws on a cycle. */\nexport function scopeChain(manifest: Manifest, scope: string | null): string[] {\n if (scope === null) return []\n const chain: string[] = []\n const seen = new Set<string>()\n const visit = (name: string, stack: Set<string>): void => {\n if (stack.has(name)) throw new Error(`extends cycle at scope \"${name}\"`)\n if (seen.has(name)) return\n seen.add(name)\n chain.push(name)\n stack.add(name)\n const entry = Object.hasOwn(manifest.scopes, name)\n ? manifest.scopes[name]\n : undefined\n for (const target of entry?.extends ?? []) visit(target, stack)\n stack.delete(name)\n }\n visit(scope, new Set())\n return chain\n}\n","import { join } from 'node:path'\n\nimport { collectMarkdown } from './collect.ts'\nimport { scopeChain } from './scope.ts'\nimport type {\n CollectionName,\n Context,\n ContextCollection,\n ContextFile,\n Manifest,\n MarkdownItem,\n} from './types.ts'\n\nexport const COLLECTIONS: readonly CollectionName[] = [\n 'standards',\n 'adr',\n 'specs',\n 'plans',\n 'skills',\n]\n\n/** The first path segment of `rel`, or null for a file at the collection root. */\nexport function ownerScope(rel: string): string | null {\n const slash = rel.indexOf('/')\n return slash === -1 ? null : rel.slice(0, slash)\n}\n\ntype Owned = MarkdownItem & { scope: string | null }\n\n/**\n * The file's place defines its scope (spec 0003 §4.0): collection-root files\n * are global, `<scope>/**` files belong to that scope. A file under a\n * directory outside the chain is ignored; front matter never re-routes.\n */\nasync function assembleCollection(\n dir: string,\n name: CollectionName,\n chain: string[]\n): Promise<ContextCollection> {\n const items = await collectMarkdown(dir)\n const groups = new Map<string, Owned[]>(chain.map((s) => [s, []]))\n const rootFiles: Owned[] = []\n for (const item of items) {\n const owner = ownerScope(item.rel)\n if (owner === null) rootFiles.push({ ...item, scope: null })\n else groups.get(owner)?.push({ ...item, scope: owner })\n }\n const files: ContextFile[] = []\n const push = (f: Owned): void => {\n files.push({\n rel: f.rel,\n scope: f.scope,\n title: f.title,\n body: f.body,\n content: f.content,\n })\n }\n for (const s of chain) for (const f of groups.get(s) ?? []) push(f)\n for (const f of rootFiles) push(f)\n return { name, files }\n}\n\nexport interface AssembleInput {\n rnessDir: string\n manifest: Manifest\n scope: string | null\n}\n\n/** Resolve every scoped collection for `scope` (null = global only). */\nexport async function assembleContext({\n rnessDir,\n manifest,\n scope,\n}: AssembleInput): Promise<Context> {\n const chain = scopeChain(manifest, scope)\n const collections = await Promise.all(\n COLLECTIONS.map((name) =>\n assembleCollection(join(rnessDir, name), name, chain)\n )\n )\n return { scope, collections }\n}\n","import { join } from 'node:path'\n\nimport { BEGIN, END } from './block.ts'\nimport { isSymlink, readOrNull, writeFileAtomic } from './fs.ts'\n\nexport type FindResult =\n | { kind: 'none' }\n | { kind: 'one'; begin: number; end: number }\n | { kind: 'error'; message: string }\n\n/** Locate the single rness span (line indexes, inclusive). Anything but 0 or 1 span is an error. */\nexport function findBlock(lines: string[]): FindResult {\n const begins: number[] = []\n const ends: number[] = []\n lines.forEach((line, i) => {\n const l = line.trimEnd()\n if (l === BEGIN) begins.push(i)\n if (l === END) ends.push(i)\n })\n if (begins.length === 0 && ends.length === 0) return { kind: 'none' }\n const begin = begins[0]\n const end = ends[0]\n if (\n begins.length !== 1 ||\n ends.length !== 1 ||\n begin === undefined ||\n end === undefined\n ) {\n return {\n kind: 'error',\n message: `expected exactly one ${BEGIN} … ${END} span, found ${begins.length} BEGIN and ${ends.length} END`,\n }\n }\n if (end < begin)\n return { kind: 'error', message: `${END} comes before ${BEGIN}` }\n return { kind: 'one', begin, end }\n}\n\nexport type MergeResult =\n { ok: true; text: string; changed: boolean } | { ok: false; error: string }\n\n/**\n * Merge `block` (LF, no trailing newline) into `existing` (spec 0003 §4.3):\n * missing file → the block; one span → replaced in place; no span → after a\n * leading `# H1` + blank line, else at the top. Bytes outside the span are\n * preserved, including the file's line-ending style.\n */\nexport function mergeBlock(\n existing: string | null,\n block: string\n): MergeResult {\n if (existing === null) return { ok: true, text: `${block}\\n`, changed: true }\n const eol = existing.includes('\\r\\n') ? '\\r\\n' : '\\n'\n const lines = existing.split(/\\r?\\n/)\n const found = findBlock(lines)\n if (found.kind === 'error') return { ok: false, error: found.message }\n const rendered = block.split('\\n').join(eol)\n // Offsets of every line start in the original text, so the regions outside the\n // span are copied byte for byte — a file mixing LF and CRLF keeps every separator.\n const starts: number[] = [0]\n for (const m of existing.matchAll(/\\r?\\n/g))\n starts.push((m.index ?? 0) + m[0].length)\n const lineStart = (i: number): number => starts[i] ?? existing.length\n let text: string\n if (found.kind === 'one') {\n const endLine = lines[found.end] ?? ''\n const afterEnd = lineStart(found.end) + endLine.length\n text = `${existing.slice(0, lineStart(found.begin))}${rendered}${existing.slice(afterEnd)}`\n } else if (\n lines.length >= 3 &&\n (lines[0] ?? '').startsWith('# ') &&\n lines[1] === ''\n ) {\n const at = lineStart(2)\n text = `${existing.slice(0, at)}${rendered}${eol}${eol}${existing.slice(at)}`\n } else {\n text = `${rendered}${eol}${eol}${existing}`\n }\n return { ok: true, text, changed: text !== existing }\n}\n\n/**\n * `CLAUDE.md` next to an `AGENTS.md`: create with `@AGENTS.md`, or prepend that\n * line when absent. A symlinked `CLAUDE.md` is left exactly as it is — reading\n * would follow it and the atomic rename would replace the link with a regular\n * file holding a copy of its target. (`sync` skips such a directory outright;\n * this guard is defence in depth for any other caller.)\n */\nexport async function ensureClaudeMd(\n dir: string\n): Promise<'created' | 'prepended' | 'unchanged'> {\n const file = join(dir, 'CLAUDE.md')\n if (await isSymlink(file)) return 'unchanged'\n const existing = await readOrNull(file)\n if (existing === null) {\n await writeFileAtomic(file, '@AGENTS.md\\n')\n return 'created'\n }\n if (existing.split(/\\r?\\n/).some((l) => l.trim() === '@AGENTS.md'))\n return 'unchanged'\n const eol = existing.includes('\\r\\n') ? '\\r\\n' : '\\n'\n await writeFileAtomic(file, `@AGENTS.md${eol}${existing}`)\n return 'prepended'\n}\n","import { join } from 'node:path'\n\nimport {\n BLOCK_SIZE_WARNING,\n isCurrentBlock,\n renderBlock,\n} from '../core/block.ts'\nimport { assembleContext } from '../core/context.ts'\nimport type { CommandDeps } from '../core/deps.ts'\nimport { exists, isSymlink, readOrNull, writeFileAtomic } from '../core/fs.ts'\nimport { clone, isClean, pullFastForward } from '../core/git.ts'\nimport { githubProvider } from '../core/github-oauth-provider.ts'\nimport { loadManifest, workspaceName } from '../core/manifest.ts'\nimport { ensureClaudeMd, findBlock, mergeBlock } from '../core/merge.ts'\nimport { rnessCommand } from '../core/pm.ts'\nimport type { GitCredentials } from '../core/provider.ts'\nimport { type Terminal, defaultTerminal } from '../core/terminal.ts'\nimport {\n CHECKING,\n INSTEAD_OF_LINES,\n defaultTransport,\n isSshUrl,\n sshWorkspaceLines,\n testGithubSsh,\n} from '../core/transport.ts'\nimport type { Manifest } from '../core/types.ts'\nimport { type Line, type Ui, makeUi, plainUi } from '../core/ui.ts'\nimport { clonesIn, findWorkspace } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\n\nexport interface SyncOptions {\n /** Only this scope's block (the root block is skipped). */\n scope?: string\n /** Render and compare; write nothing; exit 1 when any block differs. */\n check?: boolean\n /** `git pull --ff-only` in every clean clone. */\n pull?: boolean\n /** Clone every catalogue repository missing from `org/`; by default none is cloned. */\n all?: boolean\n /** Skip the confirmation prompt. */\n yes?: boolean\n /** Internal (tests): directory to resolve from; default `process.cwd()`. */\n cwd?: string\n}\n\ninterface Target {\n scope: string | null\n dir: string\n depth: number\n label: string\n}\n\n// Excluded from the cleanliness check whatever their status: sync writes them itself. A\n// user's uncommitted edit to a tracked AGENTS.md is therefore not a veto — git pull\n// --ff-only still refuses to overwrite it and that surfaces as a problem.\nconst MANAGED_FILES = ['AGENTS.md', 'CLAUDE.md']\n\nfunction targetsOf(\n manifest: Manifest,\n root: string,\n only: string | undefined\n): Target[] {\n const targets: Target[] = []\n if (only === undefined)\n targets.push({ scope: null, dir: root, depth: 0, label: 'AGENTS.md' })\n for (const [name, entry] of Object.entries(manifest.scopes)) {\n if (only !== undefined && name !== only) continue\n const segments = entry.path.split('/')\n targets.push({\n scope: name,\n dir: join(root, ...segments),\n depth: segments.length,\n label: `${entry.path}/AGENTS.md`,\n })\n }\n return targets\n}\n\n/** The picker's \"select all\" entry; no repository name can take this value. */\nconst SELECT_ALL = '*'\n\n/** The directories under `org/` — the user's workspace (ADR 0008). */\n/**\n * In a terminal: offer the catalogue repositories that are not cloned, or\n * confirm when there are none. Returns the repositories to clone, or an exit\n * code when the run stops here.\n */\nasync function askWhatToSync(input: {\n org: string\n missing: readonly string[]\n offer: boolean\n terminal: Terminal\n ui: Ui\n}): Promise<string[] | number> {\n if (!input.terminal.isTty()) {\n process.stderr.write(\n 'rness sync writes files; pass --yes to run without a prompt\\n'\n )\n return 2\n }\n const p = await input.terminal.prompts()\n const cancelled = (): number => {\n input.ui.cancelled()\n return 1\n }\n if (input.offer && input.missing.length > 0) {\n const answer = await p.autocompleteMultiselect({\n message: 'Do you want to sync as well?',\n options: [\n {\n value: SELECT_ALL,\n label: 'Select all',\n hint: `${input.missing.length} repositories from rness.json`,\n },\n ...input.missing.map((name) => ({ value: name, label: name })),\n ],\n required: false,\n placeholder: 'Type to filter',\n })\n if (p.isCancel(answer) || !Array.isArray(answer)) return cancelled()\n return answer.includes(SELECT_ALL)\n ? [...input.missing]\n : answer.filter((name) => name !== SELECT_ALL)\n }\n const ok = await p.confirm({\n message: `Sync workspace \\`${input.org}\\`: rewrite the rness blocks of your clones?`,\n })\n if (p.isCancel(ok) || ok !== true) return cancelled()\n return []\n}\n\n/**\n * `rness sync`: write the blocks of the repositories cloned in `org/` (spec\n * 0003 §4). The clones are the workspace; `rness.json` is the organization's\n * catalogue, so a catalogue repository that is not cloned is offered (in a\n * terminal) or named, never cloned silently — `--all` clones them all.\n * Returns the exit code.\n */\nexport async function syncCommand(\n opts: SyncOptions,\n deps: Partial<CommandDeps> = {}\n): Promise<number> {\n const terminal = deps.terminal ?? defaultTerminal\n const transport = deps.transport ?? defaultTransport\n // Only a clone or a pull needs it, and it reads the stored login.\n let provider = deps.provider\n const credentialsFor = async (url: string): Promise<GitCredentials | null> =>\n (provider ??= await githubProvider()).credentialsFor(url)\n const cwd = opts.cwd ?? process.cwd()\n const check = opts.check === true\n // Inside another command's session (`add`, `create`) its reporter is used;\n // on its own, a sync that asks questions is a session of its own.\n const ownUi = deps.ui === undefined\n const ui =\n deps.ui ??\n (opts.yes !== true && !check ? await makeUi(terminal) : { ...plainUi })\n try {\n const ws = await findWorkspace(cwd)\n const manifest = await loadManifest(ws.rnessDir)\n const org = workspaceName(manifest, ws.root)\n if (ownUi) ui.intro(`Sync workspace ${org}`)\n if (\n opts.scope !== undefined &&\n !Object.hasOwn(manifest.scopes, opts.scope)\n ) {\n process.stderr.write(`unknown scope: ${opts.scope}\\n`)\n return 1\n }\n\n const clones = await clonesIn(ws.root)\n const missing = Object.keys(manifest.repos).filter((n) => !clones.has(n))\n let toClone = new Set<string>(opts.all === true && !check ? missing : [])\n if (!check && opts.yes !== true) {\n const answer = await askWhatToSync({\n org,\n missing,\n // `--all` already answers; `--scope` is about one block, not the workspace.\n offer: opts.all !== true && opts.scope === undefined,\n terminal,\n ui,\n })\n if (typeof answer === 'number') return answer\n if (opts.all !== true) toClone = new Set(answer)\n }\n\n // rness.json is authoritative: a git@ entry is cloned over SSH or not at\n // all. Without SSH access, stop before the first clone (spec 0005 §3).\n const overSsh = [...toClone].some((name) => {\n const repo = manifest.repos[name]\n return repo !== undefined && isSshUrl(repo.url, transport.hosts)\n })\n // Only a clone over SSH can make git ask something on the terminal.\n if (!overSsh) ui.gitIsSilent = true\n if (overSsh) {\n const interactive = opts.yes !== true && terminal.isTty()\n const { access, unattended } = await testGithubSsh(\n transport,\n interactive,\n () => ui.line(...CHECKING)\n )\n if (unattended) ui.gitIsSilent = true\n if (!access.ok) {\n process.stderr.write(\n `${[...sshWorkspaceLines(access.reason), ...INSTEAD_OF_LINES].join('\\n')}\\n`\n )\n return 1\n }\n }\n\n // A status line as `[verb, rest]`, or a sentence; said once the pass ends.\n const lines: (Line | string)[] = []\n const problems: string[] = []\n\n try {\n // 1. Repositories: clone only what was asked for; pull only on request,\n // only clean trees.\n const notCloned = new Set<string>()\n for (const [name, repo] of Object.entries(manifest.repos)) {\n const dir = join(ws.root, 'org', name)\n const label = `org/${name}`\n if (!(await exists(dir))) {\n if (!toClone.has(name)) {\n notCloned.add(name)\n continue\n }\n try {\n const credentials = await credentialsFor(repo.url)\n await ui.step({ doing: `cloning ${label}`, git: true }, () =>\n clone(repo.url, dir, credentials)\n )\n lines.push(['cloned', `${label}`])\n } catch (e) {\n problems.push(\n `${label}: ${e instanceof Error ? e.message : String(e)}`\n )\n }\n } else if (opts.pull === true && !check) {\n try {\n if (!(await isClean(dir, MANAGED_FILES))) {\n lines.push(['skipped', `${label} (working tree not clean)`])\n continue\n }\n const credentials = await credentialsFor(repo.url)\n await ui.step({ doing: `pulling ${label}`, git: true }, () =>\n pullFastForward(dir, credentials)\n )\n lines.push(['pulled', `${label}`])\n } catch (e) {\n problems.push(\n `${label}: ${e instanceof Error ? e.message : String(e)}`\n )\n }\n }\n }\n\n if (notCloned.size > 0)\n lines.push(\n `not cloned: ${[...notCloned].join(', ')} (${rnessCommand()} add <name>, or ${rnessCommand()} sync --all)`\n )\n // A clone the catalogue does not know gets no block: no scope declares\n // its rules. Say how to bring it in rather than skipping it silently.\n const scoped = new Set(\n Object.values(manifest.scopes).map((s) => s.path.split('/')[1])\n )\n const undeclared = [...clones].filter(\n (n) => !Object.hasOwn(manifest.repos, n) && !scoped.has(n)\n )\n if (undeclared.length > 0)\n lines.push(\n `not in rness.json: ${undeclared.join(', ')} (${rnessCommand()} add <name> declares it)`\n )\n\n // 2. Blocks — only where repositories live; a standalone context checkout has no org/.\n if (!(await exists(join(ws.root, 'org')))) {\n lines.push(['skipped', 'blocks (no org/ directory here)'])\n } else {\n let differences = 0\n for (const t of targetsOf(manifest, ws.root, opts.scope)) {\n if (!(await exists(t.dir))) {\n // A scope inside a repository that is not cloned is covered by\n // the `not cloned:` line; only a directory missing from a present\n // clone (or from no repository at all) is worth its own line.\n const repo = t.label.split('/')[1]\n if (\n !t.label.startsWith('org/') ||\n repo === undefined ||\n !notCloned.has(repo)\n )\n lines.push(['skipped', `${t.label} (directory not present)`])\n continue\n }\n // One of the pair symlinked to the other (the common `CLAUDE.md →\n // AGENTS.md`) is left untouched: reading follows the link, and the\n // atomic rename would replace the link with a duplicate of its target.\n const linked = await Promise.all(\n MANAGED_FILES.map((f) => isSymlink(join(t.dir, f)))\n )\n if (linked.includes(true)) {\n lines.push(['skipped', `${t.label} (symlink)`])\n continue\n }\n const context = await assembleContext({\n rnessDir: ws.rnessDir,\n manifest,\n scope: t.scope,\n })\n const block = renderBlock({\n scope: t.scope,\n org,\n depth: t.depth,\n context,\n })\n if (block.bytes > BLOCK_SIZE_WARNING) {\n ui.warn(\n `${t.label}: block is ${Math.round(block.bytes / 1024)} KB (over 32 KB)`\n )\n }\n const file = join(t.dir, 'AGENTS.md')\n const existing = await readOrNull(file)\n // Current by its hash, not by its text: a block an older CLI wrote,\n // whose header still names that version, is left byte for byte.\n const existingLines = existing === null ? [] : existing.split(/\\r?\\n/)\n const span = findBlock(existingLines)\n const current =\n span.kind === 'one' &&\n isCurrentBlock(\n existingLines.slice(span.begin, span.end + 1),\n block.hash\n )\n const merged = current\n ? { ok: true as const, text: existing ?? '', changed: false }\n : mergeBlock(existing, block.text)\n if (!merged.ok) {\n problems.push(`${t.label}: ${merged.error}`)\n continue\n }\n if (!merged.changed) {\n lines.push(['unchanged', `${t.label}`])\n if (!check) await ensureClaudeMd(t.dir)\n continue\n }\n if (check) {\n lines.push(['stale', `${t.label}`])\n differences += 1\n continue\n }\n await writeFileAtomic(file, merged.text)\n await ensureClaudeMd(t.dir)\n lines.push(['updated', `${t.label}`])\n }\n if (check && differences > 0)\n problems.push(\n `${differences} block(s) out of date — run ${rnessCommand()} sync`\n )\n }\n\n return problems.length > 0 ? 1 : 0\n } finally {\n // Both flushes run even when something above throws, and stdout precedes\n // stderr so the report reads in order. The exit code above is computed\n // before this block, so it is unaffected.\n for (const l of lines)\n if (typeof l === 'string') ui.hint(l)\n else ui.line(l[0], l[1])\n for (const p of problems) ui.error(p)\n if (ownUi)\n ui.outro(\n problems.length > 0\n ? 'Done, with problems'\n : check\n ? 'Checked'\n : 'Your clones carry the current context',\n problems.length > 0 ? 'warn' : 'done'\n )\n }\n } catch (e) {\n return reportError(e)\n }\n}\n","import { paint } from './style.ts'\n\nconst FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']\nconst INTERVAL_MS = 80\n/** Back to column 0, erase the line. */\nconst CLEAR_LINE = '\\r\\x1b[2K'\n\nexport interface StepOptions {\n /** What is happening, as a status line in the making: `cloning org/api`. */\n label: string\n /**\n * Animate a spinner. Off for anything that runs git: over SSH, git's `ssh`\n * may ask for a passphrase on the terminal, and a line redrawn every 80 ms\n * would shred the question. The label is then written once and erased.\n */\n animate: boolean\n stream?: NodeJS.WriteStream\n}\n\nfunction isLive(stream: NodeJS.WriteStream): boolean {\n return (\n stream.isTTY === true &&\n process.env['TERM'] !== 'dumb' &&\n process.env['CI'] === undefined\n )\n}\n\n/**\n * Run `work` with a transient line saying what is going on (spec 0007 §5).\n * The line is erased when `work` settles, and the caller prints the step's\n * status line as it always did — so off a terminal, where nothing transient\n * is written, the output is byte for byte what it was.\n */\nexport async function step<T>(\n options: StepOptions,\n work: () => Promise<T>\n): Promise<T> {\n const stream = options.stream ?? process.stdout\n if (!isLive(stream)) return work()\n const draw = (frame: string): void => {\n rawWrite(\n `${CLEAR_LINE}${paint('info', frame, stream)} ${paint('idle', options.label, stream)}`\n )\n }\n let timer: NodeJS.Timeout | undefined\n let shown = true\n // Erase the label, once: when the work ends, or as soon as the work itself\n // writes — its first line must not land behind `… syncing the blocks`.\n const erase = (): void => {\n if (!shown) return\n shown = false\n if (timer !== undefined) clearInterval(timer)\n rawWrite(CLEAR_LINE)\n }\n // Both streams share the terminal's line, so a write to either erases it.\n const rawWrite = stream.write.bind(stream) as NodeJS.WriteStream['write']\n const rawErr = process.stderr.write.bind(\n process.stderr\n ) as NodeJS.WriteStream['write']\n type Write = NodeJS.WriteStream['write']\n // `write` is overloaded; the guard only forwards, whatever the overload.\n const guard = (raw: Write): Write =>\n ((...args: Parameters<Write>) => {\n erase()\n return raw(...args)\n }) as Write\n if (options.animate) {\n let i = 0\n draw(FRAMES[0] ?? '')\n timer = setInterval(() => {\n i = (i + 1) % FRAMES.length\n if (shown) draw(FRAMES[i] ?? '')\n }, INTERVAL_MS)\n // Never the reason the process stays alive.\n timer.unref()\n } else {\n draw('…')\n }\n stream.write = guard(rawWrite)\n if (process.stderr !== stream) process.stderr.write = guard(rawErr)\n try {\n return await work()\n } finally {\n stream.write = rawWrite\n if (process.stderr !== stream) process.stderr.write = rawErr\n erase()\n }\n}\n","import { step as transientStep } from './progress.ts'\nimport { type Tone, badge, grey, paint, status, toneOf, warn } from './style.ts'\nimport type { Prompts, Terminal } from './terminal.ts'\n\n// How an interactive command speaks (spec 0007 §5b). Two renderings of the\n// same calls: `plain` — the status column, the bytes scripts and tests read —\n// and `session`, clack's gutter from `intro` to `outro`, in a terminal.\n\n/** A status line: the verb of the column, what follows it. */\nexport type Line = readonly [verb: string, rest: string]\n\nexport interface StepOptions {\n /** The transient label of the plain look: `cloning org/api`. */\n doing: string\n /** What the session look shows while it runs; defaults to `doing`, tidied. */\n sentence?: string\n /** The step runs git: it animates only when git is known not to prompt. */\n git?: boolean\n /**\n * The plain look has already said what it needs (`listing acme\n * repositories…`): only the session look prints the step's outcome.\n */\n quiet?: boolean\n}\n\nexport interface Ui {\n /** True for the session look. */\n readonly session: boolean\n /**\n * Set once rness knows git will not ask anything on the terminal (SSH works\n * unattended, or the clones are not over SSH): git steps may then animate.\n */\n gitIsSilent: boolean\n intro(title: string): void\n /** The last word of a session: green for a success, the tone given otherwise. */\n outro(message: string, tone?: Tone): void\n /** `sentence` replaces `verb rest` in the session look. */\n line(verb: string, rest: string, sentence?: string): void\n warn(text: string): void\n /** A block of commands or facts under a title. */\n note(title: string, lines: readonly string[]): void\n /** An aside: a plain line in the plain look, dimmed in the session one. */\n hint(text: string, stream?: 'stdout' | 'stderr'): void\n /** A handled error the command goes on after. */\n error(text: string): void\n cancelled(): void\n /** Run `work`; then print `done(result)` unless it answers null. */\n step<T>(\n options: StepOptions,\n work: () => Promise<T>,\n done?: (result: T) => Line | null\n ): Promise<T>\n}\n\nconst capitalise = (s: string): string =>\n s === '' ? s : `${s[0]?.toUpperCase() ?? ''}${s.slice(1)}`\n\n/** `cloning org/api` → `Cloning org/api`. */\nconst tidy = (label: string): string =>\n capitalise(label.replace(/\\s+/g, ' ').trim())\n\nexport const plainUi: Ui = {\n session: false,\n gitIsSilent: false,\n intro: () => undefined,\n outro: () => undefined,\n line: (verb, rest) => {\n process.stdout.write(`${status(verb, rest)}\\n`)\n },\n warn: (text) => {\n process.stderr.write(`${warn(text)}\\n`)\n },\n note: (title, lines) => {\n process.stdout.write(\n ['', `${title}:`, ...lines.map((l) => ` ${l}`), ''].join('\\n')\n )\n },\n hint: (text, stream = 'stdout') => {\n process[stream].write(`${text}\\n`)\n },\n error: (text) => {\n process.stderr.write(`${text}\\n`)\n },\n cancelled: () => {\n process.stderr.write('cancelled\\n')\n },\n async step(options, work, done) {\n // Animation is the install's; git steps write their label once.\n const result = await transientStep(\n { label: options.doing, animate: options.git !== true },\n work\n )\n const line = options.quiet === true ? null : (done?.(result) ?? null)\n if (line !== null) this.line(line[0], line[1])\n return result\n },\n}\n\nexport type Session = Required<\n Pick<Prompts, 'intro' | 'outro' | 'cancel' | 'note' | 'log' | 'spinner'>\n>\n\n/** The session look over clack's functions; exported for tests, which script them. */\n/** What a line says, once its tone has a symbol of its own to carry it. */\nconst IDLE_SYMBOL = '\\u00b7'\n\nexport function sessionUi(p: Session): Ui {\n // clack draws the gutter symbol, so it is the coloured column the plain\n // look puts first (spec 0007 §4): the text beside it stays neutral, which\n // is what lets a path lead and the paths of a list align (§5d).\n const say = (verb: string, text: string): void => {\n const tone = toneOf(verb)\n if (tone === 'done') p.log.success(text)\n else if (tone === 'warn') p.log.warn(text)\n else if (tone === 'error') p.log.error(text)\n else if (tone === 'idle')\n p.log.message(paint('idle', text), {\n symbol: paint('idle', IDLE_SYMBOL),\n })\n else p.log.info(text)\n }\n return {\n session: true,\n gitIsSilent: false,\n intro: (title) => {\n p.intro(badge(title))\n },\n outro: (message, tone = 'done') => {\n // The verdict closes a session the way the title opened it: on a\n // background, legible before the words are read (spec 0007 §5c).\n p.outro(badge(message, tone))\n },\n line: (verb, rest, sentence) => {\n // The path leads, the verb follows: in a list the paths align on the\n // left instead of starting at whatever width the verb happened to be.\n say(verb, sentence ?? `${rest} ${verb}`)\n },\n warn: (text) => {\n p.log.warn(text)\n },\n note: (title, lines) => {\n p.note(lines.join('\\n'), title, { format: (line) => grey(line) })\n },\n hint: (text) => {\n p.log.message(paint('idle', text))\n },\n error: (text) => {\n p.log.error(text)\n },\n cancelled: () => {\n p.cancel('Cancelled')\n },\n async step(options, work, done) {\n const label = options.sentence ?? tidy(options.doing)\n // The verb is kept beside its text: a finished step is said by `say`,\n // so its symbol is the one a plain line of the same tone would wear.\n const finish = (\n result: Awaited<ReturnType<typeof work>>\n ): readonly [string, string] | null => done?.(result) ?? null\n const label_ = (line: readonly [string, string]): string =>\n `${line[1]} ${line[0]}`\n // A spinner redraws its line: not while git's ssh may be asking for a\n // passphrase on the same terminal.\n if (options.git === true && !this.gitIsSilent) {\n p.log.message(paint('idle', `${label}…`))\n const result = await work()\n const line = finish(result)\n if (line !== null) say(line[0], label_(line))\n return result\n }\n const spin = p.spinner()\n spin.start(label)\n try {\n const result = await work()\n const line = finish(result)\n spin.stop(line === null ? label : label_(line))\n return result\n } catch (e) {\n spin.error(`${label} — failed`)\n throw e\n }\n },\n }\n}\n\n/** The session look needs a real terminal; everything else gets the plain one. */\nexport async function makeUi(terminal: Terminal): Promise<Ui> {\n const live =\n terminal.isTty() &&\n process.stdout.isTTY === true &&\n process.env['CI'] === undefined &&\n process.env['TERM'] !== 'dumb'\n if (!live) return { ...plainUi }\n const p = await terminal.prompts()\n if (\n p.intro === undefined ||\n p.outro === undefined ||\n p.cancel === undefined ||\n p.note === undefined ||\n p.log === undefined ||\n p.spinner === undefined\n )\n return { ...plainUi }\n return sessionUi({\n intro: p.intro,\n outro: p.outro,\n cancel: p.cancel,\n note: p.note,\n log: p.log,\n spinner: p.spinner,\n })\n}\n","import { basename, join } from 'node:path'\n\nimport type { CommandDeps } from '../core/deps.ts'\nimport { exists } from '../core/fs.ts'\nimport { githubProvider } from '../core/github-oauth-provider.ts'\nimport {\n CONTEXT_REPO,\n loadManifest,\n parseRepoSpec,\n workspaceName,\n} from '../core/manifest.ts'\nimport type { GitCredentials } from '../core/provider.ts'\nimport {\n type AddRepositoryResult,\n addRepository,\n workspaceDirs,\n} from '../core/repos.ts'\nimport { defaultTerminal } from '../core/terminal.ts'\nimport {\n CHECKING,\n defaultTransport,\n httpsFlagLine,\n isSshUrl,\n sshWorkspaceLines,\n testGithubSsh,\n usingRest,\n usingSentence,\n} from '../core/transport.ts'\nimport { type Ui, makeUi, plainUi } from '../core/ui.ts'\nimport { findWorkspace } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\nimport { syncCommand } from './sync.ts'\n\nexport interface AddOptions {\n /** Comma-separated sub-directories to declare as scopes extending the repository scope. */\n scopes?: string\n /** Force `git@github.com:` without the SSH test. */\n ssh?: boolean\n /** Force `https://github.com/` without the SSH test. */\n https?: boolean\n /** Internal: remote base (`file:///…/`, another host); wins over both flags and skips the SSH test. */\n host?: string\n yes?: boolean\n /** Internal (tests): directory to resolve from. */\n cwd?: string\n}\n\n/** One `declared scope …` line per scope of `result` not named in `already`. */\nfunction printDeclared(\n ui: Ui,\n result: AddRepositoryResult,\n already: ReadonlySet<string>\n): void {\n for (const name of result.declared) {\n if (already.has(name)) continue\n const entry = result.manifest.scopes[name]\n if (entry === undefined) continue\n const ext =\n entry.extends.length === 0 ? '' : `, extends ${entry.extends.join(', ')}`\n ui.line('declared', `scope ${name} (${entry.path}${ext})`)\n }\n}\n\nconst FULL_URL = /^(https?:\\/\\/|git@|ssh:\\/\\/|file:\\/\\/)/\n\n/**\n * `rness add <repo>`: clone or adopt, declare, sync (spec 0003 §3). A name is\n * written over SSH when github.com accepts the user's key, over HTTPS\n * otherwise — except in a workspace that clones over SSH, which never falls\n * back silently (spec 0005). Returns the exit code.\n */\nexport async function addCommand(\n spec: string,\n opts: AddOptions,\n deps: Partial<CommandDeps> = {}\n): Promise<number> {\n const terminal = deps.terminal ?? defaultTerminal\n const transport = deps.transport ?? defaultTransport\n let provider = deps.provider\n const credentialsFor = async (url: string): Promise<GitCredentials | null> =>\n (provider ??= await githubProvider()).credentialsFor(url)\n const cwd = opts.cwd ?? process.cwd()\n if (opts.ssh === true && opts.https === true) {\n process.stderr.write('--ssh and --https cannot be combined\\n')\n return 2\n }\n try {\n const ws = await findWorkspace(cwd)\n const manifest = await loadManifest(ws.rnessDir)\n // The owner of a bare `<repo>`; a blank workspace has none (spec 0012).\n const org = manifest.org\n\n // The name is checked before anything else runs; the host comes later.\n let parsed: { name: string; url: string }\n try {\n parsed = parseRepoSpec(spec, org, transport.hosts.https)\n } catch (e) {\n process.stderr.write(`${e instanceof Error ? e.message : String(e)}\\n`)\n return 2\n }\n // The context repository holds the catalogue and is already cloned as\n // `<root>/.rness`. Adding it would put a second, diverging copy under\n // `org/`, list the catalogue inside itself, and give `.rness/AGENTS.md` a\n // generated member block next to the shared one (spec 0009). The name\n // decides, whatever organization it came from: every spelling lands on\n // the same directory and the same catalogue key.\n if (parsed.name === CONTEXT_REPO) {\n process.stderr.write(\n `${CONTEXT_REPO} is the workspace context, not a member repository — it is already cloned at ${basename(ws.root)}/${CONTEXT_REPO}\\n`\n )\n return 2\n }\n const interactive = opts.yes !== true\n const ownUi = deps.ui === undefined\n if (interactive && !terminal.isTty()) {\n process.stderr.write(\n 'rness add clones and writes files; pass --yes to run without a prompt\\n'\n )\n return 2\n }\n\n const ui: Ui =\n deps.ui ?? (interactive ? await makeUi(terminal) : { ...plainUi })\n if (ownUi)\n ui.intro(\n `Add ${parsed.name} to workspace ${workspaceName(manifest, ws.root)}`\n )\n // Only SSH can make git ask something on the terminal (a passphrase).\n if (opts.host !== undefined || opts.https === true) ui.gitIsSilent = true\n let host = opts.host\n if (host === undefined && opts.ssh === true) host = transport.hosts.ssh\n if (host === undefined && opts.https === true) host = transport.hosts.https\n if (host === undefined && FULL_URL.test(spec)) host = transport.hosts.https\n if (host === undefined) {\n const { access, unattended } = await testGithubSsh(\n transport,\n interactive,\n () => ui.line(...CHECKING)\n )\n if (unattended || !access.ok) ui.gitIsSilent = true\n const overSsh = Object.values(manifest.repos).some((r) =>\n isSshUrl(r.url, transport.hosts)\n )\n if (access.ok || !overSsh) {\n ui.line('using', usingRest(access), usingSentence(access))\n host = access.ok ? transport.hosts.ssh : transport.hosts.https\n } else {\n // An SSH workspace never falls back silently: say why, then let the\n // user choose HTTPS for this one repository.\n const lines = sshWorkspaceLines(access.reason)\n if (!interactive) {\n process.stderr.write(\n `${[...lines, httpsFlagLine(spec)].join('\\n')}\\n`\n )\n return 1\n }\n ui.error(lines[0])\n ui.hint(lines[1], 'stderr')\n const p = await terminal.prompts()\n const https = await p.confirm({\n message: `Clone ${parsed.name} over HTTPS instead?`,\n initialValue: false,\n })\n if (p.isCancel(https) || https !== true) return 1\n host = transport.hosts.https\n }\n }\n parsed = parseRepoSpec(spec, org, host)\n\n const scopes = (opts.scopes ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s !== '')\n const dir = join(ws.root, 'org', parsed.name)\n const present = await exists(dir)\n\n if (interactive) {\n const { confirm, isCancel } = await terminal.prompts()\n const plan = present\n ? `adopt org/${parsed.name}`\n : `clone ${parsed.url} into org/${parsed.name}`\n const ok = await confirm({\n message: `${plan}, declare scope \"${parsed.name}\" in rness.json, then sync?`,\n })\n if (isCancel(ok) || ok !== true) {\n ui.cancelled()\n return 1\n }\n }\n\n const credentials = await credentialsFor(parsed.url)\n const chosenHost = host\n let result = await ui.step(\n {\n doing: `${present ? 'adopting' : 'cloning '} org/${parsed.name}`,\n git: true,\n },\n () =>\n addRepository({\n root: ws.root,\n rnessDir: ws.rnessDir,\n manifest,\n spec,\n org,\n host: chosenHost,\n scopes,\n credentialsFor: () => credentials,\n }),\n (r) => [r.action, `org/${r.name}`]\n )\n const announced = new Set<string>()\n printDeclared(ui, result, announced)\n for (const name of result.declared) announced.add(name)\n\n // A monorepo's workspace packages are only knowable once the clone is on\n // disk, so the offer comes after it and adds to what is already declared.\n if (opts.yes !== true && scopes.length === 0) {\n const candidates = await workspaceDirs(dir)\n if (candidates.length > 0) {\n const { isCancel, multiselect } = await terminal.prompts()\n const picked = await multiselect({\n message: 'Declare these workspace packages as scopes?',\n options: candidates.map((c) => ({ value: c, label: c })),\n required: false,\n })\n if (isCancel(picked)) {\n ui.cancelled()\n return 1\n }\n // `isCancel` narrows only the unique cancel symbol, not the broader\n // `symbol` half of clack's `Value[] | symbol` return type, so an array\n // check is what narrows the rest.\n if (Array.isArray(picked) && picked.length > 0) {\n result = await addRepository({\n root: ws.root,\n rnessDir: ws.rnessDir,\n manifest: result.manifest,\n spec,\n org,\n host,\n scopes: picked,\n credentialsFor: () => credentials,\n })\n printDeclared(ui, result, announced)\n }\n }\n }\n const code = await syncCommand({ yes: true, cwd: ws.root }, { ui })\n if (ownUi)\n ui.outro(\n code === 0\n ? `${result.name} is in your workspace`\n : 'Done, with problems',\n code === 0 ? 'done' : 'warn'\n )\n return code\n } catch (e) {\n return reportError(e)\n }\n}\n","import { posix, relative, sep } from 'node:path'\n\nimport { assembleContext } from '../core/context.ts'\nimport { loadManifest } from '../core/manifest.ts'\nimport { resolveScope } from '../core/scope.ts'\nimport type { Context } from '../core/types.ts'\nimport { findWorkspace } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\n\nexport interface ContextOptions {\n /** Scope to resolve; default: the scope owning `cwd`. */\n scope?: string\n /** Print the resolved context as JSON instead of Markdown. */\n json?: boolean\n /** Internal (tests): directory to resolve from; default `process.cwd()`. */\n cwd?: string\n}\n\nexport function renderMarkdown(ctx: Context): string {\n const parts: string[] = []\n for (const collection of ctx.collections) {\n if (collection.files.length === 0) continue\n parts.push(`## ${collection.name}\\n`)\n for (const file of collection.files) {\n parts.push(\n `<!-- rness: ${collection.name}/${file.rel} -->\\n${file.content.trim()}\\n`\n )\n }\n }\n return `${parts.join('\\n')}\\n`\n}\n\n/** `rness context`: resolve and print the context for a scope. Returns the exit code. */\nexport async function contextCommand(opts: ContextOptions): Promise<number> {\n const cwd = opts.cwd ?? process.cwd()\n try {\n const ws = await findWorkspace(cwd)\n const manifest = await loadManifest(ws.rnessDir)\n\n let scope: string | null\n if (opts.scope !== undefined) {\n if (!Object.hasOwn(manifest.scopes, opts.scope)) {\n process.stderr.write(`unknown scope: ${opts.scope}\\n`)\n return 1\n }\n scope = opts.scope\n } else {\n const rel = relative(ws.root, cwd).split(sep).join(posix.sep)\n scope = resolveScope(manifest, rel)\n }\n\n const ctx = await assembleContext({\n rnessDir: ws.rnessDir,\n manifest,\n scope,\n })\n process.stdout.write(\n opts.json ? `${JSON.stringify(ctx, null, 2)}\\n` : renderMarkdown(ctx)\n )\n return 0\n } catch (e) {\n return reportError(e)\n }\n}\n","// Single source of the package version. test/version.test.ts keeps it equal\n// to package.json; bump both together.\nexport const VERSION = '0.6.1'\n","import { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nimport { findWorkspace } from './workspace.ts'\n\nexport interface Delegate {\n /** Absolute path of the pinned copy's `dist/index.js`. */\n entry: string\n version: string\n /** Workspace root (the directory holding `.rness/`). */\n root: string\n}\n\nexport interface PinnedCli {\n /** Absolute path of `<rnessDir>/node_modules/@rness/cli`. */\n dir: string\n /** `bin.rness` as the package declares it (package-relative, POSIX). */\n bin: string\n version: string | null\n}\n\n/** A published `@rness/cli` whose `package.json` has no usable `bin`. */\nconst DEFAULT_BIN = 'dist/bin/rness.js'\n\n/**\n * The `@rness/cli` installed under `<rnessDir>/node_modules`, or null when\n * nothing is installed there. Reading the package's own `package.json` is what\n * makes the launcher and `create` agree on which copy owns a workspace.\n */\nexport async function readPinnedCli(\n rnessDir: string\n): Promise<PinnedCli | null> {\n const dir = join(rnessDir, 'node_modules', '@rness', 'cli')\n let pkg: { version?: unknown; bin?: unknown }\n try {\n pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) as {\n version?: unknown\n bin?: unknown\n }\n } catch {\n return null\n }\n const declared = pkg.bin\n let bin = DEFAULT_BIN\n if (typeof declared === 'string') bin = declared\n else if (declared !== null && typeof declared === 'object') {\n const named = (declared as Record<string, unknown>)['rness']\n if (typeof named === 'string') bin = named\n }\n return {\n dir,\n bin,\n version: typeof pkg.version === 'string' ? pkg.version : null,\n }\n}\n\n/** Absolute path of the pinned copy's executable, or null when nothing is installed. */\nexport async function pinnedBinPath(rnessDir: string): Promise<string | null> {\n const pinned = await readPinnedCli(rnessDir)\n if (pinned === null) return null\n return join(pinned.dir, ...pinned.bin.split('/'))\n}\n\n/**\n * The `@rness/cli` pinned in `<workspace>/.rness/package.json` (installed under\n * `.rness/node_modules`), when it exists and is not the running version. The\n * pinned copy is the only one that should ever act on a workspace.\n */\nexport async function findDelegate(\n cwd: string,\n ownVersion: string\n): Promise<Delegate | null> {\n let root: string\n let rnessDir: string\n try {\n const ws = await findWorkspace(cwd)\n root = ws.root\n rnessDir = ws.rnessDir\n } catch {\n return null\n }\n const pinned = await readPinnedCli(rnessDir)\n if (pinned === null) return null\n const { version } = pinned\n if (version === null || version === ownVersion) return null\n return { entry: join(pinned.dir, 'dist', 'index.js'), version, root }\n}\n","import { statSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\n/**\n * Files shipped in `scaffold/`, POSIX-relative. `_gitignore` is renamed to\n * `.gitignore` when copied (npm would rename a packed `.gitignore`).\n */\nexport const SCAFFOLD_FILES: readonly string[] = [\n 'AGENTS.md',\n 'CONVENTIONS.md',\n 'README.md',\n 'WORKSPACE.md',\n 'rness.json',\n 'package.json',\n '_gitignore',\n '.githooks/pre-commit',\n '.github/workflows/validate.yml',\n '.github/dependabot.yml',\n 'pnpm-workspace.yaml',\n 'adr/0000-template.md',\n 'standards/.gitkeep',\n 'specs/.gitkeep',\n 'plans/.gitkeep',\n 'skills/.gitkeep',\n 'docs/.gitkeep',\n]\n\n/**\n * Absolute path of the shipped scaffold. Works from the sources\n * (`src/core/scaffold.ts` → `../../scaffold`) and from the bundle\n * (`dist/<chunk>.js` or `dist/index.js` → `../scaffold`): walk up from this\n * file until a directory containing `scaffold/rness.json` is the package root.\n */\nexport function scaffoldDir(): string {\n let dir = dirname(fileURLToPath(import.meta.url))\n for (let i = 0; i < 4; i += 1) {\n const candidate = join(dir, 'scaffold')\n try {\n if (statSync(join(candidate, 'rness.json')).isFile()) return candidate\n } catch {\n // keep walking\n }\n dir = dirname(dir)\n }\n throw new Error('scaffold directory not found next to the @rness/cli package')\n}\n","import { chmod, mkdir, readFile, stat, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\n\nimport { SCAFFOLD_FILES, scaffoldDir } from './scaffold.ts'\n\nexport interface ScaffoldTokens {\n version: string\n packageManager: string\n}\n\n// The CI workflow reads the pinned version from package.json (spec 0006 §2).\nconst TOKENISED = new Set(['package.json'])\n\n/** Materialise the shipped skeleton into `dest` (spec 0003 §2.1 step 3); `rness.json` is the caller's. */\nexport async function copyScaffold(\n dest: string,\n tokens: ScaffoldTokens\n): Promise<void> {\n const source = scaffoldDir()\n for (const rel of SCAFFOLD_FILES) {\n if (rel === 'rness.json') continue\n const from = join(source, ...rel.split('/'))\n const targetRel = rel === '_gitignore' ? '.gitignore' : rel\n const to = join(dest, ...targetRel.split('/'))\n await mkdir(dirname(to), { recursive: true })\n let content = await readFile(from, 'utf8')\n if (TOKENISED.has(rel)) {\n content = content\n .replaceAll('__RNESS_VERSION__', tokens.version)\n .replaceAll('__RNESS_PM__', tokens.packageManager)\n }\n await writeFile(to, content, 'utf8')\n const mode = (await stat(from)).mode & 0o777\n if (mode & 0o111) await chmod(to, mode)\n }\n}\n","import { spawn } from 'node:child_process'\nimport { realpath } from 'node:fs/promises'\n\nimport { envToken, readAuth, resolveToken, writeAuth } from '../core/auth.ts'\nimport {\n LoginError,\n type PollDeps,\n clientId,\n pollForToken,\n requestDeviceCode,\n} from '../core/device-flow.ts'\nimport { DEFAULT_GITHUB_API, getUser } from '../core/github.ts'\nimport { rnessCommand } from '../core/pm.ts'\nimport { isStableInstall, setupGit } from '../core/setup-git.ts'\nimport { type Terminal, defaultTerminal } from '../core/terminal.ts'\nimport { type Ui, makeUi } from '../core/ui.ts'\nimport { reportError } from '../report.ts'\n\nexport interface LoginOptions {\n /** `--setup-git` / `--no-setup-git`; undefined asks in a terminal. */\n setupGit?: boolean\n /** Internal (tests): GitHub REST API base. */\n githubApi?: string\n}\n\nexport interface LoginDeps extends PollDeps {\n terminal?: Terminal\n /** The caller's reporter: `create` logs in from inside its own session. */\n ui?: Ui\n /** Open a URL in the browser; failures are nobody's problem. */\n open?: (url: string) => void\n /** This rness's launcher, as git will have to find it. */\n bin?: string\n}\n\nfunction openInBrowser(url: string): void {\n const [command, args] =\n process.platform === 'darwin'\n ? ['open', [url]]\n : process.platform === 'win32'\n ? ['cmd', ['/c', 'start', '', url]]\n : ['xdg-open', [url]]\n try {\n const child = spawn(command, args, { stdio: 'ignore', detached: true })\n child.on('error', () => undefined)\n child.unref()\n } catch {\n // no browser here: the URL is on the screen\n }\n}\n\n/** The question of spec 0004 §5, or the line that replaces it under npx. */\nasync function offerSetupGit(\n opts: LoginOptions,\n terminal: Terminal,\n bin: string,\n ui: Ui\n): Promise<void> {\n if (opts.setupGit === false) return\n if (!isStableInstall(bin)) {\n ui.hint(\n 'install rness globally to let git use your login: npm i -g @rness/cli'\n )\n return\n }\n if (opts.setupGit !== true) {\n if (!terminal.isTty()) return\n const p = await terminal.prompts()\n const ok = await p.confirm({\n message: 'Use rness to authenticate git over HTTPS for github.com?',\n initialValue: true,\n })\n if (p.isCancel(ok) || ok !== true) return\n }\n const changed = await setupGit(process.execPath, bin)\n ui.line(\n changed ? 'updated' : 'unchanged',\n `git: rness answers for https://github.com (${rnessCommand()} logout undoes it)`,\n `git now asks rness for your github.com login over HTTPS (${rnessCommand()} logout undoes it)`\n )\n}\n\n/**\n * `rness login`: GitHub's device flow (spec 0004 §2). Concerns the machine,\n * not a workspace: never delegated to a pinned copy.\n */\nexport async function loginCommand(\n opts: LoginOptions,\n deps: LoginDeps = {}\n): Promise<number> {\n const terminal = deps.terminal ?? defaultTerminal\n // On its own `login` is a session of its own; inside `create` it is a part.\n const own = deps.ui === undefined\n const ui = deps.ui ?? (await makeUi(terminal))\n if (own) ui.intro('Log in to GitHub')\n try {\n const bin =\n deps.bin ?? (await realpath(process.argv[1] ?? '').catch(() => ''))\n const env = envToken()\n if (env !== null)\n ui.hint(`${env.source} is set and wins over a stored login`)\n const stored = await readAuth()\n if (stored !== null && (await resolveToken()) !== null) {\n ui.line(\n 'logged in',\n `as ${stored.login} (github.com); ${rnessCommand()} logout to switch`\n )\n await offerSetupGit(opts, terminal, bin, ui)\n if (own) ui.outro('Nothing to do', 'idle')\n return 0\n }\n\n const code = await requestDeviceCode()\n if (ui.session)\n ui.line(\n 'open',\n code.verificationUri,\n `Open ${code.verificationUri} and enter the code ${code.userCode}`\n )\n else {\n ui.line('open', code.verificationUri)\n ui.line('code', code.userCode)\n }\n if (terminal.isTty() && process.env['SSH_CONNECTION'] === undefined)\n (deps.open ?? openInBrowser)(code.verificationUri)\n // The plain look says it is waiting, then who logged in; the session\n // look spins, and the spinner ends as that second line.\n if (!ui.session)\n ui.line('waiting', 'for you to approve rness on github.com…')\n const login = await ui.step(\n {\n doing: 'waiting for you to approve rness on github.com',\n sentence: 'Waiting for your approval on github.com',\n quiet: true,\n },\n async () => {\n const tokens = await pollForToken(code, deps)\n const user = await getUser({\n token: tokens.accessToken,\n apiBase: opts.githubApi ?? DEFAULT_GITHUB_API,\n })\n await writeAuth({ login: user.login, tokens })\n return user.login\n },\n (name) => ['logged in', `as ${name} (github.com)`]\n )\n if (!ui.session) ui.line('logged in', `as ${login} (github.com)`)\n await offerSetupGit(opts, terminal, bin, ui)\n if (own) ui.outro(`You are logged in as ${login}`)\n return 0\n } catch (e) {\n if (e instanceof LoginError) {\n ui.error(e.message)\n return 1\n }\n return reportError(e)\n }\n}\n\n/** Where a user revokes what `rness login` was granted; doing it by API needs the client secret. */\nexport function revokeUrl(): string {\n return `https://github.com/settings/connections/applications/${clientId()}`\n}\n","import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\n\nconst execFileP = promisify(execFile)\n\n// Making rness git's credential helper for github.com (spec 0004 §5): what\n// `gh auth setup-git` does for gh. Two values under one key — an empty one,\n// which clears the helpers inherited from the system (osxkeychain would\n// otherwise answer first), then rness, by absolute path so git finds it\n// whatever PATH it runs with.\n\nconst KEY = 'credential.https://github.com.helper'\n\nexport function helperValue(node: string, bin: string): string {\n return `!'${node}' '${bin}' git-credential`\n}\n\n// The shape `helperValue` writes — not gh's `!gh auth git-credential`, nor\n// anyone else's helper that happens to end the same way.\nconst isOurs = (value: string): boolean =>\n /^!'[^']+' '[^']*rness[^']*' git-credential$/.test(value)\n\nasync function config(args: string[]): Promise<string> {\n const { stdout } = await execFileP('git', ['config', '--global', ...args])\n return stdout\n}\n\nasync function values(): Promise<string[]> {\n try {\n const out = await config(['--get-all', KEY])\n return out.replace(/\\n$/, '').split('\\n')\n } catch {\n return [] // the key is not set\n }\n}\n\n/** A copy run through npx lives in a cache that is cleared: not a path to give git. */\nexport function isStableInstall(bin: string): boolean {\n return !/[\\\\/]_npx[\\\\/]/.test(bin)\n}\n\n/** Register rness for github.com. False when it already was. */\nexport async function setupGit(node: string, bin: string): Promise<boolean> {\n const ours = helperValue(node, bin)\n if ((await values()).includes(ours)) return false\n // A stale rness entry (another install path) goes first.\n await removeGitSetup()\n await config(['--add', KEY, ''])\n await config(['--add', KEY, ours])\n return true\n}\n\n/**\n * Remove exactly what `setupGit` wrote: rness's entry and the empty one in\n * front of it. A helper someone else registered is left as it was. False\n * when there was nothing of rness's.\n */\nexport async function removeGitSetup(): Promise<boolean> {\n const current = await values()\n if (!current.some(isOurs)) return false\n const kept = current.filter(\n (value, i) =>\n !isOurs(value) && !(value === '' && isOurs(current[i + 1] ?? ''))\n )\n await config(['--unset-all', KEY])\n for (const value of kept) await config(['--add', KEY, value])\n return true\n}\n","import { mkdir, mkdtemp, rename, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join, relative, resolve } from 'node:path'\n\nimport type { CommandDeps } from '../core/deps.ts'\nimport { clone, publish } from '../core/git.ts'\nimport { githubProvider } from '../core/github-oauth-provider.ts'\nimport { MAX_PAGES, PER_PAGE } from '../core/github.ts'\nimport {\n NAME,\n ORG_NAME,\n isMemberRepo,\n loadManifest,\n parseRepoSpec,\n} from '../core/manifest.ts'\nimport {\n buildContext,\n commitContext,\n insideWorkspace,\n installContext,\n targetProblem,\n} from '../core/new-workspace.ts'\nimport { workspacePackageManager } from '../core/pinned.ts'\nimport {\n PACKAGE_MANAGERS,\n type PackageManager,\n detectPackageManager,\n isPackageManager,\n rnessCommand,\n} from '../core/pm.ts'\nimport type { GitCredentials, GitProvider } from '../core/provider.ts'\nimport { probeRemote, repoUrl } from '../core/remote.ts'\nimport { addRepository } from '../core/repos.ts'\nimport { PRIVATE_MARK, banner, unicode } from '../core/style.ts'\nimport { syncBlocks } from '../core/sync-blocks.ts'\nimport {\n type Prompts,\n type Terminal,\n defaultTerminal,\n} from '../core/terminal.ts'\nimport {\n CHECKING,\n INSTEAD_OF_LINES,\n type SshAccess,\n type SshTest,\n defaultTransport,\n isSshUrl,\n sshWorkspaceLines,\n testGithubSsh,\n usingRest,\n usingSentence,\n} from '../core/transport.ts'\nimport type { Manifest } from '../core/types.ts'\nimport { type Ui, makeUi, plainUi } from '../core/ui.ts'\nimport { clonesIn } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\nimport { VERSION } from '../version.ts'\nimport {\n WORKSPACE_NAME,\n createBlank,\n workspaceNameError,\n} from './create-blank.ts'\nimport { loginCommand, revokeUrl } from './login.ts'\nimport { syncCommand } from './sync.ts'\n\nexport interface CreateOptions {\n /** The GitHub organization, exact name (`github.com/<org>`); prompted for when absent. */\n org?: string\n /** Comma-separated repositories for the workspace (`<repo>` or `<owner>/<repo>`): catalogue entries are cloned, others added. */\n repos?: string\n pm?: string\n /** Force `git@github.com:` without the SSH test. */\n ssh?: boolean\n /** Force `https://github.com/` without the SSH test. */\n https?: boolean\n /** Internal: remote base; wins over both flags and skips the SSH test. */\n host?: string\n yes?: boolean\n skipInstall?: boolean\n /** Reserved; rejected. */\n template?: string\n /** A workspace with no GitHub organization (spec 0012). */\n blank?: boolean\n /** With `blank`: the workspace directory; prompted for when absent. */\n name?: string\n /** Internal (tests): directory to resolve from. */\n cwd?: string\n /** Internal (tests): GitHub REST API base. */\n githubApi?: string\n}\n\nexport type { Prompts }\n\n/** What create needs from the terminal; tests replace it with scripted answers. */\nexport type CreateDeps = Terminal\n\nfunction firstLine(text: string): string {\n return (\n text\n .split('\\n')\n .find((l) => l.trim() !== '')\n ?.trim() ?? 'unknown error'\n )\n}\n\nfunction splitSpecs(list: string): string[] {\n return list\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s !== '')\n}\n\n// A cancelled or declined prompt is the user's choice, not a failure: exit 0\n// so `npm create rness` does not wrap it in npm's error report.\nfunction cancelled(ui: Ui): number {\n ui.cancelled()\n return 0\n}\n\n/**\n * The repositories to offer: the organization's, listed from the GitHub API,\n * plus every catalogue repository the API did not return (a private one\n * listed anonymously). Catalogue repositories are pre-selected. A listing that\n * fails is a warning: the catalogue is still offered, and `rness add` adds\n * repositories later. `null` when the user cancels; `prompted` tells whether\n * the picker was shown at all.\n */\nasync function pickRepositories(input: {\n org: string\n provider: GitProvider\n prompts: Prompts\n ui: Ui\n catalogue: Readonly<Record<string, unknown>>\n}): Promise<{ picked: string[]; prompted: boolean } | null> {\n const { org, prompts, provider, ui } = input\n // Logged in: say as whom rness looks at the organization, and when the\n // organization hides its private repositories from OAuth apps (spec 0004 §3).\n if (provider.authenticated) {\n const access = await provider.organizationAccess(org)\n const login = (await provider.identity())?.login\n if (access === 'member')\n ui.line(\n 'member',\n `${org}${login === undefined ? '' : ` (as ${login})`}`,\n `You are a member of ${org}${login === undefined ? '' : ` (as ${login})`}`\n )\n else if (access === 'restricted') {\n ui.warn(\n `${org} restricts OAuth apps, so its private repositories are hidden from rness`\n )\n ui.hint(`ask an owner to approve it: ${revokeUrl()}`, 'stderr')\n }\n }\n let listed: { name: string; private: boolean; archived: boolean }[] = []\n let failed = false\n // The plain look announces the listing; the session look spins on it.\n if (!ui.session) ui.line('listing', `${org} repositories…`)\n try {\n const listing = await ui.step(\n {\n doing: `listing ${org} repositories`,\n sentence: `Listing the repositories of ${org}`,\n quiet: true,\n },\n () => provider.listRepositories(org),\n // What the listing offers, not what GitHub returned: the count and the\n // list below it must agree (spec 0009).\n (l) => [\n 'listed',\n `${l.repositories.filter(isMemberRepo).length} repositories of ${org}`,\n ]\n )\n listed = listing.repositories\n if (listing.owner === 'user')\n ui.hint(\n `only public repositories of ${org} are listed; add private ones later with ${rnessCommand()} add <repo>`\n )\n else if (!provider.authenticated)\n ui.hint(\n `only public repositories are listed; ${rnessCommand()} login lists the private ones you can access`\n )\n if (listing.truncated)\n ui.hint(`listed the first ${MAX_PAGES * PER_PAGE} repositories of ${org}`)\n } catch (e) {\n failed = true\n ui.warn(firstLine(e instanceof Error ? e.message : String(e)))\n }\n const inCatalogue = (name: string): boolean =>\n Object.hasOwn(input.catalogue, name)\n // Every active repository of the organization is a candidate but its context\n // repository, which is already cloned as `<root>/.rness` and is not a member\n // of the workspace it defines (spec 0009). A name beginning with a dot is an\n // ordinary repository: `.github` carries an organization's profile, its\n // issue templates and its shared workflows, and a member works on it like\n // any other. Archived repositories stay out: GitHub makes them read-only, so\n // a block written into one could never be pushed back.\n // GitHub names are case-insensitive, so a name that differs from `NAME` only\n // by case is offered — and declared — in lowercase, as `rness add` would;\n // any other name is shown but cannot be picked yet.\n const byLabel = (a: { label: string }, b: { label: string }): number =>\n a.label.localeCompare(b.label, 'en', { sensitivity: 'base' })\n const candidates = listed.filter(isMemberRepo)\n // A private repository wears a padlock next to its name — visible on every\n // line, where a hint shows on the focused one only. A terminal that cannot\n // draw it falls back to the word, as a hint.\n const padlock = unicode()\n const hint = (isPrivate: boolean, catalogued: boolean): string | null =>\n [isPrivate && !padlock ? 'private' : null, catalogued ? 'in .rness' : null]\n .filter((h) => h !== null)\n .join(' · ') || null\n const declarable = candidates\n .filter((r) => NAME.test(r.name.toLowerCase()))\n .map((r) => {\n const value = r.name.toLowerCase()\n const h = hint(r.private, inCatalogue(value))\n const label = r.private && padlock ? `${r.name} ${PRIVATE_MARK}` : r.name\n return { value, label, ...(h === null ? {} : { hint: h }) }\n })\n const offered = new Set(declarable.map((o) => o.value))\n for (const name of Object.keys(input.catalogue)) {\n if (!offered.has(name))\n declarable.push({ value: name, label: name, hint: 'in .rness' })\n }\n declarable.sort(byLabel)\n const unsupported = candidates\n .filter((r) => !NAME.test(r.name.toLowerCase()))\n .map((r) => ({\n value: r.name,\n label: r.name,\n hint: 'name not supported yet',\n disabled: true,\n }))\n .sort(byLabel)\n // clack renders a disabled option struck through but never its hint, so\n // the reason is printed here.\n if (unsupported.length > 0) {\n const names = unsupported.slice(0, 5).map((o) => o.label)\n const more =\n unsupported.length > names.length\n ? ` and ${unsupported.length - names.length} more`\n : ''\n ui.hint(\n `names rness cannot declare yet (struck through): ${names.join(', ')}${more}`\n )\n }\n if (declarable.length === 0) {\n // After a failed listing its own warning already says why.\n if (!failed) ui.warn(`no repositories to list for ${org}`)\n return { picked: [], prompted: false }\n }\n const initialValues = Object.keys(input.catalogue)\n // Disabled options go last: clack focuses the first option before any key\n // is pressed, and Tab would select it even when it is disabled.\n const answer = await prompts.autocompleteMultiselect<string>({\n message: 'Which repositories do you want in your workspace?',\n options: [...declarable, ...unsupported],\n ...(initialValues.length > 0 ? { initialValues } : {}),\n required: false,\n placeholder: 'Type to filter',\n })\n if (prompts.isCancel(answer)) return null\n const allowed = new Set(declarable.map((o) => o.value))\n return {\n picked: Array.isArray(answer) ? answer.filter((v) => allowed.has(v)) : [],\n prompted: true,\n }\n}\n\ninterface Failure {\n spec: string\n message: string\n}\n\n/**\n * Bring each selected repository into `org/`, in order. A catalogue\n * repository is cloned from its catalogue URL and `rness.json` is left alone;\n * any other goes through `addRepository` (declared, then cloned), as\n * `rness add` would. A failure is reported on one line and the next entry\n * still runs: a typo in `--repos` must not cost the workspace the\n * repositories that do exist, nor the commit and sync that follow.\n */\nasync function cloneSelection(input: {\n root: string\n rnessDir: string\n manifest: Manifest\n org: string\n host: string\n specs: readonly string[]\n provider: GitProvider\n ui: Ui\n}): Promise<Failure[]> {\n const { ui } = input\n let manifest = input.manifest\n const failures: Failure[] = []\n for (const spec of new Set(input.specs)) {\n try {\n let name: string | null = null\n try {\n name = parseRepoSpec(spec, input.org, input.host).name\n } catch {\n // `addRepository` reports the malformed spec below.\n }\n const entry = name === null ? undefined : manifest.repos[name]\n if (name !== null && entry !== undefined) {\n const repo = name\n await ui.step(\n { doing: `cloning org/${repo}`, git: true },\n () =>\n clone(\n entry.url,\n join(input.root, 'org', repo),\n input.provider.credentialsFor(entry.url)\n ),\n () => ['cloned', `org/${repo}`]\n )\n continue\n }\n const current = manifest\n const result = await ui.step(\n { doing: `cloning ${spec}`, git: true },\n () =>\n addRepository({\n root: input.root,\n rnessDir: input.rnessDir,\n manifest: current,\n spec,\n org: input.org,\n host: input.host,\n scopes: [],\n credentialsFor: (url) => input.provider.credentialsFor(url),\n }),\n (r) => [r.action, `org/${r.name}`]\n )\n manifest = result.manifest\n ui.line('declared', `scope ${result.name} (org/${result.name})`)\n } catch (e) {\n const message = firstLine(e instanceof Error ? e.message : String(e))\n ui.error(`${spec}: ${message}`)\n failures.push({ spec, message })\n }\n }\n return failures\n}\n\n/**\n * Move the staged `.rness` clone into the workspace. A rename is atomic and\n * keeps the clone's origin; across filesystems (`EXDEV`: the temporary\n * directory on another volume) the context is cloned a second time instead.\n */\nasync function placeContext(\n staged: string,\n rnessDir: string,\n url: string,\n credentials: GitCredentials | null\n): Promise<void> {\n try {\n await rename(staged, rnessDir)\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'EXDEV') throw e\n await clone(url, rnessDir, credentials)\n }\n}\n\n/** The flags that name a GitHub workspace, which a blank one has none of. */\nfunction blankConflict(opts: CreateOptions): string | null {\n if (opts.org !== undefined) return '--org'\n if (opts.repos !== undefined) return '--repos'\n if (opts.ssh === true) return '--ssh'\n if (opts.https === true) return '--https'\n if (opts.host !== undefined) return '--host'\n return null\n}\n\n/**\n * The wizard's first question (spec 0012): from a GitHub organization, the\n * flow below, or a blank local workspace. Null is a cancel.\n */\nasync function chooseStart(\n prompts: Prompts\n): Promise<'github' | 'blank' | null> {\n const answer = await prompts.select<string>({\n message: 'How do you want to start?',\n options: [\n { value: 'github', label: 'From a GitHub organization' },\n { value: 'blank', label: 'Blank local workspace' },\n ],\n })\n if (prompts.isCancel(answer)) return null\n return answer === 'blank' ? 'blank' : 'github'\n}\n\nconst OTHER = Symbol('another organization')\n\n/**\n * Logged in, the organization is picked from the user's own and their\n * account rather than typed. `OTHER` leads to the text prompt — as does\n * having nothing to offer; null is a cancel.\n */\nasync function chooseOrganization(\n provider: GitProvider,\n prompts: Prompts\n): Promise<string | typeof OTHER | null> {\n if (!provider.authenticated) return OTHER\n let names: string[]\n try {\n const self = (await provider.identity())?.login\n names = (await provider.listOrganizations()).map((o) => o.login)\n if (self !== undefined) names.push(self)\n } catch {\n return OTHER\n }\n if (names.length === 0) return OTHER\n const answer = await prompts.select<string>({\n message: 'Which GitHub organization?',\n options: [\n ...names.map((name) => ({ value: name, label: name })),\n { value: '', label: 'another one…' },\n ],\n })\n if (prompts.isCancel(answer)) return null\n if (typeof answer !== 'string' || answer === '') return OTHER\n return answer\n}\n\n/**\n * Offer to create `<org>/.rness` on GitHub and push the new context to it.\n * True when it is published, false when it is left to the user (anonymous,\n * declined, refused by GitHub — said in one warning), null on a cancel.\n */\nasync function publishContext(input: {\n ui: Ui\n prompts: Prompts\n provider: GitProvider\n org: string\n rnessDir: string\n url: string\n}): Promise<boolean | null> {\n const { ui, prompts, provider, org } = input\n if (!provider.authenticated) return false\n const ok = await prompts.confirm({\n message: `Create ${org}/.rness on GitHub (private) and push it?`,\n initialValue: true,\n })\n if (prompts.isCancel(ok)) return null\n if (ok !== true) return false\n try {\n const result = await ui.step(\n { doing: `creating ${org}/.rness on GitHub` },\n () => provider.createRepository(org, '.rness')\n )\n if (result.kind === 'exists') {\n ui.warn(`${org}/.rness already exists on GitHub; nothing was pushed`)\n return false\n }\n if (result.kind === 'refused') {\n ui.warn(`GitHub did not create ${org}/.rness: ${result.reason}`)\n return false\n }\n ui.line('created', `github.com/${org}/.rness (private)`)\n await ui.step(\n { doing: `pushing ${org}/.rness`, git: true },\n () =>\n publish(input.rnessDir, input.url, provider.credentialsFor(input.url)),\n () => ['pushed', `${org}/.rness`]\n )\n return true\n } catch (e) {\n ui.warn(firstLine(e instanceof Error ? e.message : String(e)))\n return false\n }\n}\n\n/**\n * `rness create`: join the organization's `.rness` or start a new one in\n * `./<org>` (spec 0003 §2.1). `rness.json` is the organization's catalogue;\n * the workspace is the selection of it cloned into `org/`. Every prompt comes\n * before the first write, so a cancel leaves nothing behind. URLs are written\n * over SSH when github.com accepts the user's key, over HTTPS otherwise\n * (spec 0005); a catalogue URL is cloned as written.\n */\nexport async function createCommand(\n opts: CreateOptions,\n deps: Partial<CommandDeps> = {}\n): Promise<number> {\n const terminal = deps.terminal ?? defaultTerminal\n const transport = deps.transport ?? defaultTransport\n // Built on first use: it reads the stored login, which most paths never need.\n let provider = deps.provider\n const getProvider = async (): Promise<GitProvider> =>\n (provider ??= await githubProvider(opts.githubApi))\n const cwd = opts.cwd ?? process.cwd()\n if (opts.template !== undefined) {\n process.stderr.write('--template is reserved for a later version\\n')\n return 2\n }\n if (opts.pm !== undefined && !isPackageManager(opts.pm)) {\n process.stderr.write(`--pm must be one of ${PACKAGE_MANAGERS.join(', ')}\\n`)\n return 2\n }\n if (opts.ssh === true && opts.https === true) {\n process.stderr.write('--ssh and --https cannot be combined\\n')\n return 2\n }\n if (opts.blank === true) {\n const clash = blankConflict(opts)\n if (clash !== null) {\n process.stderr.write(`--blank cannot be combined with ${clash}\\n`)\n return 2\n }\n if (opts.name !== undefined && !WORKSPACE_NAME.test(opts.name)) {\n process.stderr.write(`${workspaceNameError(opts.name)}\\n`)\n return 2\n }\n }\n // A malformed flag is refused before any question is asked about the rest.\n if (opts.org !== undefined && !ORG_NAME.test(opts.org)) {\n process.stderr.write(\n `organization name \"${opts.org}\" is not a valid GitHub organization name\\n`\n )\n return 2\n }\n let pm: PackageManager =\n opts.pm !== undefined && isPackageManager(opts.pm)\n ? opts.pm\n : detectPackageManager()\n const interactive = opts.yes !== true && terminal.isTty()\n // The plain look unless this is a wizard in a real terminal (spec 0007 §5b).\n const ui = interactive ? await makeUi(terminal) : { ...plainUi }\n // The SSH test runs at most once, and only when its answer is needed.\n let sshTest: SshTest | undefined\n const testSsh = async (): Promise<SshAccess> => {\n if (sshTest === undefined) {\n sshTest = await testGithubSsh(transport, interactive, () =>\n ui.line(...CHECKING)\n )\n // Unattended SSH never asks anything: git steps may animate.\n if (sshTest.unattended) ui.gitIsSilent = true\n }\n return sshTest.access\n }\n // Whether this machine's SSH access to github.com was proved. A delegated\n // child that then fails on publickey is missing an agent, not a key\n // (spec 0008 §2.1).\n const sshWorks = (): boolean => sshTest?.access.ok === true\n const chooseHost = async (): Promise<string> => {\n // Only SSH can make git ask something on the terminal (a passphrase).\n if (opts.host !== undefined || opts.https === true) ui.gitIsSilent = true\n if (opts.host !== undefined) return opts.host\n if (opts.ssh === true) return transport.hosts.ssh\n if (opts.https === true) return transport.hosts.https\n const access = await testSsh()\n const github = access.ok ? null : await getProvider()\n const login = github?.authenticated\n ? (await github.identity())?.login\n : undefined\n ui.line('using', usingRest(access, login), usingSentence(access, login))\n if (!access.ok) ui.gitIsSilent = true\n return access.ok ? transport.hosts.ssh : transport.hosts.https\n }\n let loaded: Prompts | undefined\n const prompts = async (): Promise<Prompts> =>\n (loaded ??= await terminal.prompts())\n let staging: string | undefined\n // '' off a terminal, so scripts and tests see nothing of it.\n if (interactive) process.stdout.write(banner(VERSION))\n ui.intro('Create a workspace')\n try {\n // In a terminal, before the first question: no answer could fix it.\n if (interactive && (await insideWorkspace(cwd))) {\n process.stderr.write(\n 'already inside an rness workspace; create runs from outside one\\n'\n )\n return 1\n }\n\n // Blank, or the wizard's first answer: no GitHub step at all. An\n // organization or repositories on the command line settle it.\n let blank = opts.blank === true\n if (\n !blank &&\n interactive &&\n opts.org === undefined &&\n opts.repos === undefined\n ) {\n const start = await chooseStart(await prompts())\n if (start === null) return cancelled(ui)\n blank = start === 'blank'\n }\n if (blank)\n return await createBlank({\n name: opts.name,\n cwd,\n pm,\n interactive,\n mayWrite: opts.yes === true || terminal.isTty(),\n skipInstall: opts.skipInstall === true,\n ui,\n prompts,\n })\n\n let prompted = false\n let org = opts.org\n if (org === undefined && !interactive) {\n process.stderr.write('rness create needs --org <name> without a prompt\\n')\n return 2\n }\n // Anonymous, and about to list repositories: offer the login first — it is\n // what lists the private ones, and the user's organizations to pick from.\n if (\n interactive &&\n opts.repos === undefined &&\n !(await getProvider()).authenticated\n ) {\n const p = await prompts()\n const login = await p.confirm({\n message: 'Log in to GitHub to list private repositories?',\n initialValue: true,\n })\n if (p.isCancel(login)) return cancelled(ui)\n if (login === true) {\n const code = await loginCommand(\n opts.githubApi === undefined ? {} : { githubApi: opts.githubApi },\n { terminal, ui }\n )\n if (code !== 0) return code\n provider = await githubProvider(opts.githubApi)\n }\n }\n if (org === undefined) {\n const chosen = await chooseOrganization(\n await getProvider(),\n await prompts()\n )\n if (chosen === null) return cancelled(ui)\n if (chosen !== OTHER) {\n org = chosen\n prompted = true\n }\n }\n if (org === undefined) {\n const p = await prompts()\n const answer = await p.text({\n message: 'What is your GitHub organization named?',\n placeholder: 'acme',\n validate: (value) => {\n const v = value?.trim() ?? ''\n return ORG_NAME.test(v)\n ? undefined\n : `\"${v}\" is not a valid GitHub organization name`\n },\n })\n if (p.isCancel(answer) || typeof answer !== 'string') return cancelled(ui)\n org = answer.trim()\n prompted = true\n }\n\n // The organization is the workspace: its directory carries the exact name.\n const root = resolve(cwd, org)\n const shown = relative(cwd, root) || '.'\n const problem = await targetProblem(cwd, root, pm)\n if (problem !== null) {\n process.stderr.write(`${problem}\\n`)\n return 1\n }\n if (opts.yes !== true && !terminal.isTty()) {\n process.stderr.write(\n 'rness create writes files; pass --yes to run without a prompt\\n'\n )\n return 2\n }\n\n const host = await chooseHost()\n const contextUrl = repoUrl(host, org, '.rness')\n const gitProvider = await getProvider()\n const probe = await probeRemote(\n contextUrl,\n undefined,\n gitProvider.credentialsFor(contextUrl)\n )\n if (probe.kind === 'error') {\n process.stderr.write(`${probe.message}\\n`)\n return 1\n }\n const joining = probe.kind === 'found'\n if (joining)\n ui.line(\n 'found',\n `${org}/.rness — joining`,\n `${org} has a workspace — joining it`\n )\n else\n ui.line(\n 'not found',\n `${org}/.rness (or not visible to you) — starting a new workspace`,\n `${org} has no workspace yet (or none you can see) — starting one`\n )\n\n // Joining: the catalogue is read from a clone staged outside the target,\n // so the picker can offer it before anything is written there.\n let catalogue: Manifest = { contract: 1, org, repos: {}, scopes: {} }\n const staged = async (): Promise<string> => {\n staging ??= await mkdtemp(join(tmpdir(), 'rness-join-'))\n return join(staging, '.rness')\n }\n if (joining) {\n const stagedDir = await staged()\n await ui.step(\n {\n doing: `cloning ${org}/.rness`,\n sentence: `Reading the catalogue of ${org}`,\n git: true,\n },\n () =>\n clone(contextUrl, stagedDir, gitProvider.credentialsFor(contextUrl))\n )\n // Validates that the clone is a workspace context: throws on a\n // malformed or absent rness.json.\n catalogue = await loadManifest(await staged())\n // An SSH workspace is not negotiable: without SSH access its\n // repositories cannot be cloned, so stop before any question or write.\n // `--ssh` is the user's word that SSH works; git reports otherwise.\n const overSsh = Object.values(catalogue.repos).some((r) =>\n isSshUrl(r.url, transport.hosts)\n )\n if (overSsh && opts.ssh !== true && opts.host === undefined) {\n const access = await testSsh()\n if (!access.ok) {\n process.stderr.write(\n `${[...sshWorkspaceLines(access.reason), ...INSTEAD_OF_LINES].join('\\n')}\\n`\n )\n return 1\n }\n }\n }\n\n let specs: string[]\n if (opts.repos !== undefined) specs = splitSpecs(opts.repos)\n else if (interactive) {\n const result = await pickRepositories({\n org,\n provider: gitProvider,\n ui,\n prompts: await prompts(),\n catalogue: catalogue.repos,\n })\n if (result === null) return cancelled(ui)\n specs = result.picked\n prompted ||= result.prompted\n } else {\n // Scripts and CI: a join takes the whole catalogue, a new workspace nothing.\n specs = Object.keys(catalogue.repos)\n }\n if (interactive && !prompted) {\n const p = await prompts()\n const ok = await p.confirm({\n message: `Create workspace ${org} in ./${shown}?`,\n })\n if (p.isCancel(ok) || ok !== true) return cancelled(ui)\n }\n\n const rnessDir = join(root, '.rness')\n const install = (): Promise<void> =>\n installContext({ ui, pm, rnessDir, skip: opts.skipInstall === true })\n\n if (joining) {\n await mkdir(root, { recursive: true })\n await placeContext(\n await staged(),\n rnessDir,\n contextUrl,\n gitProvider.credentialsFor(contextUrl)\n )\n ui.line('cloned', `${shown}/.rness (joined ${org})`)\n // The workspace declares the manager it installs with (`packageManager`,\n // else the lockfile it committed). Joining adopts it: installing with\n // the one that happened to launch `create` would drop a second lockfile\n // beside the committed one (spec 0009 §5). `--pm` still wins.\n if (opts.pm === undefined) pm = await workspacePackageManager(rnessDir)\n // The pin is the team's, in the repository just cloned. Joining aligns\n // on it and says nothing: moving an organization's version is a\n // maintainer's act, not something asked of whoever arrives\n // (spec 0008 §2).\n await install()\n await mkdir(join(root, 'org'), { recursive: true })\n const failures = await cloneSelection({\n root,\n rnessDir,\n manifest: catalogue,\n org,\n host,\n specs,\n provider: gitProvider,\n ui,\n })\n const code = await syncBlocks(\n ui,\n root,\n shown,\n () => syncCommand({ yes: true, cwd: root }),\n sshWorks()\n )\n if (code !== 0) return code\n // What is left to do, never what just scrolled past: the `cloned` lines\n // are right above (spec 0009 §6).\n const cloned = await clonesIn(root)\n const remaining = Object.keys(catalogue.repos).filter(\n (name) => !cloned.has(name)\n )\n const rness = rnessCommand()\n const next = [\n `cd ${shown}`,\n // The comment above its command, as the new-workspace note does: a\n // line that wraps in a narrow terminal is a line nobody reads.\n ...(remaining.length > 0\n ? [\n `# clone the catalogue repositories you did not pick: ${remaining.join(', ')}`,\n `${rness} sync --all`,\n ]\n : []),\n ...failures.map(\n (f) => `${rness} add ${f.spec} # failed: ${f.message}`\n ),\n ]\n if (ui.session) ui.note('Next steps', next)\n else process.stdout.write(`\\n${next.map((l) => ` ${l}`).join('\\n')}\\n`)\n ui.outro(`You joined ${org} — your workspace is in ${shown}/`)\n return failures.length > 0 ? 1 : 0\n }\n\n // Phase 1 — creating the workspace itself; a failure is rolled back. Past\n // it the workspace exists and is worth keeping, whatever a repository\n // does next.\n const built = await buildContext({\n ui,\n root,\n shown,\n manifest: catalogue,\n pm,\n skipInstall: opts.skipInstall === true,\n kind: 'new workspace',\n })\n if (!built) return 1\n\n // Phase 2 — the repositories. Nothing here is rolled back.\n await mkdir(join(root, 'org'), { recursive: true })\n const failures = await cloneSelection({\n root,\n rnessDir,\n manifest: catalogue,\n org,\n host,\n specs,\n provider: gitProvider,\n ui,\n })\n\n await commitContext({ ui, rnessDir, shown })\n\n const code = await syncBlocks(\n ui,\n root,\n shown,\n () => syncCommand({ yes: true, cwd: root }),\n sshWorks()\n )\n if (code !== 0) return code\n\n // Teammates join once <org>/.rness is on GitHub. Logged in, in a\n // terminal, rness offers to put it there; otherwise it says how, with\n // nothing but git (spec 0004 §3b).\n const name = org\n const published = interactive\n ? await publishContext({\n ui,\n prompts: await prompts(),\n provider: gitProvider,\n org: name,\n rnessDir,\n url: contextUrl,\n })\n : false\n if (published === null) return cancelled(ui)\n const rness = rnessCommand()\n const next = [\n `cd ${shown}/.rness`,\n // What was asked for and did not happen, as the command that retries\n // it — the workspace is complete otherwise.\n ...failures.map((f) => `${rness} add ${f.spec} # failed: ${f.message}`),\n ...(published\n ? []\n : [\n `# create the empty private repository ${org}/.rness on github.com, then:`,\n `git remote add origin ${contextUrl} && git push -u origin main`,\n // git first: everyone has it. The GitHub CLI second, for those\n // who do — it creates the repository and pushes in one step.\n '# or, with the GitHub CLI (gh) installed, in one step:',\n `gh repo create ${org}/.rness --private --source . --push`,\n ]),\n // How this command was launched (npm when rness was typed directly),\n // whatever --pm installed with.\n `# then, for every teammate: ${detectPackageManager()} create rness ${org}`,\n ]\n if (ui.session) {\n ui.note('Next steps', next)\n ui.outro(`Workspace for ${org} is ready in ${shown}/`)\n } else\n process.stdout.write(\n [\n '',\n `Workspace for \\`${org}\\` is ready in ${shown}/.`,\n '',\n 'Next:',\n ...next.map((line) => ` ${line}`),\n '',\n ].join('\\n')\n )\n return failures.length > 0 ? 1 : 0\n } catch (e) {\n return reportError(e)\n } finally {\n // The staged context is either moved into place or no longer needed.\n if (staging !== undefined)\n await rm(staging, { recursive: true, force: true }).catch(() => undefined)\n }\n}\n","import { mkdir, readdir, rm, stat } from 'node:fs/promises'\nimport { dirname, join, relative } from 'node:path'\n\nimport { reportError } from '../report.ts'\nimport { VERSION } from '../version.ts'\nimport { exists } from './fs.ts'\nimport { commitAll, init } from './git.ts'\nimport { writeManifest } from './manifest.ts'\nimport { hasLockfile } from './pinned.ts'\nimport {\n type PackageManager,\n installDependencies,\n packageManagerVersion,\n rnessCommand,\n} from './pm.ts'\nimport { copyScaffold } from './scaffold-copy.ts'\nimport type { Manifest } from './types.ts'\nimport type { Ui } from './ui.ts'\nimport { findWorkspace } from './workspace.ts'\n\n/**\n * The steps `create` takes to bring a workspace into being, shared by the\n * organization path and the blank one (spec 0012): where it may go, the\n * context scaffolded and installed, then committed.\n */\n\nexport async function isEmptyDir(dir: string): Promise<boolean> {\n return (await readdir(dir)).length === 0\n}\n\nexport async function insideWorkspace(dir: string): Promise<boolean> {\n try {\n await findWorkspace(dir)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Why `root` cannot receive a new workspace, as the one-line message the\n * guards print; `null` when it can. Both ends of the operation count: the\n * directory create runs in, and the parent of the target — either one inside\n * a workspace would nest a second `.rness` under the first.\n */\nexport async function targetProblem(\n cwd: string,\n root: string,\n pm: PackageManager\n): Promise<string | null> {\n const shown = relative(cwd, root) || '.'\n if ((await insideWorkspace(cwd)) || (await insideWorkspace(dirname(root))))\n return 'already inside an rness workspace; create runs from outside one'\n if (!(await exists(root))) return null\n if (await exists(join(root, '.rness', 'rness.json'))) {\n // A join whose install failed leaves exactly this: a context clone and\n // no dependencies. Re-running create cannot help — point at the install\n // that finishes the job instead of at `rness add`.\n if (!(await exists(join(root, '.rness', 'node_modules'))))\n return `${shown} holds an rness workspace whose dependencies are not installed; cd ${shown}/.rness && ${pm} install, then ${rnessCommand()} sync`\n return `${shown} already holds an rness workspace (.rness/); run ${rnessCommand()} add inside it to add repositories`\n }\n if (!(await stat(root)).isDirectory()) return `${shown} is not a directory`\n if (!(await isEmptyDir(root))) return `${shown} is not empty`\n return null\n}\n\n/** Install the dependencies of `.rness/`, or say how to when `skip`. */\nexport async function installContext(input: {\n ui: Ui\n pm: PackageManager\n rnessDir: string\n skip: boolean\n}): Promise<void> {\n const { ui, pm, rnessDir } = input\n if (input.skip) {\n // Naming the manager says what to run by hand — and, on a join, which\n // one the workspace declared (spec 0009 §5).\n ui.line('skipped', `install with ${pm} (--skip-install)`)\n return\n }\n // A joined workspace carries the lockfile its clone brought, so the\n // install is frozen and leaves the working tree clean (spec 0008 §2). A\n // new workspace has no lockfile yet and resolves freely.\n const frozen = await hasLockfile(rnessDir, pm)\n await ui.step(\n { doing: `installing dependencies with ${pm}` },\n () => installDependencies(pm, rnessDir, { frozen }),\n () => ['installed', `dependencies with ${pm}`]\n )\n}\n\n/**\n * Create `root` and a new `.rness/` in it: the scaffold, `manifest`, the\n * install. False when a step failed: the error is reported and everything\n * this call wrote is removed, so the retry the message asks for is not\n * refused.\n */\nexport async function buildContext(input: {\n ui: Ui\n root: string\n shown: string\n manifest: Manifest\n pm: PackageManager\n skipInstall: boolean\n /** What the `created` line calls it: `new workspace`, `blank workspace`. */\n kind: string\n}): Promise<boolean> {\n const { ui, root, shown, pm } = input\n const rnessDir = join(root, '.rness')\n // Resolved before anything touches the filesystem: a missing package\n // manager binary must not leave an empty `<shown>/` behind.\n const pmVersion = await packageManagerVersion(pm)\n await mkdir(root, { recursive: true })\n try {\n await copyScaffold(rnessDir, {\n version: VERSION,\n packageManager: `${pm}@${pmVersion}`,\n })\n await writeManifest(rnessDir, input.manifest)\n ui.line('created', `${shown}/.rness (${input.kind})`)\n await installContext({ ui, pm, rnessDir, skip: input.skipInstall })\n return true\n } catch (e) {\n // Report the cause before the consequence: the original error first,\n // then the rollback note. Everything under `rnessDir` was written by\n // this call, so removing it is safe; `root` goes too when it is left\n // empty (this call created it, or found it empty), or the retry the\n // message asks for would be refused with \"<shown> is not empty\". A\n // failing `rm` is swallowed rather than thrown, since it must never\n // mask the original error.\n reportError(e)\n await rm(rnessDir, { recursive: true, force: true }).catch(() => undefined)\n if (await isEmptyDir(root).catch(() => false))\n await rm(root, { recursive: true, force: true }).catch(() => undefined)\n process.stderr.write(\n `removed ${shown}/.rness after the failure; fix it and retry\\n`\n )\n return false\n }\n}\n\n/** Make `.rness/` a repository with one commit; a failure is a warning. */\nexport async function commitContext(input: {\n ui: Ui\n rnessDir: string\n shown: string\n}): Promise<void> {\n const { ui, rnessDir, shown } = input\n await init(rnessDir)\n try {\n await commitAll(rnessDir, 'chore: rness workspace context')\n ui.line('committed', `${shown}/.rness`)\n } catch (e) {\n ui.warn(\n `${e instanceof Error ? e.message : String(e)} — commit ${shown}/.rness yourself`\n )\n }\n}\n","import { execFile } from 'node:child_process'\nimport { readFile } from 'node:fs/promises'\nimport { basename, join } from 'node:path'\nimport { promisify } from 'node:util'\n\nimport { readPinnedCli } from './delegate.ts'\nimport { exists, writeFileAtomic } from './fs.ts'\nimport {\n type PackageManager,\n installDependencies,\n isPackageManager,\n rnessCommand,\n} from './pm.ts'\nimport { warn } from './style.ts'\nimport { agentHintLines } from './transport.ts'\nimport { findWorkspace } from './workspace.ts'\n\nconst execFileP = promisify(execFile)\n\nconst PACKAGE = '@rness/cli'\n\n/** A released version, pre-releases included; never a range or a tag. */\nexport const EXACT_VERSION = /^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$/\n\n/** Negative when `a` is the older version. A pre-release is older than its release. */\nexport function compareVersions(a: string, b: string): number {\n const split = (v: string): [number[], string | null] => {\n const dash = v.indexOf('-')\n const core = dash === -1 ? v : v.slice(0, dash)\n return [core.split('.').map(Number), dash === -1 ? null : v.slice(dash + 1)]\n }\n const [coreA, preA] = split(a)\n const [coreB, preB] = split(b)\n for (let i = 0; i < 3; i += 1) {\n const diff = (coreA[i] ?? 0) - (coreB[i] ?? 0)\n if (diff !== 0) return diff\n }\n if (preA === preB) return 0\n if (preA === null) return 1\n if (preB === null) return -1\n return preA.localeCompare(preB, 'en', { numeric: true })\n}\n\nexport interface Pin {\n /** What `package.json` says: an exact version in a workspace rness created. */\n spec: string\n field: 'devDependencies' | 'dependencies'\n}\n\nasync function readPackageJson(\n rnessDir: string\n): Promise<Record<string, unknown> | null> {\n try {\n const parsed: unknown = JSON.parse(\n await readFile(join(rnessDir, 'package.json'), 'utf8')\n )\n return parsed !== null && typeof parsed === 'object'\n ? (parsed as Record<string, unknown>)\n : null\n } catch {\n return null\n }\n}\n\n/** The `@rness/cli` entry of `.rness/package.json` — the one place the version is written (spec 0006). */\nexport async function readPin(rnessDir: string): Promise<Pin | null> {\n const pkg = await readPackageJson(rnessDir)\n if (pkg === null) return null\n for (const field of ['devDependencies', 'dependencies'] as const) {\n const deps = pkg[field]\n if (deps === null || typeof deps !== 'object') continue\n const spec = (deps as Record<string, unknown>)[PACKAGE]\n if (typeof spec === 'string') return { spec, field }\n }\n return null\n}\n\n/**\n * Replace the pinned version in place: every other byte of `package.json` —\n * its indentation, its inline objects, its key order — is the user's.\n */\nexport async function writePin(\n rnessDir: string,\n from: string,\n to: string\n): Promise<void> {\n const file = join(rnessDir, 'package.json')\n const text = await readFile(file, 'utf8')\n const entry = new RegExp(\n `(\"${PACKAGE}\"\\\\s*:\\\\s*\")${from.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}(\")`\n )\n if (!entry.test(text))\n throw new Error(`\"${PACKAGE}\": \"${from}\" not found in package.json`)\n await writeFileAtomic(file, text.replace(entry, `$1${to}$2`))\n}\n\nconst LOCKFILES: readonly (readonly [string, PackageManager])[] = [\n ['pnpm-lock.yaml', 'pnpm'],\n ['yarn.lock', 'yarn'],\n ['bun.lock', 'bun'],\n ['bun.lockb', 'bun'],\n ['package-lock.json', 'npm'],\n]\n\n/** The package manager a workspace installs with: `packageManager`, else its lockfile, else npm. */\nexport async function workspacePackageManager(\n rnessDir: string\n): Promise<PackageManager> {\n const declared = (await readPackageJson(rnessDir))?.['packageManager']\n if (typeof declared === 'string') {\n const name = declared.split('@')[0] ?? ''\n if (isPackageManager(name)) return name\n }\n for (const [lockfile, pm] of LOCKFILES)\n if (await exists(join(rnessDir, lockfile))) return pm\n return 'npm'\n}\n\n/**\n * Whether the workspace carries a lockfile **this** manager can install from.\n * A frozen install is per-manager: `npm ci` needs `package-lock.json` and\n * fails outright next to a `pnpm-lock.yaml`, which is the common case when the\n * manager running `create` is not the one the workspace declares.\n */\nexport async function hasLockfile(\n rnessDir: string,\n pm: PackageManager\n): Promise<boolean> {\n for (const [lockfile, owner] of LOCKFILES)\n if (owner === pm && (await exists(join(rnessDir, lockfile)))) return true\n return false\n}\n\n/**\n * An exact pin that is not the installed copy: someone pulled an upgrade and\n * did not reinstall, or never installed. Null when they agree, and when the\n * pin is a range — it says nothing precise about what should be installed.\n */\nexport async function pinDrift(\n rnessDir: string\n): Promise<{ pin: string; installed: string | null } | null> {\n const pin = await readPin(rnessDir)\n if (pin === null || !EXACT_VERSION.test(pin.spec)) return null\n const installed = (await readPinnedCli(rnessDir))?.version ?? null\n return installed === pin.spec ? null : { pin: pin.spec, installed }\n}\n\n/**\n * The line the launcher prints when the workspace around `cwd` pins one\n * version and holds another (spec 0006 §4): the teammate who pulled an\n * upgrade and did not reinstall. Null outside a workspace, and without drift.\n */\nexport async function driftWarning(cwd: string): Promise<string | null> {\n let root: string\n let rnessDir: string\n try {\n const ws = await findWorkspace(cwd)\n root = ws.root\n rnessDir = ws.rnessDir\n } catch {\n return null\n }\n const drift = await pinDrift(rnessDir)\n if (drift === null) return null\n const pm = await workspacePackageManager(rnessDir)\n return warn(\n `${basename(root)}/.rness pins @rness/cli ${drift.pin} but ${drift.installed ?? 'nothing'} is installed — run ${pm} install in .rness`\n )\n}\n\n/** A delegated child is killed after this long without finishing (spec 0008 §5). */\nexport const CHILD_DEADLINE_MS = 120_000\n\n/**\n * The environment of a delegated child. Its output is piped and the parent\n * owns the terminal, so a prompt from `ssh` or from git's credential helper is\n * invisible and blocks forever. `GIT_SSH_COMMAND` is composed, not replaced:\n * a user's own agent command (1Password, a named key) must survive.\n */\nexport function childEnv(\n env: NodeJS.ProcessEnv = process.env\n): NodeJS.ProcessEnv {\n return {\n ...env,\n GIT_SSH_COMMAND: `${env['GIT_SSH_COMMAND'] ?? 'ssh'} -o BatchMode=yes`,\n GIT_TERMINAL_PROMPT: '0',\n }\n}\n\nexport interface InstallOutcome {\n installed: boolean\n pin: string\n /** Why it did not install; null when it did. */\n reason: string | null\n}\n\nexport interface EnsureOptions {\n env?: NodeJS.ProcessEnv\n announce?: (pin: string) => void\n install?: (\n pm: PackageManager,\n dir: string,\n opts: { frozen: boolean }\n ) => Promise<void>\n}\n\n/**\n * Bring `.rness/node_modules` back to the pin (spec 0008 §4). The version was\n * decided by the pull request that moved the pin, so this asks nothing. Null\n * when there is no drift. A failure is reported, never thrown: the caller\n * falls back to the warning and runs the command anyway.\n */\nexport async function ensureInstalled(\n rnessDir: string,\n opts: EnsureOptions = {}\n): Promise<InstallOutcome | null> {\n const drift = await pinDrift(rnessDir)\n if (drift === null) return null\n const env = opts.env ?? process.env\n if (env['RNESS_NO_INSTALL'] === '1')\n return { installed: false, pin: drift.pin, reason: 'RNESS_NO_INSTALL=1' }\n const pm = await workspacePackageManager(rnessDir)\n const frozen = await hasLockfile(rnessDir, pm)\n const install = opts.install ?? installDependencies\n opts.announce?.(drift.pin)\n try {\n await install(pm, rnessDir, { frozen })\n return { installed: true, pin: drift.pin, reason: null }\n } catch (e) {\n return {\n installed: false,\n pin: drift.pin,\n reason: e instanceof Error ? e.message : String(e),\n }\n }\n}\n\nexport interface PinnedSyncResult {\n code: number\n stdout: string\n stderr: string\n}\n\n/** `sync --yes` through the installed copy, its output kept. Null when nothing is installed. */\nexport async function runPinnedSync(\n root: string\n): Promise<PinnedSyncResult | null> {\n const installed = await readPinnedCli(join(root, '.rness'))\n if (installed === null) return null\n const pinned = join(installed.dir, ...installed.bin.split('/'))\n if (!(await exists(pinned)))\n return {\n code: 1,\n stdout: '',\n stderr: `@rness/cli in .rness is not installed correctly (missing ${installed.bin}); reinstall in .rness/\\n`,\n }\n try {\n const { stdout, stderr } = await execFileP(\n process.execPath,\n [pinned, 'sync', '--yes'],\n {\n cwd: root,\n maxBuffer: 16 * 1024 * 1024,\n env: childEnv(),\n timeout: CHILD_DEADLINE_MS,\n killSignal: 'SIGKILL',\n }\n )\n return { code: 0, stdout, stderr }\n } catch (e) {\n const err = e as {\n code?: number\n killed?: boolean\n stdout?: string\n stderr?: string\n }\n const deadline =\n err.killed === true\n ? `rness sync in .rness did not finish within ${CHILD_DEADLINE_MS / 1000}s and was stopped\\n`\n : ''\n return {\n code: typeof err.code === 'number' ? err.code : 1,\n stdout: err.stdout ?? '',\n stderr: `${err.stderr ?? ''}${deadline}`,\n }\n }\n}\n\n/**\n * What a sync printed, in one line: `3 blocks: 2 updated, 1 unchanged`. The\n * lines that are not about a block (`not cloned: …`) are returned as they are.\n */\nexport function summariseSync(stdout: string): {\n summary: string\n others: string[]\n} {\n const counts = new Map<string, number>()\n const others: string[] = []\n for (const line of stdout.split('\\n')) {\n if (line.trim() === '') continue\n const verb = /^(updated|unchanged|stale)\\s/.exec(line)?.[1]\n if (verb === undefined) others.push(line)\n else counts.set(verb, (counts.get(verb) ?? 0) + 1)\n }\n const total = [...counts.values()].reduce((a, b) => a + b, 0)\n const detail = [...counts].map(([verb, n]) => `${n} ${verb}`).join(', ')\n return {\n summary: `${total} block${total === 1 ? '' : 's'}${detail === '' ? '' : `: ${detail}`}`,\n others,\n }\n}\n\n/**\n * What the parent makes of a delegated sync (spec 0008 §2.1). A pinned copy\n * older than 0.5.0 clones catalogue repositories nobody picked and exits 1 when\n * one fails; it cannot be made to exit 0, so the blocks decide. One block line\n * on stdout means the sync did its job: what the child wrote to stderr is then\n * context, not the command's outcome.\n */\nexport function syncOutcome(\n result: PinnedSyncResult,\n opts: { sshWorks?: boolean } = {}\n): { code: number; hints: string[]; errors: string[] } {\n const { others } = summariseSync(result.stdout)\n const wrote = /^(updated|unchanged|stale)\\s/m.test(result.stdout)\n const stderr = result.stderr\n .split('\\n')\n .map((l) => l.trimEnd())\n .filter((l) => l.trim() !== '')\n const hints = wrote ? [...others, ...stderr] : others\n if (\n opts.sshWorks === true &&\n /Permission denied \\(publickey\\)/.test(result.stderr)\n )\n hints.push(...agentHintLines())\n return {\n code: wrote ? 0 : result.code,\n hints,\n errors: wrote ? [] : stderr,\n }\n}\n\n/**\n * Run `sync --yes` through the copy installed in `.rness/`. With nothing\n * installed, `fallback` runs instead (`create --skip-install`); without a\n * fallback that is an error, never the caller's own code standing in for the\n * pinned copy (spec 0003 §2.2).\n */\nexport async function syncPinned(\n root: string,\n shown: string,\n fallback?: () => Promise<number>\n): Promise<number> {\n const rnessDir = join(root, '.rness')\n const installed = await readPinnedCli(rnessDir)\n if (installed === null) {\n if (fallback !== undefined) return fallback()\n process.stderr.write(\n `@rness/cli is not installed in ${shown}/.rness; install in .rness/, then ${rnessCommand()} sync\\n`\n )\n return 1\n }\n const pinned = join(installed.dir, ...installed.bin.split('/'))\n if (!(await exists(pinned))) {\n process.stderr.write(\n `@rness/cli in ${shown}/.rness is not installed correctly (missing ${installed.bin}); reinstall in .rness/\\n`\n )\n return 1\n }\n try {\n const { stdout, stderr } = await execFileP(\n process.execPath,\n [pinned, 'sync', '--yes'],\n {\n cwd: root,\n maxBuffer: 16 * 1024 * 1024,\n env: childEnv(),\n timeout: CHILD_DEADLINE_MS,\n killSignal: 'SIGKILL',\n }\n )\n process.stdout.write(stdout)\n if (stderr !== '') process.stderr.write(stderr)\n return 0\n } catch (e) {\n const err = e as { code?: number; stdout?: string; stderr?: string }\n if (err.stdout !== undefined && err.stdout !== '')\n process.stdout.write(err.stdout)\n if (err.stderr !== undefined && err.stderr !== '')\n process.stderr.write(err.stderr)\n return typeof err.code === 'number' ? err.code : 1\n }\n}\n","import {\n runPinnedSync,\n summariseSync,\n syncOutcome,\n syncPinned,\n} from './pinned.ts'\nimport { rnessCommand } from './pm.ts'\nimport type { Ui } from './ui.ts'\n\n/**\n * `sync --yes` through the copy installed in `.rness/` (spec 0003 §2.2), said\n * the way `ui` speaks. The plain look passes the child's lines through, as it\n * always did. The session look keeps them to itself and says them in one —\n * `Synced 3 blocks: 2 updated, 1 unchanged` — since the child, whose stdout\n * is a pipe, can only print the plain look. `inPlace` runs when nothing is\n * installed (`create --skip-install`), or when delegation is off.\n */\nexport async function syncBlocks(\n ui: Ui,\n root: string,\n shown: string,\n inPlace?: () => Promise<number>,\n sshWorks?: boolean\n): Promise<number> {\n // Delegation off (`rness-dev`, `RNESS_NO_DELEGATE=1`): the sources under\n // test write the blocks, not the published copy the install just pinned.\n if (process.env['RNESS_NO_DELEGATE'] === '1' && inPlace !== undefined)\n return inPlace()\n if (!ui.session)\n return ui.step({ doing: 'syncing the blocks', git: true }, () =>\n syncPinned(root, shown, inPlace)\n )\n const result = await ui.step(\n {\n doing: 'syncing the blocks',\n sentence: 'Writing the rness block into every AGENTS.md',\n },\n () => runPinnedSync(root),\n (r) =>\n r === null || r.code !== 0\n ? null\n : ['synced', summariseSync(r.stdout).summary]\n )\n if (result === null) {\n if (inPlace !== undefined) return inPlace()\n ui.error(\n `@rness/cli is not installed in ${shown}/.rness; install in .rness/, then ${rnessCommand()} sync`\n )\n return 1\n }\n const outcome = syncOutcome(result, { sshWorks: sshWorks === true })\n for (const line of outcome.hints) ui.hint(line)\n for (const line of outcome.errors) ui.error(line)\n return outcome.code\n}\n","import { mkdir } from 'node:fs/promises'\nimport { join, relative, resolve } from 'node:path'\n\nimport {\n buildContext,\n commitContext,\n targetProblem,\n} from '../core/new-workspace.ts'\nimport { type PackageManager, rnessCommand } from '../core/pm.ts'\nimport { syncBlocks } from '../core/sync-blocks.ts'\nimport type { Prompts } from '../core/terminal.ts'\nimport type { Ui } from '../core/ui.ts'\nimport { syncCommand } from './sync.ts'\n\n/**\n * A blank workspace's directory name: one path segment of letters, digits,\n * `.`, `_` and `-`, not `.` or `..`, no leading `-`. Case is kept: it names a\n * local directory, not a GitHub account.\n */\nexport const WORKSPACE_NAME = /^(?!\\.{1,2}$)[A-Za-z0-9._][A-Za-z0-9._-]*$/\n\nexport function workspaceNameError(name: string): string {\n return `workspace name \"${name}\" may only contain letters, digits, '.', '_' and '-', not starting with '-'`\n}\n\n/**\n * `rness create --blank`: a workspace with no GitHub organization\n * (spec 0012) — `.rness/` scaffolded with a `rness.json` without `org`, an\n * empty `org/`, the root `AGENTS.md` and `CLAUDE.md`. No login, SSH test,\n * probe or listing: the install of `.rness/` is the only network access.\n * Every prompt comes before the first write.\n */\nexport async function createBlank(input: {\n /** Already checked against `WORKSPACE_NAME`; prompted for when absent. */\n name: string | undefined\n cwd: string\n pm: PackageManager\n /** A wizard in a terminal: questions may be asked. */\n interactive: boolean\n /** `--yes`, or a terminal: allowed to write. */\n mayWrite: boolean\n skipInstall: boolean\n ui: Ui\n prompts: () => Promise<Prompts>\n}): Promise<number> {\n const { cwd, pm, ui } = input\n let name = input.name\n let prompted = false\n if (name === undefined) {\n if (!input.interactive) {\n process.stderr.write(\n 'rness create --blank needs a <name> without a prompt\\n'\n )\n return 2\n }\n const p = await input.prompts()\n const answer = await p.text({\n message: 'What should the workspace be called?',\n placeholder: 'my-workspace',\n validate: (value) => {\n const v = value?.trim() ?? ''\n return WORKSPACE_NAME.test(v) ? undefined : workspaceNameError(v)\n },\n })\n if (p.isCancel(answer) || typeof answer !== 'string') {\n ui.cancelled()\n return 0\n }\n name = answer.trim()\n prompted = true\n }\n\n const root = resolve(cwd, name)\n const shown = relative(cwd, root) || '.'\n const problem = await targetProblem(cwd, root, pm)\n if (problem !== null) {\n process.stderr.write(`${problem}\\n`)\n return 1\n }\n if (!input.mayWrite) {\n process.stderr.write(\n 'rness create writes files; pass --yes to run without a prompt\\n'\n )\n return 2\n }\n if (input.interactive && !prompted) {\n const p = await input.prompts()\n const ok = await p.confirm({\n message: `Create blank workspace ${name} in ./${shown}?`,\n })\n if (p.isCancel(ok) || ok !== true) {\n ui.cancelled()\n return 0\n }\n }\n\n const built = await buildContext({\n ui,\n root,\n shown,\n manifest: { contract: 1, org: null, repos: {}, scopes: {} },\n pm,\n skipInstall: input.skipInstall,\n kind: 'blank workspace',\n })\n if (!built) return 1\n await mkdir(join(root, 'org'), { recursive: true })\n await commitContext({ ui, rnessDir: join(root, '.rness'), shown })\n const code = await syncBlocks(ui, root, shown, () =>\n syncCommand({ yes: true, cwd: root })\n )\n if (code !== 0) return code\n\n // No organization to publish to: say how to bring repositories in, and how\n // the workspace becomes an organization's once there is one.\n const next = [\n `cd ${shown}`,\n '# bring a repository in: <owner>/<repo> on GitHub, or any git URL',\n `${rnessCommand()} add <owner>/<repo>`,\n '# to share it: set \"org\" in .rness/rness.json, then push .rness to github.com/<org>/.rness',\n ]\n if (ui.session) {\n ui.note('Next steps', next)\n ui.outro(`Workspace ${name} is ready in ${shown}/`)\n } else\n process.stdout.write(\n [\n '',\n `Workspace \\`${name}\\` is ready in ${shown}/.`,\n '',\n 'Next:',\n ...next.map((line) => ` ${line}`),\n '',\n ].join('\\n')\n )\n return 0\n}\n","import { clearAuth, readAuth } from '../core/auth.ts'\nimport { removeGitSetup } from '../core/setup-git.ts'\nimport { status } from '../core/style.ts'\nimport { reportError } from '../report.ts'\nimport { revokeUrl } from './login.ts'\n\n/** `rness logout`: forget the stored login and undo `setup-git` (spec 0004 §2, §5). */\nexport async function logoutCommand(): Promise<number> {\n try {\n const stored = await readAuth()\n await clearAuth()\n const undone = await removeGitSetup().catch(() => false)\n if (stored === null && !undone) {\n process.stdout.write('not logged in\\n')\n return 0\n }\n if (stored !== null)\n process.stdout.write(\n `${status('logged out', `${stored.login} (github.com)`)}\\n`\n )\n if (undone)\n process.stdout.write(\n `${status('updated', 'git: rness no longer answers for https://github.com')}\\n`\n )\n process.stdout.write(`revoke rness on GitHub: ${revokeUrl()}\\n`)\n return 0\n } catch (e) {\n return reportError(e)\n }\n}\n","import { execFile } from 'node:child_process'\nimport { mkdir, readFile, readdir } from 'node:fs/promises'\nimport { basename, dirname, join, relative } from 'node:path'\nimport { promisify } from 'node:util'\n\nimport { readPinnedCli } from '../core/delegate.ts'\nimport { exists, readOrNull, writeFileAtomic } from '../core/fs.ts'\nimport {\n EXACT_VERSION,\n compareVersions,\n readPin,\n workspacePackageManager,\n writePin,\n} from '../core/pinned.ts'\nimport { installDependencies, rnessCommand } from '../core/pm.ts'\nimport { scaffoldDir } from '../core/scaffold.ts'\nimport { status } from '../core/style.ts'\nimport { syncBlocks } from '../core/sync-blocks.ts'\nimport { type Terminal, defaultTerminal } from '../core/terminal.ts'\nimport { makeUi, plainUi } from '../core/ui.ts'\nimport { findWorkspace } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\n\nconst execFileP = promisify(execFile)\n\nexport interface UpgradeOptions {\n yes?: boolean\n /** Internal (tests): directory to resolve from. */\n cwd?: string\n}\n\nconst NOTES = 'https://github.com/rness-dev/rness/tree/main/packages/cli#readme'\n\n/** The `run:` command the scaffold wrote up to 0.4.0, its version in group 1. */\nconst OLD_WORKFLOW_RUN =\n /npx --yes @rness\\/cli@(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?) validate/\n/** What the scaffold writes now: the version is read from package.json (spec 0006 §2). */\nconst WORKFLOW_RUN = `npx --yes \"@rness/cli@$(node -p \"require('./package.json').devDependencies['@rness/cli']\")\" validate`\n\n/** `npm view`: npm ships with Node and follows the user's registry configuration. */\nasync function latestVersion(): Promise<string | null> {\n try {\n const { stdout } = await execFileP(\n 'npm',\n ['view', '@rness/cli@latest', 'version'],\n { timeout: 30_000 }\n )\n const version = stdout.trim()\n return EXACT_VERSION.test(version) ? version : null\n } catch {\n return null\n }\n}\n\n/**\n * `rness upgrade [version]`: move a workspace to another `@rness/cli` — pin it\n * in `.rness/package.json` (the one place the version is written), install\n * with the workspace's package manager, sync through the new copy (spec 0006\n * §3). Never delegated: the pinned copy is what is being replaced.\n */\nexport async function upgradeCommand(\n version: string | undefined,\n opts: UpgradeOptions,\n terminal: Terminal = defaultTerminal\n): Promise<number> {\n const cwd = opts.cwd ?? process.cwd()\n if (version !== undefined && !EXACT_VERSION.test(version)) {\n process.stderr.write(\n `version \"${version}\" is not an exact version (for example 0.5.0)\\n`\n )\n return 2\n }\n try {\n const ws = await findWorkspace(cwd)\n const label = `${basename(ws.root)}/.rness`\n const pin = await readPin(ws.rnessDir)\n if (pin === null) {\n process.stderr.write(\n `no @rness/cli entry in ${label}/package.json; add it to devDependencies, then run ${rnessCommand()} upgrade\\n`\n )\n return 1\n }\n const interactive = opts.yes !== true\n if (interactive && !terminal.isTty()) {\n process.stderr.write(\n 'rness upgrade installs and writes files; pass --yes to run without a prompt\\n'\n )\n return 2\n }\n\n const ui = interactive ? await makeUi(terminal) : { ...plainUi }\n ui.intro(`Upgrade workspace ${basename(ws.root)}`)\n const target =\n version ??\n (await ui.step(\n { doing: 'asking the registry for the latest release', quiet: true },\n () => latestVersion(),\n (v) => (v === null ? null : ['latest', `@rness/cli ${v}`])\n ))\n if (target === null) {\n process.stderr.write(\n `cannot reach the registry; name the version: ${rnessCommand()} upgrade <version>\\n`\n )\n return 1\n }\n const installed = (await readPinnedCli(ws.rnessDir))?.version ?? null\n if (pin.spec === target && installed === target) {\n if (ui.session) ui.outro(`Already at ${target}`)\n else process.stdout.write(`already at ${target}\\n`)\n return 0\n }\n const downgrading =\n EXACT_VERSION.test(pin.spec) && compareVersions(target, pin.spec) < 0\n if (downgrading && version === undefined) {\n process.stderr.write(\n `${label} pins @rness/cli ${pin.spec}, newer than the latest release ${target}; to downgrade: ${rnessCommand()} upgrade ${target}\\n`\n )\n return 1\n }\n\n const pm = await workspacePackageManager(ws.rnessDir)\n if (pin.spec === target)\n ui.line(\n 'install',\n `@rness/cli ${target} in ${label} (${pm}) — ${installed ?? 'nothing'} is installed`\n )\n else {\n ui.line(\n 'upgrade',\n `@rness/cli ${pin.spec} → ${target} in ${label} (${pm})${downgrading ? ' — downgrading' : ''}`\n )\n ui.line('notes', NOTES, `Release notes: ${NOTES}`)\n }\n if (interactive) {\n const p = await terminal.prompts()\n const ok = await p.confirm({\n message: `Upgrade @rness/cli to ${target}?`,\n })\n if (p.isCancel(ok) || ok !== true) {\n ui.cancelled()\n return 1\n }\n }\n\n // Everything written before the install is restored when it fails.\n const packageFile = join(ws.rnessDir, 'package.json')\n const restore = new Map<string, string>([\n [packageFile, await readFile(packageFile, 'utf8')],\n ])\n if (pin.spec !== target) await writePin(ws.rnessDir, pin.spec, target)\n\n const workflows = join(ws.rnessDir, '.github', 'workflows')\n for (const name of await readdir(workflows).catch(() => [])) {\n if (!/\\.ya?ml$/.test(name)) continue\n const file = join(workflows, name)\n const text = await readOrNull(file)\n if (text === null) continue\n const shown = `.github/workflows/${name}`\n if (name === 'validate.yml' && OLD_WORKFLOW_RUN.test(text)) {\n restore.set(file, text)\n await writeFileAtomic(\n file,\n text.replace(OLD_WORKFLOW_RUN, () => WORKFLOW_RUN)\n )\n ui.line(\n 'updated',\n `${shown} (it now reads the version from package.json)`\n )\n } else if (\n pin.spec !== target &&\n text.includes(`@rness/cli@${pin.spec}`)\n ) {\n ui.warn(`${shown} names @rness/cli@${pin.spec}; update it by hand`)\n }\n }\n\n // An organization created before 0.5.1 never runs the scaffold again, so\n // the upgrade is where it receives the bot that moves the pin by pull\n // request (spec 0008 §3.2).\n const dependabot = join(ws.rnessDir, '.github', 'dependabot.yml')\n if (await exists(dependabot)) {\n ui.hint('.github/dependabot.yml is already there — left as it is')\n } else {\n await mkdir(dirname(dependabot), { recursive: true })\n await writeFileAtomic(\n dependabot,\n await readFile(join(scaffoldDir(), '.github', 'dependabot.yml'), 'utf8')\n )\n ui.line(\n 'wrote',\n '.rness/.github/dependabot.yml (@rness/cli now moves by pull request)'\n )\n }\n\n try {\n await ui.step(\n { doing: `installing dependencies with ${pm}` },\n () => installDependencies(pm, ws.rnessDir),\n () => ['installed', `dependencies with ${pm}`]\n )\n } catch (e) {\n for (const [file, text] of restore) await writeFileAtomic(file, text)\n const message = e instanceof Error ? e.message : String(e)\n ui.error(message)\n ui.hint(`restored ${relative(cwd, packageFile) || packageFile}`, 'stderr')\n if (/minimum.?release.?age|NO_MATURE/i.test(message))\n ui.hint(\n \"pnpm refuses versions published less than 24 h ago: add '@rness/cli' under minimumReleaseAgeExclude in .rness/pnpm-workspace.yaml\",\n 'stderr'\n )\n return 1\n }\n const now = (await readPinnedCli(ws.rnessDir))?.version ?? null\n if (now !== target) {\n process.stderr.write(\n `${pm} install left @rness/cli ${now ?? 'not installed'} in ${label}, not ${target}\\n`\n )\n return 1\n }\n\n // The installed copy is a child with plain output: never a prompt.\n ui.gitIsSilent = true\n const code = await syncBlocks(ui, ws.root, basename(ws.root))\n if (code !== 0) return code\n\n const rel = relative(cwd, ws.rnessDir) || '.'\n const next = [\n `git -C ${rel} add -A && git -C ${rel} commit -m \"chore: rness ${target}\"`,\n '# teammates: git pull — the next rness command installs it',\n ]\n if (ui.session) {\n ui.note('Next steps', next)\n ui.outro(`${label} runs @rness/cli ${target}`)\n } else\n process.stdout.write(\n [\n '',\n status('upgraded', `${label} to @rness/cli ${target}`),\n '',\n 'Next:',\n ...next.map((line) => ` ${line}`),\n '',\n ].join('\\n')\n )\n return 0\n } catch (e) {\n return reportError(e)\n }\n}\n","import { join } from 'node:path'\n\nimport { isCurrentBlock, renderBlock } from './block.ts'\nimport { assembleContext } from './context.ts'\nimport { exists, readOrNull } from './fs.ts'\nimport { findBlock } from './merge.ts'\nimport { rnessCommand } from './pm.ts'\nimport type { Manifest } from './types.ts'\n\nexport interface CheckBlocksInput {\n root: string\n rnessDir: string\n manifest: Manifest\n org: string\n}\n\n/**\n * What a target's `AGENTS.md` turned out to be. `stale` and `malformed` are\n * problems, `missing-dir` and `no-block` only warnings; `current` says\n * nothing and carries no message.\n */\nexport type BlockStatus =\n 'current' | 'stale' | 'malformed' | 'missing-dir' | 'no-block'\n\nexport interface BlockCheck {\n label: string\n status: BlockStatus\n /** The line the plain look prints; null when the block is current. */\n message: string | null\n}\n\nexport interface CheckBlocksResult {\n problems: string[]\n warnings: string[]\n /** One entry per target, in the order they were checked (spec 0007 §5c). */\n checks: BlockCheck[]\n}\n\nconst PROBLEM: ReadonlySet<BlockStatus> = new Set(['stale', 'malformed'])\n\n/**\n * Compare every present block with a fresh render (spec 0003 §4.6): a\n * different hash is a problem, a missing block only a warning, and nothing\n * is checked where no `org/` directory exists (a standalone context checkout).\n */\nexport async function checkBlocks({\n root,\n rnessDir,\n manifest,\n org,\n}: CheckBlocksInput): Promise<CheckBlocksResult> {\n const checks: BlockCheck[] = []\n const note = (\n label: string,\n status: BlockStatus,\n message: string | null = null\n ): void => {\n checks.push({ label, status, message })\n }\n // The two flat arrays are a view over `checks`, so a line printed today\n // cannot drift from what the terminal renders.\n const derive = (): CheckBlocksResult => ({\n problems: checks\n .filter((c) => PROBLEM.has(c.status) && c.message !== null)\n .map((c) => c.message as string),\n warnings: checks\n .filter((c) => !PROBLEM.has(c.status) && c.message !== null)\n .map((c) => c.message as string),\n checks,\n })\n if (!(await exists(join(root, 'org')))) return derive()\n\n const targets: Array<{\n scope: string | null\n dir: string\n depth: number\n label: string\n }> = [{ scope: null, dir: root, depth: 0, label: 'AGENTS.md' }]\n for (const [name, entry] of Object.entries(manifest.scopes)) {\n const segments = entry.path.split('/')\n targets.push({\n scope: name,\n dir: join(root, ...segments),\n depth: segments.length,\n label: `${entry.path}/AGENTS.md`,\n })\n }\n\n for (const t of targets) {\n if (!(await exists(t.dir))) {\n note(\n t.label,\n 'missing-dir',\n `${t.label}: directory not present, block not checked`\n )\n continue\n }\n const text = await readOrNull(join(t.dir, 'AGENTS.md'))\n const lines = text === null ? [] : text.split(/\\r?\\n/)\n const found = findBlock(lines)\n if (found.kind === 'none') {\n note(\n t.label,\n 'no-block',\n `${t.label}: no rness block yet (run ${rnessCommand()} sync)`\n )\n continue\n }\n if (found.kind === 'error') {\n note(t.label, 'malformed', `${t.label}: ${found.message}`)\n continue\n }\n const context = await assembleContext({\n rnessDir,\n manifest,\n scope: t.scope,\n })\n const fresh = renderBlock({\n scope: t.scope,\n org,\n depth: t.depth,\n context,\n })\n // Two ways to be stale: the header no longer matches a fresh render, or the\n // body no longer matches its own header — a hand edit inside the block.\n if (isCurrentBlock(lines.slice(found.begin, found.end + 1), fresh.hash))\n note(t.label, 'current')\n else\n note(\n t.label,\n 'stale',\n `${t.label}: stale rness block (run ${rnessCommand()} sync)`\n )\n }\n return derive()\n}\n","import { join } from 'node:path'\n\nimport { collectMarkdown } from './collect.ts'\nimport { COLLECTIONS } from './context.ts'\nimport type { CollectionName } from './types.ts'\n\n/** Collections whose files must carry front matter with a `status`. */\nexport const STATUSES: Partial<Record<CollectionName, readonly string[]>> = {\n adr: ['Proposed', 'Accepted', 'Rejected', 'Superseded'],\n specs: [\n 'Draft',\n 'Proposed',\n 'Approved',\n 'Implemented',\n 'Superseded',\n 'Rejected',\n ],\n plans: ['Draft', 'Ready', 'In progress', 'Blocked', 'Completed', 'Abandoned'],\n}\nconst SKIP = new Set(['adr/0000-template.md'])\n/** Front-matter keys from the withdrawn routing feature — the directory decides. */\nconst PLACEMENT_KEYS = ['scopes', 'scope'] as const\n\n/** Human-readable problems across every collection; empty when the tree is valid. */\nexport async function checkContract(rnessDir: string): Promise<string[]> {\n const problems: string[] = []\n for (const name of COLLECTIONS) {\n const allowed = STATUSES[name]\n const items = await collectMarkdown(join(rnessDir, name))\n for (const item of items) {\n const where = `${name}/${item.rel}`\n if (SKIP.has(where)) continue\n if (item.fieldsError !== null) {\n problems.push(`${where}: invalid front matter (${item.fieldsError})`)\n continue\n }\n if (item.fields !== null) {\n for (const key of PLACEMENT_KEYS) {\n if (Object.hasOwn(item.fields, key)) {\n problems.push(\n `${where}: front matter \"${key}\" is not supported — the directory decides the scope; move the file`\n )\n }\n }\n }\n if (allowed === undefined) continue\n if (item.fields === null) {\n problems.push(`${where}: missing a front-matter block`)\n continue\n }\n if (item.title === null) problems.push(`${where}: missing a \"# \" title`)\n const status = item.fields['status']\n if (status === undefined || status === null || status === '') {\n problems.push(`${where}: missing \"status\"`)\n } else if (typeof status !== 'string' || !allowed.includes(status)) {\n problems.push(\n `${where}: unknown status ${JSON.stringify(status)} (expected ${allowed.join(', ')})`\n )\n }\n }\n }\n return problems\n}\n","import { checkBlocks } from '../core/blocks.ts'\nimport { checkContract } from '../core/contract.ts'\nimport type { CommandDeps } from '../core/deps.ts'\nimport { loadManifest, workspaceName } from '../core/manifest.ts'\nimport { scopeChain } from '../core/scope.ts'\nimport { warn } from '../core/style.ts'\nimport { defaultTerminal } from '../core/terminal.ts'\nimport { makeUi } from '../core/ui.ts'\nimport { findWorkspace } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\n\nexport interface ValidateOptions {\n /** Internal (tests): directory to resolve from; default `process.cwd()`. */\n cwd?: string\n}\n\n/**\n * `rness validate`: manifest, extends cycles, front-matter contract, stale\n * blocks. Returns the exit code.\n *\n * Off a terminal — CI, a git hook, an agent, a pipe — it writes the bytes it\n * always has (spec 0007 rule 1), and never loads a prompt library: that path\n * is ADR 0004's trust anchor. In a real terminal it speaks through the same\n * reporter as the interactive commands (spec 0007 §5c): a count of the blocks\n * that are current, a line for each that is not, and the verdict as the outro.\n */\nexport async function validateCommand(\n opts: ValidateOptions,\n deps: Partial<CommandDeps> = {}\n): Promise<number> {\n const cwd = opts.cwd ?? process.cwd()\n try {\n const ws = await findWorkspace(cwd)\n const manifest = await loadManifest(ws.rnessDir)\n // loadManifest only checks that extends targets exist; walk every scope so\n // an extends cycle is reported here rather than breaking `context` later.\n for (const s of Object.keys(manifest.scopes)) scopeChain(manifest, s)\n const org = workspaceName(manifest, ws.root)\n const problems = await checkContract(ws.rnessDir)\n const blocks = await checkBlocks({\n root: ws.root,\n rnessDir: ws.rnessDir,\n manifest,\n org,\n })\n problems.push(...blocks.problems)\n\n const ui = await makeUi(deps.terminal ?? defaultTerminal)\n if (!ui.session) {\n for (const p of problems) process.stderr.write(`${p}\\n`)\n for (const w of blocks.warnings) process.stderr.write(`${warn(w)}\\n`)\n if (problems.length > 0) return 1\n process.stdout.write('context ok\\n')\n return 0\n }\n\n ui.intro(`Validate ${org}`)\n // One line per target, as `sync` reports one per file it walked: the two\n // commands cross the same targets, so they read the same (spec 0007 §5c).\n // A conforming block is grey — green means something was written, and on a\n // large organization that is what must stand out (spec 0007 §4).\n for (const c of blocks.checks)\n if (c.message === null) ui.line('current', c.label)\n else if (c.status === 'stale' || c.status === 'malformed')\n ui.error(c.message)\n else ui.warn(c.message)\n for (const p of problems) if (!blocks.problems.includes(p)) ui.error(p)\n ui.outro(\n problems.length > 0 ? 'Context mismatch' : 'Context OK',\n problems.length > 0 ? 'error' : 'done'\n )\n return problems.length > 0 ? 1 : 0\n } catch (e) {\n return reportError(e)\n }\n}\n","import { Command, CommanderError, Option } from 'commander'\n\nimport { type AddOptions, addCommand } from './commands/add.ts'\nimport { type ContextOptions, contextCommand } from './commands/context.ts'\nimport { type CreateOptions, createCommand } from './commands/create.ts'\nimport { gitCredentialCommand } from './commands/git-credential.ts'\nimport { type LoginOptions, loginCommand } from './commands/login.ts'\nimport { logoutCommand } from './commands/logout.ts'\nimport { type SyncOptions, syncCommand } from './commands/sync.ts'\nimport { type UpgradeOptions, upgradeCommand } from './commands/upgrade.ts'\nimport { type ValidateOptions, validateCommand } from './commands/validate.ts'\nimport { PACKAGE_MANAGERS } from './core/pm.ts'\nimport { banner, bold, paint } from './core/style.ts'\nimport { VERSION } from './version.ts'\n\ninterface RunState {\n code: number\n}\n\nfunction buildProgram(state: RunState): Command {\n const program = new Command()\n .name('rness')\n .description('Configuration-plane CLI for rness workspaces')\n .version(VERSION, '-v, --version', 'print the version')\n .exitOverride()\n .showHelpAfterError()\n .configureOutput({\n writeOut: (s) => {\n process.stdout.write(s)\n },\n writeErr: (s) => {\n process.stderr.write(s)\n },\n outputError: (s, write) => {\n write(paint('error', s, process.stderr))\n },\n })\n // Before any sub-command is created: they inherit it. The painters answer\n // plain text off a terminal, so a piped help is what it always was.\n .configureHelp({\n styleTitle: (s) => bold(s),\n styleUsage: (s) => paint('done', s),\n styleCommandText: (s) => paint('info', s),\n styleSubcommandText: (s) => paint('info', s),\n styleArgumentText: (s) => paint('info', s),\n styleOptionText: (s) => paint('warn', s),\n styleDescriptionText: (s) => paint('idle', s),\n })\n // The root help only: a sub-command's help stays short.\n .addHelpText('before', () => banner(VERSION))\n\n program\n .command('context')\n .description('Resolve and print the context for a scope')\n .option(\n '--scope <name>',\n 'scope to resolve (default: the scope owning the current directory)'\n )\n .option('--json', 'print JSON instead of Markdown')\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (opts: ContextOptions) => {\n state.code = await contextCommand(opts)\n })\n\n program\n .command('validate')\n .description(\n 'Check the .rness/ tree against the contract and every generated block'\n )\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (opts: ValidateOptions) => {\n state.code = await validateCommand(opts)\n })\n\n program\n .command('sync')\n .description(\n 'Write the rness block into every AGENTS.md of the cloned repositories'\n )\n .option('--scope <name>', 'only this scope (the root block is skipped)')\n .option(\n '--check',\n 'render and compare only; exit 1 when a block is out of date'\n )\n .option('--pull', 'git pull --ff-only in every clean clone')\n .option('--all', 'clone every rness.json repository missing from org/')\n .option('-y, --yes', 'do not ask for confirmation')\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (opts: SyncOptions) => {\n state.code = await syncCommand(opts)\n })\n\n program\n .command('add')\n .description(\n 'Clone (or adopt) a repository under org/ and declare it in rness.json'\n )\n .argument('<repo>', '<repo>, <owner>/<repo>, or a clone URL')\n .option(\n '--scopes <list>',\n 'comma-separated sub-directories to declare as scopes extending the repository'\n )\n .option(\n '--ssh',\n 'force git@github.com: (default: SSH when it works, else HTTPS)'\n )\n .option('--https', 'force https://github.com/')\n .option('-y, --yes', 'do not ask for confirmation')\n .addOption(new Option('--host <base>').hideHelp())\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (repo: string, opts: AddOptions) => {\n state.code = await addCommand(repo, opts)\n })\n\n program\n .command('login')\n .description('Log in to GitHub, to list and clone private repositories')\n .option('--setup-git', \"make rness git's credential helper for github.com\")\n .option('--no-setup-git', 'do not ask about git')\n .addOption(new Option('--github-api <base>').hideHelp())\n .action(async (opts: LoginOptions) => {\n state.code = await loginCommand(opts)\n })\n\n program\n .command('logout')\n .description('Forget the GitHub login of this machine')\n .action(async () => {\n state.code = await logoutCommand()\n })\n\n // What git runs once `rness login` made rness its credential helper.\n program\n .command('git-credential', { hidden: true })\n .argument('<operation>')\n .action(async (operation: string) => {\n state.code = await gitCredentialCommand(operation)\n })\n\n program\n .command('upgrade')\n .alias('update')\n .description(\n 'Move this workspace to another @rness/cli: pin it in .rness/package.json, install, sync'\n )\n .argument('[version]', 'an exact version (default: the latest release)')\n .option('-y, --yes', 'do not ask for confirmation')\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (version: string | undefined, opts: UpgradeOptions) => {\n state.code = await upgradeCommand(version, opts)\n })\n\n program\n .command('create')\n .description(\n \"Create or join a GitHub organization's workspace, or a blank one with --blank\"\n )\n .argument(\n '[name]',\n 'the GitHub organization, same as --org; with --blank, the workspace directory'\n )\n .option(\n '--org <name>',\n 'the GitHub organization, exact name (github.com/<name>)'\n )\n .option(\n '--repos <list>',\n 'comma-separated repositories for your workspace (catalogue entries are cloned, others added)'\n )\n .option(\n '--pm <name>',\n `package manager for .rness/ (${PACKAGE_MANAGERS.join(', ')}; default: the one running this command)`\n )\n .option(\n '--ssh',\n 'force git@github.com: (default: SSH when it works, else HTTPS)'\n )\n .option('--https', 'force https://github.com/')\n .option(\n '--blank',\n 'a local workspace with no GitHub organization: .rness/, an empty org/, the root files'\n )\n .option('--skip-install', 'do not install .rness/ dependencies')\n .option('-y, --yes', 'do not ask for confirmation')\n .option('--template <name>', 'reserved')\n .addOption(new Option('--host <base>').hideHelp())\n .addOption(new Option('--github-api <base>').hideHelp())\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (orgArg: string | undefined, opts: CreateOptions) => {\n // Blank, the positional names the directory; --org is refused there.\n if (opts.blank === true) {\n state.code = await createCommand(\n orgArg === undefined ? opts : { ...opts, name: orgArg }\n )\n return\n }\n if (\n orgArg !== undefined &&\n opts.org !== undefined &&\n orgArg !== opts.org\n ) {\n process.stderr.write(\n `organization given twice: \"${orgArg}\" and --org \"${opts.org}\"\\n`\n )\n state.code = 2\n return\n }\n const org = opts.org ?? orgArg\n state.code = await createCommand(\n org === undefined ? opts : { ...opts, org }\n )\n })\n\n return program\n}\n\n/**\n * Parse user arguments and run the matching command. Returns the exit code\n * and never calls process.exit: 0 success, 1 handled error, 2 bad usage.\n */\nexport async function run(argv: string[]): Promise<number> {\n const state: RunState = { code: 0 }\n const program = buildProgram(state)\n if (argv.length === 0) {\n process.stdout.write(banner(VERSION) + program.helpInformation())\n return 0\n }\n try {\n await program.parseAsync(argv, { from: 'user' })\n } catch (e) {\n if (e instanceof CommanderError) {\n // Commander 15 reuses `commander.help`'s code for both the successful\n // `--help` path and error paths (e.g. `help wat`, a lone `--`), so the\n // exit code it already computed is the only reliable signal here.\n return e.exitCode === 0 ? 0 : 2\n }\n throw e\n }\n return state.code\n}\n","import { resolveToken } from '../core/auth.ts'\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = []\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer)\n return Buffer.concat(chunks).toString('utf8')\n}\n\n/**\n * `rness git-credential <get|store|erase>`: git's credential-helper protocol\n * (spec 0004 §5). Only `get` for https://github.com is answered, with the\n * token of this machine; everything else is silence, which tells git to look\n * elsewhere. `input` is what git writes on stdin.\n */\nexport async function gitCredentialCommand(\n operation: string,\n input?: string\n): Promise<number> {\n if (operation !== 'get') return 0\n const fields = new Map<string, string>()\n for (const line of (input ?? (await readStdin())).split('\\n')) {\n const eq = line.indexOf('=')\n if (eq > 0) fields.set(line.slice(0, eq), line.slice(eq + 1).trimEnd())\n }\n if (fields.get('protocol') !== 'https' || fields.get('host') !== 'github.com')\n return 0\n const resolved = await resolveToken().catch(() => null)\n if (resolved === null) return 0\n process.stdout.write(`username=x-access-token\\npassword=${resolved.token}\\n`)\n return 0\n}\n","import { spawnSync } from 'node:child_process'\n\nimport { pinnedBinPath } from './delegate.ts'\nimport {\n type EnsureOptions,\n driftWarning,\n ensureInstalled,\n pinDrift,\n} from './pinned.ts'\nimport { findWorkspace } from './workspace.ts'\n\n/**\n * `create` makes a workspace and `upgrade` replaces the pinned copy: both are\n * served by the copy the user invoked (spec 0006 §3). The login concerns the\n * machine, not a workspace — and git runs `git-credential` from inside a\n * clone, on every fetch: no delegation, no install and no warning there.\n */\nexport const OWN_COMMANDS: readonly string[] = [\n 'create',\n 'upgrade',\n 'update',\n 'login',\n 'logout',\n 'git-credential',\n]\n\n/**\n * Set in the environment once an invocation has looked at the drift. Two\n * copies can look in one invocation — the launcher, then the installed copy it\n * delegates to — and they are different modules, in one process or in a child:\n * the environment is the only state they share. Private, not a user setting.\n */\nexport const CATCH_UP_DONE = 'RNESS_CATCH_UP_DONE'\n\nexport interface CatchUpDeps {\n cwd?: string\n env?: NodeJS.ProcessEnv\n stderr?: (text: string) => void\n install?: EnsureOptions['install']\n /** Run the installed bin with the user's arguments; its exit code. */\n spawn?: (bin: string, argv: string[], cwd: string) => number\n}\n\n/**\n * Close the gap between the pin and what is installed, then hand the command\n * to the freshly installed copy (spec 0008 §4). Returns that copy's exit code,\n * or null when the caller should run the command itself: no workspace, no\n * drift, nothing to do for this command, or an install that did not close the\n * drift (reported as a warning).\n *\n * It runs in two places. The launcher calls it before delegating. The\n * package's exported `run` calls it too, because a launcher older than 0.5.1\n * never does: it imports the installed copy's `run` and knows nothing about\n * drift. Everything on this path is imported statically — after the install,\n * the tree this module was loaded from may be gone.\n */\nexport async function catchUp(\n argv: string[],\n deps: CatchUpDeps = {}\n): Promise<number | null> {\n const env = deps.env ?? process.env\n const cwd = deps.cwd ?? process.cwd()\n const command = argv[0]\n if (\n command === undefined ||\n command.startsWith('-') ||\n OWN_COMMANDS.includes(command) ||\n env['RNESS_NO_DELEGATE'] === '1' ||\n env[CATCH_UP_DONE] === '1'\n )\n return null\n const ws = await findWorkspace(cwd).catch(() => null)\n if (ws === null) return null\n env[CATCH_UP_DONE] = '1'\n\n const stderr = deps.stderr ?? ((text) => void process.stderr.write(text))\n // The version was decided by the pull request that moved the pin, so\n // catching up asks nothing.\n const outcome = await ensureInstalled(ws.rnessDir, {\n env,\n announce: (pin) => stderr(`installing @rness/cli ${pin} in .rness…\\n`),\n ...(deps.install === undefined ? {} : { install: deps.install }),\n })\n if (outcome === null) return null\n if (!outcome.installed) {\n const warning = await driftWarning(cwd)\n if (warning !== null) stderr(`${warning}\\n`)\n return null\n }\n // Only hand off when the install actually closed the drift: a child that\n // would install again on every run must never be spawned.\n if ((await pinDrift(ws.rnessDir)) !== null) return null\n const bin = await pinnedBinPath(ws.rnessDir)\n if (bin === null) return null\n // The pinned tree was just rebuilt: importing out of it in this process is\n // fragile, so the freshly installed copy runs as its own process.\n const spawn =\n deps.spawn ??\n ((file, args, dir) =>\n spawnSync(process.execPath, [file, ...args], {\n cwd: dir,\n env,\n stdio: 'inherit',\n }).status ?? 1)\n return spawn(bin, argv, cwd)\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,UAAU,SAAS,YAAY;AAExC,eAAsB,OAAO,GAA6B;AACxD,MAAI;AACF,UAAM,OAAO,CAAC;AACd,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOA,eAAsB,UAAU,GAA6B;AAC3D,MAAI;AACF,YAAQ,MAAM,MAAM,CAAC,GAAG,eAAe;AAAA,EACzC,SAAS,GAAG;AACV,QAAK,EAA4B,SAAS,SAAU,QAAO;AAC3D,UAAM;AAAA,EACR;AACF;AAGA,eAAsB,WAAW,GAAmC;AAClE,MAAI;AACF,WAAO,MAAM,SAAS,GAAG,MAAM;AAAA,EACjC,SAAS,GAAG;AACV,QAAK,EAA4B,SAAS,SAAU,QAAO;AAC3D,UAAM;AAAA,EACR;AACF;AAEA,IAAI,WAAW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A,IACA,OAAO;AAAA,EACT,CAAC,EAAE,UAAU;AACjB,SAAOA,OAAM,KAAK,MAAM,GAAG;AAC7B;","names":["readFile","rm","join","join","readFile","rm","reason","status","post","execFile","dirname","promisify","execFileP","firstLine","resolve","readFile","basename","join","basename","readFile","join","readFile","rm","join","join","rm","readFile","spawn","firstLine","STDERR_FLUSH_MS","resolve","spawn","access","stderr","reason","dirname","join","resolve","resolve","dirname","join","header","parse","fail","glob","readFile","join","posix","sep","sep","posix","glob","join","readFile","join","join","join","join","join","join","cancelled","access","basename","join","FULL_URL","basename","access","join","posix","sep","sep","posix","readFile","join","join","readFile","dirname","join","chmod","mkdir","readFile","stat","writeFile","dirname","join","join","mkdir","dirname","readFile","writeFile","stat","chmod","spawn","execFile","promisify","execFileP","spawn","mkdir","rename","rm","join","relative","resolve","mkdir","readdir","rm","stat","dirname","join","relative","execFile","readFile","basename","join","promisify","execFileP","promisify","execFile","readFile","join","basename","readdir","relative","dirname","join","stat","mkdir","rm","mkdir","join","relative","resolve","resolve","relative","mkdir","join","firstLine","access","join","rename","code","resolve","relative","mkdir","failures","name","rness","next","rm","execFile","mkdir","readFile","readdir","basename","dirname","join","relative","promisify","execFileP","promisify","execFile","basename","join","readFile","readdir","mkdir","dirname","relative","join","status","join","fresh","join","join","status","spawn"]}