@rness/cli 0.4.0 → 0.5.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/fs.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/core/delegate.ts","../src/core/pm.ts","../src/core/pinned.ts","../src/core/scaffold.ts","../src/core/scaffold-copy.ts","../src/version.ts","../src/commands/login.ts","../src/core/setup-git.ts","../src/commands/create.ts","../src/core/sync-blocks.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"],"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 { 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'\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 rness 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","/** 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 ADD_LATER = '; add repositories later with rness 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 rness add',\n { cause }\n )\n }\n return new Error(\n `GitHub API answered ${page.status} for ${path}${ADD_LATER}`,\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)${ADD_LATER}`,\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/** 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/** The organisation name every block and `add` use: `org`, else the root directory's name. */\nexport function resolveOrg(\n manifest: Manifest,\n root: string\n): { org: string; warning: string | null } {\n if (manifest.org !== null) return { org: manifest.org, warning: null }\n const name = basename(root)\n return {\n org: name,\n warning: `rness.json: no \"org\"; using the directory name \"${name}\"`,\n }\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,\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) 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 org: string\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 { 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. */\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: rness 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'])\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 * A title on a coloured background — the intro of a session. Without colour\n * it is the bare text: padding only makes sense around a background.\n */\nexport function badge(\n text: string,\n stream: NodeJS.WriteStream = process.stdout\n): string {\n if (noColor()) return text\n const padded = ` ${text} `\n const painted = styleText(['bgCyan', 'black', 'bold'], padded, {\n stream,\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 { dirname, join, parse, resolve } from 'node:path'\n\nimport { exists } from './fs.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","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 'read `STATUS.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}\\` — read \\`STATUS.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 { readdir } from 'node:fs/promises'\nimport { 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, resolveOrg } from '../core/manifest.ts'\nimport { ensureClaudeMd, findBlock, mergeBlock } from '../core/merge.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 { 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). */\nasync 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() && !e.name.startsWith('.'))\n .map((e) => e.name)\n )\n } catch {\n return new Set()\n }\n}\n\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, warning } = resolveOrg(manifest, ws.root)\n if (ownUi) ui.intro(`Sync workspace ${org}`)\n if (warning !== null) ui.warn(warning)\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(', ')} (rness add <name>, or rness 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(', ')} (rness 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(`${differences} block(s) out of date — run rness sync`)\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. */\nexport function sessionUi(p: Session): Ui {\n const say = (verb: string, text: string): void => {\n const tone = toneOf(verb)\n if (tone === 'done') p.log.step(text)\n else if (tone === 'warn') p.log.warn(text)\n else if (tone === 'idle') p.log.message(paint('idle', text))\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 p.outro(paint(tone, message))\n },\n line: (verb, rest, sentence) => {\n say(verb, sentence ?? tidy(`${verb} ${rest}`))\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 const finish = (\n result: Awaited<ReturnType<typeof work>>\n ): string | null => {\n const line = done?.(result) ?? null\n return line === null ? null : tidy(`${line[0]} ${line[1]}`)\n }\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 text = finish(result)\n if (text !== null) p.log.step(text)\n return result\n }\n const spin = p.spinner()\n spin.start(label)\n try {\n const result = await work()\n spin.stop(finish(result) ?? label)\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 { 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 { loadManifest, parseRepoSpec, resolveOrg } 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 { warn } from '../core/style.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 const { org, warning } = resolveOrg(manifest, ws.root)\n if (warning !== null) process.stderr.write(`${warn(warning)}\\n`)\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 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) ui.intro(`Add ${parsed.name} to workspace ${org}`)\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","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/**\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 { 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\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\n/** `<pm> install` in `dir`; output is swallowed, failure is one line. */\nexport async function installDependencies(\n pm: PackageManager,\n dir: string\n): Promise<void> {\n try {\n await execFileP(pm, ['install'], { cwd: dir, maxBuffer: 16 * 1024 * 1024 })\n } catch (e) {\n const err = e as { stderr?: string; message: string }\n throw new Error(\n `${pm} install failed in ${dir}: ${installErrorLine(err.stderr ?? err.message)}`,\n { cause: e }\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 { type PackageManager, isPackageManager } from './pm.ts'\nimport { warn } from './style.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 * 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\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 { cwd: root, maxBuffer: 16 * 1024 * 1024 }\n )\n return { code: 0, stdout, stderr }\n } catch (e) {\n const err = e as { code?: number; stdout?: string; stderr?: string }\n return {\n code: typeof err.code === 'number' ? err.code : 1,\n stdout: err.stdout ?? '',\n stderr: err.stderr ?? '',\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 * 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 rness 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 { cwd: root, maxBuffer: 16 * 1024 * 1024 }\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 { 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 '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","// Single source of the package version. test/version.test.ts keeps it equal\n// to package.json; bump both together.\nexport const VERSION = '0.5.0'\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 { 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 (rness logout undoes it)',\n 'git now asks rness for your github.com login over HTTPS (rness 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); rness 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, readdir, rename, rm, stat } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { dirname, join, relative, resolve } from 'node:path'\n\nimport type { CommandDeps } from '../core/deps.ts'\nimport { exists } from '../core/fs.ts'\nimport { clone, commitAll, init, 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 loadManifest,\n parseRepoSpec,\n writeManifest,\n} from '../core/manifest.ts'\nimport { EXACT_VERSION, compareVersions, readPin } from '../core/pinned.ts'\nimport {\n PACKAGE_MANAGERS,\n type PackageManager,\n detectPackageManager,\n installDependencies,\n isPackageManager,\n packageManagerVersion,\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 { copyScaffold } from '../core/scaffold-copy.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 { findWorkspace } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\nimport { VERSION } from '../version.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 /** 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\nasync function isEmptyDir(dir: string): Promise<boolean> {\n return (await readdir(dir)).length === 0\n}\n\nasync function insideWorkspace(dir: string): Promise<boolean> {\n try {\n await findWorkspace(dir)\n return true\n } catch {\n return false\n }\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\nfunction splitSpecs(list: string): string[] {\n return list\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s !== '')\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 */\nasync 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 rness sync`\n return `${shown} already holds an rness workspace (.rness/); run rness 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// 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 (l) => ['listed', `${l.repositories.length} repositories of ${org}`]\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 rness add <repo>`\n )\n else if (!provider.authenticated)\n ui.hint(\n 'only public repositories are listed; rness 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 // Archived repositories and hidden ones (a leading dot: .github, the\n // context repository .rness, …) are never candidates. GitHub names are\n // case-insensitive, so a name that differs from `NAME` only by case is\n // offered — and declared — in lowercase, as `rness add` would; any other\n // 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(\n (r) => !r.archived && !r.name.startsWith('.')\n )\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\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 // 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 const 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 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 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 = async (): Promise<void> => {\n if (opts.skipInstall === true) {\n ui.line('skipped', 'install (--skip-install)')\n return\n }\n await ui.step(\n { doing: `installing dependencies with ${pm}` },\n () => installDependencies(pm, rnessDir),\n () => ['installed', `dependencies with ${pm}`]\n )\n }\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 pin is the team's, in the repository just cloned: say when it is\n // behind this rness, and what moves it (spec 0006).\n const pin = (await readPin(rnessDir))?.spec\n if (\n pin !== undefined &&\n EXACT_VERSION.test(pin) &&\n compareVersions(pin, VERSION) < 0\n )\n ui.hint(\n `${org}/.rness pins @rness/cli ${pin} — you run ${VERSION}; rness upgrade moves the workspace`\n )\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(ui, root, shown, () =>\n syncCommand({ yes: true, cwd: root })\n )\n if (code !== 0) return code\n if (failures.length > 0)\n ui.note(\n 'Next steps',\n failures.map((f) => `rness add ${f.spec} # failed: ${f.message}`)\n )\n ui.outro(`You joined ${org} — your workspace is in ${shown}/`)\n return failures.length > 0 ? 1 : 0\n }\n\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 // Phase 1 — creating the workspace itself. Only these steps are rolled\n // back: past them the workspace exists and is worth keeping, whatever a\n // repository does next.\n try {\n await copyScaffold(rnessDir, {\n version: VERSION,\n packageManager: `${pm}@${pmVersion}`,\n })\n await writeManifest(rnessDir, catalogue)\n ui.line('created', `${shown}/.rness (new workspace)`)\n await install()\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(\n () => undefined\n )\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 1\n }\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 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 const code = await syncBlocks(ui, root, shown, () =>\n syncCommand({ yes: true, cwd: root })\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 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 `# then, for every teammate: npm 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 { runPinnedSync, summariseSync, syncPinned } from './pinned.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`).\n */\nexport async function syncBlocks(\n ui: Ui,\n root: string,\n shown: string,\n inPlace?: () => Promise<number>\n): Promise<number> {\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 rness sync`\n )\n return 1\n }\n for (const line of summariseSync(result.stdout).others) ui.hint(line)\n for (const line of result.stderr.split('\\n'))\n if (line.trim() !== '') ui.error(line)\n return result.code\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 { readFile, readdir } from 'node:fs/promises'\nimport { basename, join, relative } from 'node:path'\nimport { promisify } from 'node:util'\n\nimport { readPinnedCli } from '../core/delegate.ts'\nimport { 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 } from '../core/pm.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 rness 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: rness 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: rness 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 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, then ${pm} install in .rness`,\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 type { Manifest } from './types.ts'\n\nexport interface CheckBlocksInput {\n root: string\n rnessDir: string\n manifest: Manifest\n org: string\n}\n\nexport interface CheckBlocksResult {\n problems: string[]\n warnings: string[]\n}\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 problems: string[] = []\n const warnings: string[] = []\n if (!(await exists(join(root, 'org')))) return { problems, warnings }\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 warnings.push(`${t.label}: directory not present, block not checked`)\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 warnings.push(`${t.label}: no rness block yet (run rness sync)`)\n continue\n }\n if (found.kind === 'error') {\n problems.push(`${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 problems.push(`${t.label}: stale rness block (run rness sync)`)\n }\n }\n return { problems, warnings }\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 { loadManifest, resolveOrg } from '../core/manifest.ts'\nimport { scopeChain } from '../core/scope.ts'\nimport { warn } from '../core/style.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/** `rness validate`: manifest, extends cycles, front-matter contract, stale blocks. Returns the exit code. */\nexport async function validateCommand(opts: ValidateOptions): 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, warning } = resolveOrg(manifest, ws.root)\n const warnings: string[] = warning === null ? [] : [warning]\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 warnings.push(...blocks.warnings)\n for (const p of problems) process.stderr.write(`${p}\\n`)\n for (const w of 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 } 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 a workspace for a GitHub organization, or join its existing .rness'\n )\n .argument('[org]', 'the GitHub organization, same as --org')\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('--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 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"],"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;AA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;AAAA,IAC5C;AAAA,EACF,CAAC;AAEH,SAAO;AACT;AAMA,eAAsB,IAAI,MAAiC;AACzD,QAAM,QAAkB,EAAE,MAAM,EAAE;AAClC,QAAM,UAAU,aAAa,KAAK;AAClC,MAAI,KAAK,WAAW,GAAG;AACrB,YAAQ,OAAO,MAAM,OAAO,OAAO,IAAI,QAAQ,gBAAgB,CAAC;AAChE,WAAO;AAAA,EACT;AACA,MAAI;AACF,UAAM,QAAQ,WAAW,MAAM,EAAE,MAAM,OAAO,CAAC;AAAA,EACjD,SAAS,GAAG;AACV,QAAI,aAAa,gBAAgB;AAI/B,aAAO,EAAE,aAAa,IAAI,IAAI;AAAA,IAChC;AACA,UAAM;AAAA,EACR;AACA,SAAO,MAAM;AACf;","names":["readFile","rm","join","join","readFile","rm","reason","status","post","dirname","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","join","FULL_URL","access","join","posix","sep","sep","posix","readFile","join","join","readFile","execFile","promisify","execFileP","firstLine","execFile","readFile","basename","join","promisify","execFileP","promisify","execFile","readFile","join","basename","dirname","join","chmod","mkdir","readFile","stat","writeFile","dirname","join","join","mkdir","dirname","readFile","writeFile","stat","chmod","spawn","execFile","promisify","execFileP","spawn","mkdir","readdir","rename","rm","stat","dirname","join","relative","resolve","readdir","firstLine","relative","dirname","join","stat","access","rename","code","resolve","mkdir","failures","rm","execFile","readFile","readdir","basename","join","relative","promisify","execFileP","promisify","execFile","basename","join","readFile","readdir","relative","join","join","fresh","join","join","status"]}