@rness/cli 0.22.0 → 0.22.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/dist/bin/rness.js +2 -2
- package/dist/{chunk-AEL2W76O.js → chunk-A7NX55WK.js} +4 -4
- package/dist/chunk-A7NX55WK.js.map +1 -0
- package/dist/{chunk-XCO5ZT2H.js → chunk-DFGZWBBW.js} +202 -140
- package/dist/chunk-DFGZWBBW.js.map +1 -0
- package/dist/{chunk-S4NARIQP.js → chunk-H5E6FMP6.js} +89 -59
- package/dist/chunk-H5E6FMP6.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/{note-XSJ7ASXM.js → note-PANYS7DK.js} +3 -3
- package/dist/{summary-47SFWNSQ.js → summary-K5ETHXOX.js} +3 -3
- package/package.json +1 -1
- package/scaffold/README.md +3 -3
- package/scaffold/WORKSPACE.md +2 -2
- package/scaffold/adr/0000-template.md +5 -5
- package/dist/chunk-AEL2W76O.js.map +0 -1
- package/dist/chunk-S4NARIQP.js.map +0 -1
- package/dist/chunk-XCO5ZT2H.js.map +0 -1
- /package/dist/{note-XSJ7ASXM.js.map → note-PANYS7DK.js.map} +0 -0
- /package/dist/{summary-47SFWNSQ.js.map → summary-K5ETHXOX.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/transport.ts","../src/core/delegate.ts","../src/core/block.ts","../src/core/merge.ts","../src/commands/sync.ts","../src/core/agent-targets.ts","../src/core/claude-skills.ts","../src/core/agents.ts","../src/core/json-guarantees.ts","../src/core/pinned.ts","../src/core/ask-agents.ts","../src/commands/add.ts","../src/commands/context.ts","../src/core/scaffold.ts","../src/core/scaffold-copy.ts","../src/commands/create.ts","../src/core/approval.ts","../src/core/ask-provider.ts","../src/core/new-workspace.ts","../src/core/scaffold-git.ts","../src/core/sync-blocks.ts","../src/commands/create-blank.ts","../src/core/blocks.ts","../src/commands/logout.ts","../src/commands/upgrade.ts","../src/core/board-checks.ts","../src/core/check-workspace.ts","../src/commands/validate.ts","../src/cli.ts","../src/commands/doc.ts","../src/commands/git-credential.ts","../src/commands/hook.ts","../src/core/claude-code.ts","../src/core/edit-guard.ts","../src/core/safety-net.ts","../src/mcp/tools.ts","../src/commands/snapshot.ts","../src/commands/mcp.ts","../src/mcp/protocol.ts","../src/commands/status.ts","../src/core/status-view.ts","../src/commands/written-files.ts","../src/core/catch-up.ts"],"sourcesContent":["import { spawn } from 'node:child_process'\n\nimport { rnessCommand } from './pm.ts'\nimport { DEFAULT_HOST, SSH_HOST } from './remote.ts'\nimport { status } from './style.ts'\n\n/** The two bases a github.com URL can be written with (spec 0005). */\nexport interface Hosts {\n ssh: string\n https: string\n}\n\nexport const GITHUB_HOSTS: Hosts = { ssh: SSH_HOST, https: DEFAULT_HOST }\n\nexport type SshAccess =\n { ok: true; login: string } | { ok: false; reason: string }\n\nexport type DetectSsh = (opts: { interactive: boolean }) => Promise<SshAccess>\n\n/** What a command needs to choose between SSH and HTTPS; tests replace it. */\nexport interface Transport {\n hosts: Hosts\n detect: DetectSsh\n}\n\nconst GREETING = /^Hi ([^!\\s]+)! You've successfully authenticated/m\n\n/** The login in GitHub's `Hi <login>! You've successfully authenticated…`, or null. */\nexport function parseSshGreeting(stderr: string): string | null {\n return GREETING.exec(stderr)?.[1] ?? null\n}\n\nfunction firstLine(text: string): string | null {\n return (\n text\n .split('\\n')\n .find((l) => l.trim() !== '')\n ?.trim() ?? null\n )\n}\n\n/** As in `probeRemote`: what the pipe may still deliver after `'exit'`. */\nconst STDERR_FLUSH_MS = 200\n\n/**\n * `ssh -T git@github.com`: does github.com accept one of the user's keys?\n * GitHub greets an accepted key and exits 1, so the greeting — not the exit\n * code — is the answer.\n *\n * In a terminal `ssh` may ask for a key's passphrase or confirm github.com's\n * host key; it asks on `/dev/tty`, not on stderr, so stderr stays piped and\n * the greeting is still read. Without a terminal `BatchMode=yes` forbids\n * every prompt. Never throws and never hangs: the child is killed at the\n * deadline, and the answer never waits on `'close'`.\n */\nexport async function detectGithubSsh(opts: {\n interactive: boolean\n /** Tests: a fake executable, called by path. */\n command?: string\n timeoutMs?: number\n}): Promise<SshAccess> {\n const timeoutMs = opts.timeoutMs ?? (opts.interactive ? 120_000 : 10_000)\n const args = [\n '-T',\n '-o',\n 'ConnectTimeout=5',\n ...(opts.interactive ? [] : ['-o', 'BatchMode=yes']),\n 'git@github.com',\n ]\n return new Promise<SshAccess>((resolve) => {\n const child = spawn(opts.command ?? 'ssh', args, {\n stdio: [opts.interactive ? 'inherit' : 'ignore', 'ignore', 'pipe'],\n })\n const chunks: string[] = []\n child.stderr?.setEncoding('utf8')\n child.stderr?.on('data', (chunk: string) => chunks.push(chunk))\n\n let settled = false\n const settle = (access: SshAccess): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n child.stderr?.destroy()\n resolve(access)\n }\n const timer = setTimeout(() => {\n child.kill('SIGKILL')\n settle({ ok: false, reason: `timed out after ${timeoutMs / 1000}s` })\n }, timeoutMs)\n\n child.on('error', (e: Error) => settle({ ok: false, reason: e.message }))\n child.on('exit', (code) => {\n const finish = (): void => {\n const stderr = chunks.join('')\n const login = parseSshGreeting(stderr)\n settle(\n login !== null\n ? { ok: true, login }\n : {\n ok: false,\n reason:\n firstLine(stderr) ?? `ssh exited with code ${code ?? '?'}`,\n }\n )\n }\n const stderr = child.stderr\n if (stderr === null || stderr.readableEnded || stderr.destroyed)\n return finish()\n const flush = setTimeout(finish, STDERR_FLUSH_MS)\n const done = (): void => {\n clearTimeout(flush)\n finish()\n }\n stderr.once('end', done)\n stderr.once('error', done)\n })\n })\n}\n\nexport const defaultTransport: Transport = {\n hosts: GITHUB_HOSTS,\n detect: detectGithubSsh,\n}\n\nexport interface SshTest {\n access: SshAccess\n /** SSH works without asking anything: git over SSH will not prompt either. */\n unattended: boolean\n}\n\n/**\n * The SSH test, unattended first (`BatchMode=yes`): when that passes, ssh\n * never asks anything and a progress line may animate while git runs. Only\n * when it fails, and in a terminal, the test runs again letting ssh ask for a\n * passphrase — `announce` says so first.\n */\nexport async function testGithubSsh(\n transport: Transport,\n interactive: boolean,\n announce: () => void\n): Promise<SshTest> {\n const batch = await transport.detect({ interactive: false })\n if (batch.ok || !interactive) return { access: batch, unattended: batch.ok }\n announce()\n return {\n access: await transport.detect({ interactive: true }),\n unattended: false,\n }\n}\n\nconst loggedInAs = (login?: string | null): string =>\n login === undefined || login === null ? '' : `, logged in as ${login}`\n\n/** The outcome of the SSH test as a sentence, for the session look. */\nexport function usingSentence(\n access: SshAccess,\n login?: string | null\n): string {\n return access.ok\n ? `SSH works for github.com (as ${access.login}) — repositories are cloned over SSH`\n : `No SSH access to github.com (${access.reason}) — repositories are cloned over HTTPS${loggedInAs(login)}`\n}\n\n/** Is `url` written with the SSH base? */\nexport function isSshUrl(url: string, hosts: Hosts): boolean {\n return url.startsWith(hosts.ssh)\n}\n\n/** Printed in a terminal before the test, which may ask for a passphrase. */\nexport const CHECKING_LINE = status('checking', 'ssh access to github.com…')\n/** The same as `[verb, rest, sentence]`, for a `Ui`. */\nexport const CHECKING = [\n 'checking',\n 'ssh access to github.com…',\n 'Checking SSH access to github.com — ssh may ask for your passphrase',\n] as const\n\n/** `login`: who rness is logged in as, which is what makes HTTPS reach private repositories. */\nexport function usingRest(access: SshAccess, login?: string | null): string {\n return access.ok\n ? `ssh (github.com as ${access.login})`\n : `https (ssh to github.com unavailable: ${access.reason}${loggedInAs(login)})`\n}\n\nexport function usingLine(access: SshAccess, login?: string | null): string {\n return status('using', usingRest(access, login))\n}\n\n/** Why an SSH workspace cannot be served, and how to fix it. */\n/**\n * A child's `git clone` failed on publickey although the parent's own SSH test\n * passed: the key works but no agent holds it, so git's `ssh` asks again in\n * every child (spec 0008 §2.1).\n */\nexport function agentHintLines(\n platform: NodeJS.Platform = process.platform\n): string[] {\n const mac = platform === 'darwin'\n return [\n 'your key works but is not loaded; ssh asks again in every child:',\n ` ssh-add ${mac ? '--apple-use-keychain ' : ''}~/.ssh/id_ed25519`,\n ` ~/.ssh/config: AddKeysToAgent yes${mac ? ', UseKeychain yes' : ''}`,\n ]\n}\n\n/**\n * The SSH test passed only once ssh could ask (a passphrase, and no agent\n * holding the key): every clone over SSH asks again. Said once, before them.\n */\nexport function passphraseHint(\n platform: NodeJS.Platform = process.platform\n): string {\n return [\n 'ssh asked for your passphrase, and asks again for every repository unless an agent holds the key:',\n ...agentHintLines(platform).slice(1),\n ].join('\\n')\n}\n\nexport function sshWorkspaceLines(reason: string): [string, string] {\n return [\n `this workspace clones over SSH (rness.json) but ssh to github.com fails: ${reason}`,\n 'set up an SSH key: https://docs.github.com/authentication/connecting-to-github-with-ssh',\n ]\n}\n\n/** The user-side escape hatch where `rness.json` is not negotiable. */\nexport const INSTEAD_OF_LINES: [string, string] = [\n 'or make git use HTTPS for github.com on this machine:',\n ' git config --global url.\"https://github.com/\".insteadOf git@github.com:',\n]\n\nexport function httpsFlagLine(spec: string): string {\n return `or clone this repository over HTTPS: ${rnessCommand()} add ${spec} --https`\n}\n","import { 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 pinned copy's launcher, relative to `.rness`: what the Claude target's\n * hooks and skills run.\n */\nexport const PINNED_BIN = `node_modules/@rness/cli/${DEFAULT_BIN}`\n\n/**\n * The `@rness/cli` installed under `<rnessDir>/node_modules`, or null when\n * nothing is installed there. Reading the package's own `package.json` is what\n * makes the launcher and `create` agree on which copy owns a workspace.\n */\nexport async function readPinnedCli(\n rnessDir: string\n): Promise<PinnedCli | null> {\n const dir = join(rnessDir, 'node_modules', '@rness', 'cli')\n let pkg: { version?: unknown; bin?: unknown }\n try {\n pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) as {\n version?: unknown\n bin?: unknown\n }\n } catch {\n return null\n }\n const declared = pkg.bin\n let bin = DEFAULT_BIN\n if (typeof declared === 'string') bin = declared\n else if (declared !== null && typeof declared === 'object') {\n const named = (declared as Record<string, unknown>)['rness']\n if (typeof named === 'string') bin = named\n }\n return {\n dir,\n bin,\n version: typeof pkg.version === 'string' ? pkg.version : null,\n }\n}\n\n/** Absolute path of the pinned copy's executable, or null when nothing is installed. */\nexport async function pinnedBinPath(rnessDir: string): Promise<string | null> {\n const pinned = await readPinnedCli(rnessDir)\n if (pinned === null) return null\n return join(pinned.dir, ...pinned.bin.split('/'))\n}\n\n/**\n * The `@rness/cli` pinned in `<workspace>/.rness/package.json` (installed under\n * `.rness/node_modules`), when it exists and is not the running version. The\n * pinned copy is the only one that should ever act on a workspace.\n */\nexport async function findDelegate(\n cwd: string,\n ownVersion: string\n): Promise<Delegate | null> {\n let root: string\n let rnessDir: string\n try {\n const ws = await findWorkspace(cwd)\n root = ws.root\n rnessDir = ws.rnessDir\n } catch {\n return null\n }\n const pinned = await readPinnedCli(rnessDir)\n if (pinned === null) return null\n const { version } = pinned\n if (version === null || version === ownVersion) return null\n return { entry: join(pinned.dir, 'dist', 'index.js'), version, root }\n}\n","import { createHash } from 'node:crypto'\n\nimport type { Context } from './types.ts'\n\nexport const BEGIN = '<!-- BEGIN rness -->'\nexport const END = '<!-- END rness -->'\n/** Blocks above this size are written with a warning (spec 0003 §4.2). */\nexport const BLOCK_SIZE_WARNING = 32 * 1024\n\nexport interface BlockInput {\n /** Scope name, or null for the workspace-root global block. */\n scope: string | null\n org: string\n /** Path segments between the scope directory and the workspace root (`org/web` → 2; root → 0). */\n depth: number\n context: Context\n}\n\nexport interface RenderedBlock {\n /** The whole block, LF line endings, no trailing newline. */\n text: string\n hash: string\n bytes: number\n}\n\nexport interface BlockHeader {\n /** The CLI version a 0.2–0.4 header named; null for the current form. */\n version: string | null\n scope: string\n hash: string\n}\n\n// The header names no CLI version (spec 0006 §1): nothing read it, and it\n// made every upgrade rewrite every block. The 0.2–0.4 form still parses, so a\n// block written by an older CLI stays current as long as its hash is.\nconst HEADER =\n /^<!-- rness (?:(\\S+) )?· scope: (\\S+) · contract: 1 · hash: ([0-9a-f]{12}) · generated: run `rness sync`, never edit inside this block -->$/\n\nfunction toLf(s: string): string {\n return s.replace(/\\r\\n?/g, '\\n')\n}\n\n/** SHA-256 of the LF-normalised body, first 12 hex characters. */\nexport function blockHash(body: string): string {\n return createHash('sha256')\n .update(toLf(body), 'utf8')\n .digest('hex')\n .slice(0, 12)\n}\n\nfunction intro(scope: string | null, org: string, depth: number): string {\n if (scope === null) {\n return [\n `This is the root of rness workspace \\`${org}\\`. Full context lives in \\`.rness/\\` —`,\n 'start at its `AGENTS.md`, then task-relevant `adr/`, `specs/`, `plans/`; live: `rness context`.',\n 'Every `org/<repo>/` carries its own block with the rules that apply there.',\n ].join('\\n')\n }\n const rel = `${'../'.repeat(depth)}.rness/`\n return [\n `This directory is scope \\`${scope}\\` of rness workspace \\`${org}\\`. Full context lives in`,\n `\\`${rel}\\` — start at its \\`AGENTS.md\\`, then task-relevant \\`adr/\\`, \\`specs/\\`, \\`plans/\\`;`,\n `live: \\`rness context --scope ${scope}\\`. If \\`.rness/\\` is not reachable, this is a`,\n 'standalone clone: the rules below are all you have.',\n ].join('\\n')\n}\n\nfunction header(scope: string | null, hash: string): string {\n return `<!-- rness · scope: ${scope ?? 'global'} · contract: 1 · hash: ${hash} · generated: run \\`rness sync\\`, never edit inside this block -->`\n}\n\n/** Render the block for one scope (or the root) from an already resolved context. */\nexport function renderBlock({\n scope,\n org,\n depth,\n context,\n}: BlockInput): RenderedBlock {\n const standards =\n context.collections.find((c) => c.name === 'standards')?.files ?? []\n const rules =\n standards.length === 0\n ? ['_No standards apply to this scope yet._']\n : standards.map(\n (f) => `<!-- rness: standards/${f.rel} -->\\n${toLf(f.content).trim()}`\n )\n const body = `${intro(scope, org, depth)}\\n\\n## Rules\\n${rules.join('\\n\\n')}`\n const hash = blockHash(body)\n const text = [BEGIN, header(scope, hash), body, END].join('\\n')\n return { text, hash, bytes: Buffer.byteLength(text, 'utf8') }\n}\n\n/** Parse the header line of a block; null when the line is not a rness header. */\nexport function parseHeader(line: string): BlockHeader | null {\n const m = HEADER.exec(line.trimEnd())\n if (m === null) return null\n return { version: m[1] ?? null, scope: m[2] ?? '', hash: m[3] ?? '' }\n}\n\n/** The hashed body of a block given its lines (BEGIN, header, body…, END). */\nexport function bodyOf(blockLines: string[]): string {\n return blockLines.slice(2, -1).join('\\n')\n}\n\n/**\n * Is this block (BEGIN, header, body…, END) what a fresh render would write?\n * By hash, never by text: the header's hash is the fresh one, and the body\n * still hashes to it — a hand edit inside the block breaks the second half.\n */\nexport function isCurrentBlock(\n blockLines: string[],\n freshHash: string\n): boolean {\n const header = parseHeader(blockLines[1] ?? '')\n return (\n header !== null &&\n header.hash === freshHash &&\n blockHash(bodyOf(blockLines)) === freshHash\n )\n}\n","import { 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\nconst POINTER = '@AGENTS.md'\n\n/**\n * The workspace root `CLAUDE.md` (spec 0011 §2): the global block in clear.\n * Claude Code loads it from every directory below, where `@AGENTS.md` would\n * be an import outside the working directory — gated behind a dialog. So the\n * pointer line rness wrote there is dropped, and the block merged like any\n * other; the rest of the file is kept.\n */\nexport function claudeMdAtRoot(\n existing: string | null,\n block: string\n): MergeResult {\n if (existing === null) return mergeBlock(null, block)\n const lines = existing.split(/\\r?\\n/)\n if (!lines.some((l) => l.trim() === POINTER))\n return mergeBlock(existing, block)\n const eol = existing.includes('\\r\\n') ? '\\r\\n' : '\\n'\n const rest = lines.filter((l) => l.trim() !== POINTER).join(eol)\n const merged = mergeBlock(rest.trim() === '' ? null : rest, block)\n return merged.ok ? { ...merged, changed: merged.text !== existing } : merged\n}\n\n/**\n * `CLAUDE.md` next to an `AGENTS.md`: create with `@AGENTS.md`, or prepend that\n * line when absent. A symlinked `CLAUDE.md` is left exactly as it is — reading\n * would follow it and the atomic rename would replace the link with a regular\n * file holding a copy of its target. (`sync` skips such a directory outright;\n * this guard is defence in depth for any other caller.)\n */\nexport async function ensureClaudeMd(\n dir: string\n): Promise<'created' | 'prepended' | 'unchanged'> {\n const file = join(dir, 'CLAUDE.md')\n if (await isSymlink(file)) return 'unchanged'\n const existing = await readOrNull(file)\n if (existing === null) {\n await writeFileAtomic(file, '@AGENTS.md\\n')\n return 'created'\n }\n if (existing.split(/\\r?\\n/).some((l) => l.trim() === '@AGENTS.md'))\n return 'unchanged'\n const eol = existing.includes('\\r\\n') ? '\\r\\n' : '\\n'\n await writeFileAtomic(file, `@AGENTS.md${eol}${existing}`)\n return 'prepended'\n}\n","import { join } from 'node:path'\n\nimport {\n BLOCK_FILES,\n agentTargets,\n leftoverTargets,\n writtenFiles,\n} from '../core/agent-targets.ts'\nimport {\n SUPPORTED_AGENTS,\n unsupportedAgents,\n unsupportedMessage,\n} from '../core/agents.ts'\nimport { askAgents } from '../core/ask-agents.ts'\nimport {\n BLOCK_SIZE_WARNING,\n isCurrentBlock,\n renderBlock,\n} from '../core/block.ts'\nimport { migrateBoards } from '../core/board-migration.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 { loadManifest, workspaceName, writeManifest } from '../core/manifest.ts'\nimport {\n type MergeResult,\n claudeMdAtRoot,\n ensureClaudeMd,\n findBlock,\n mergeBlock,\n} from '../core/merge.ts'\nimport { rnessCommand } from '../core/pm.ts'\nimport type { GitCredentials } from '../core/provider.ts'\nimport { openGitProvider } from '../core/providers.ts'\nimport { count } from '../core/style.ts'\nimport { type Terminal, defaultTerminal } from '../core/terminal.ts'\nimport {\n CHECKING,\n INSTEAD_OF_LINES,\n defaultTransport,\n isSshUrl,\n passphraseHint,\n sshWorkspaceLines,\n testGithubSsh,\n} from '../core/transport.ts'\nimport type { Manifest } from '../core/types.ts'\nimport { type Line, type Ui, makeUi, plainUi } from '../core/ui.ts'\nimport { clonesIn, findWorkspace } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\n\nexport interface SyncOptions {\n /** Only this scope's block (the root block is skipped). */\n scope?: string\n /** Render and compare; write nothing; exit 1 when any block differs. */\n check?: boolean\n /** `git pull --ff-only` in every clean clone. */\n pull?: boolean\n /** Clone every catalogue repository missing from `org/`; by default none is cloned. */\n all?: boolean\n /** Skip the confirmation prompt. */\n yes?: boolean\n /** Agents to declare in rness.json before compiling them (spec 0011 §3.2). */\n agent?: string[]\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\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/**\n * Bring one file's rness block up to date — or, in `check`, only say whether\n * it is. 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. At the root\n * `CLAUDE.md` a leftover `@AGENTS.md` pointer also makes it out of date.\n */\nasync function syncBlockFile(\n file: string,\n block: { text: string; hash: string },\n check: boolean,\n rootClaudeMd = false\n): Promise<'unchanged' | 'stale' | 'updated' | { error: string }> {\n const existing = await readOrNull(file)\n const existingLines = existing === null ? [] : existing.split(/\\r?\\n/)\n const span = findBlock(existingLines)\n const current =\n span.kind === 'one' &&\n isCurrentBlock(existingLines.slice(span.begin, span.end + 1), block.hash) &&\n !(rootClaudeMd && existingLines.some((l) => l.trim() === '@AGENTS.md'))\n const merged: MergeResult = current\n ? { ok: true, text: existing ?? '', changed: false }\n : rootClaudeMd\n ? claudeMdAtRoot(existing, block.text)\n : mergeBlock(existing, block.text)\n if (!merged.ok) return { error: merged.error }\n if (!merged.changed) return 'unchanged'\n if (check) return 'stale'\n await writeFileAtomic(file, merged.text)\n return 'updated'\n}\n\n/** The picker's \"select all\" entry; no repository name can take this value. */\nconst SELECT_ALL = '*'\n\n/** The directories under `org/` — the user's workspace (ADR 0008). */\n/**\n * In a terminal: offer the catalogue repositories that are not cloned, or\n * confirm when there are none. Returns the repositories to clone, or an exit\n * code when the run stops here.\n */\nasync function askWhatToSync(input: {\n org: string\n missing: readonly string[]\n offer: boolean\n terminal: Terminal\n ui: Ui\n}): Promise<string[] | number> {\n if (!input.terminal.isTty()) {\n process.stderr.write(\n 'rness sync writes files; pass --yes to run without a prompt\\n'\n )\n return 2\n }\n const p = await input.terminal.prompts()\n const cancelled = (): number => {\n input.ui.cancelled()\n return 1\n }\n if (input.offer && input.missing.length > 0) {\n const answer = await p.autocompleteMultiselect({\n message: 'Do you want to sync as well?',\n options: [\n {\n value: SELECT_ALL,\n label: 'Select all',\n hint: `${count(input.missing.length, ['repository', '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 (\n manifest: Manifest,\n url: string\n ): Promise<GitCredentials | null> =>\n (provider ??=\n (await openGitProvider(manifest)) ?? undefined)?.credentialsFor(url) ??\n null\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 const agentFlags = opts.agent ?? []\n if (agentFlags.length > 0 && check) {\n process.stderr.write(\n '--agent cannot be combined with --check: it declares agents in rness.json\\n'\n )\n return 2\n }\n const unknown = unsupportedAgents(agentFlags)[0]\n if (unknown !== undefined) {\n process.stderr.write(\n `unknown agent \"${unknown}\" (supported: ${SUPPORTED_AGENTS.join(', ')})\\n`\n )\n return 2\n }\n try {\n const ws = await findWorkspace(cwd)\n const manifest = await loadManifest(ws.rnessDir)\n const org = workspaceName(manifest, ws.root)\n // An agent this copy cannot compile would leave the team's files half\n // made: refuse before anything is written (spec 0011 §3.1).\n const unsupported = unsupportedAgents(manifest.agents ?? [])[0]\n if (unsupported !== undefined) {\n process.stderr.write(`${unsupportedMessage(unsupported)}\\n`)\n return 1\n }\n if (ownUi) ui.intro(`Sync workspace ${org}`)\n if (\n opts.scope !== undefined &&\n !Object.hasOwn(manifest.scopes, opts.scope)\n ) {\n process.stderr.write(`unknown scope: ${opts.scope}\\n`)\n return 1\n }\n\n // The team's agents: named on the command line, or asked once in a\n // terminal; never asked by --yes, --check or --scope (spec 0011 §3.2).\n let declare: string[] | null = null\n if (agentFlags.length > 0) {\n const current = manifest.agents ?? []\n const added = agentFlags.filter((a) => !current.includes(a))\n if (added.length > 0) declare = [...current, ...new Set(added)]\n } else if (\n manifest.agents === null &&\n !check &&\n opts.yes !== true &&\n opts.scope === undefined &&\n terminal.isTty()\n ) {\n const answer = await askAgents(await terminal.prompts())\n if (answer === null) {\n ui.cancelled()\n return 1\n }\n declare = answer\n }\n if (declare !== null) {\n const before = manifest.agents ?? []\n manifest.agents = declare\n await writeManifest(ws.rnessDir, manifest)\n for (const name of declare.filter((a) => !before.includes(a)))\n ui.line('declared', `agent ${name} in .rness/rness.json`)\n if (declare.length === 0)\n ui.line('declared', 'no agent in .rness/rness.json')\n ui.hint('rness.json changed: commit it in .rness, for the whole team')\n }\n\n // The boards (plan 0045): a number written whole, a README's\n // declarations moved, a newer preset merged. Workspace-wide: not for\n // one scope, never under --check. An upgrade commits what this writes.\n if (!check && opts.scope === undefined) {\n const boards = await migrateBoards(ws.rnessDir, manifest)\n if (boards.changed) {\n manifest.boards = boards.boards\n await writeManifest(ws.rnessDir, manifest)\n for (const [rel, text] of boards.readmes)\n await writeFileAtomic(join(ws.rnessDir, ...rel.split('/')), text)\n }\n for (const [verb, rest] of boards.lines) ui.line(verb, rest)\n if (boards.changed)\n ui.hint('rness.json changed: commit it in .rness, for the whole team')\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 else if (access.ok) ui.hint(passphraseHint(), 'stderr')\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(manifest, 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 // The files sync writes itself are not the developer's changes:\n // the blocks, and the declared agents' files (spec 0011 §3.3). A\n // user's uncommitted edit to a tracked AGENTS.md is therefore not\n // a veto — git pull --ff-only still refuses to overwrite it and\n // that surfaces as a problem.\n if (!(await isClean(dir, writtenFiles(manifest)))) {\n lines.push(['skipped', `${label} (working tree not clean)`])\n continue\n }\n const credentials = await credentialsFor(manifest, repo.url)\n await ui.step({ doing: `pulling ${label}`, git: true }, () =>\n pullFastForward(dir, credentials)\n )\n lines.push(['pulled', `${label}`])\n } catch (e) {\n problems.push(\n `${label}: ${e instanceof Error ? e.message : String(e)}`\n )\n }\n }\n }\n\n if (notCloned.size > 0)\n lines.push(\n `not cloned: ${[...notCloned].join(', ')} (${rnessCommand()} add <name>, or ${rnessCommand()} sync --all)`\n )\n // A clone the catalogue does not know gets no block: no scope declares\n // its rules. Say how to bring it in rather than skipping it silently.\n const scoped = new Set(\n Object.values(manifest.scopes).map((s) => s.path.split('/')[1])\n )\n const undeclared = [...clones].filter(\n (n) => !Object.hasOwn(manifest.repos, n) && !scoped.has(n)\n )\n if (undeclared.length > 0)\n lines.push(\n `not in rness.json: ${undeclared.join(', ')} (${rnessCommand()} add <name> declares it)`\n )\n\n // 2. Blocks — only where repositories live; a standalone context checkout has no org/.\n if (!(await exists(join(ws.root, 'org')))) {\n lines.push(['skipped', 'blocks (no org/ directory here)'])\n } else {\n let differences = 0\n for (const t of targetsOf(manifest, ws.root, opts.scope)) {\n if (!(await exists(t.dir))) {\n // A scope inside a repository that is not cloned is covered by\n // the `not cloned:` line; only a directory missing from a present\n // clone (or from no repository at all) is worth its own line.\n const repo = t.label.split('/')[1]\n if (\n !t.label.startsWith('org/') ||\n repo === undefined ||\n !notCloned.has(repo)\n )\n lines.push(['skipped', `${t.label} (directory not present)`])\n continue\n }\n // In a scope, one of the pair symlinked to the other (the common\n // `CLAUDE.md → AGENTS.md`) leaves the directory untouched: reading\n // follows the link, and the atomic rename would replace the link with\n // a duplicate of its target. At the root a link is still never\n // rewritten, but the other file is (spec 0011 §2).\n const [agentsLinked, claudeLinked] = await Promise.all(\n BLOCK_FILES.map((f) => isSymlink(join(t.dir, f)))\n )\n const atRoot = t.scope === null\n if (!atRoot && (agentsLinked === true || claudeLinked === 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 agents =\n agentsLinked === true\n ? 'skipped'\n : await syncBlockFile(join(t.dir, 'AGENTS.md'), block, check)\n if (typeof agents === 'object') {\n problems.push(`${t.label}: ${agents.error}`)\n continue\n }\n lines.push(\n agents === 'skipped'\n ? ['skipped', `${t.label} (symlink)`]\n : [agents, t.label]\n )\n if (agents === 'stale') differences += 1\n if (!atRoot) {\n if (!check) await ensureClaudeMd(t.dir)\n continue\n }\n // The root CLAUDE.md follows the root AGENTS.md: its line is said\n // only when its status differs (a pointer converted, a hand edit).\n if (claudeLinked === true) continue\n const claude = await syncBlockFile(\n join(t.dir, 'CLAUDE.md'),\n block,\n check,\n true\n )\n if (typeof claude === 'object') {\n problems.push(`CLAUDE.md: ${claude.error}`)\n continue\n }\n if (claude === 'stale') differences += 1\n if (claude !== agents) lines.push([claude, 'CLAUDE.md'])\n }\n if (check && differences > 0)\n problems.push(\n `${differences} block(s) out of date — run ${rnessCommand()} sync`\n )\n\n // 3. Agent targets — the whole workspace, so never under --scope.\n if (opts.scope === undefined) {\n let stale = 0\n for (const o of await agentTargets(ws.root, manifest, { check })) {\n if (o.status === 'invalid')\n problems.push(\n `${o.label}: ${o.detail ?? 'unreadable'}; fix it, then ${rnessCommand()} sync`\n )\n else if (o.status === 'stale') {\n stale += 1\n lines.push(['stale', `${o.label} (${o.detail ?? ''})`])\n } else lines.push([o.status, o.label])\n }\n if (stale > 0)\n problems.push(\n `${stale} agent file(s) out of date — run ${rnessCommand()} sync`\n )\n if (!check)\n for (const label of await leftoverTargets(ws.root, manifest))\n lines.push(\n `${label} still carries the values of an agent no longer in rness.json (left as is)`\n )\n }\n }\n\n return problems.length > 0 ? 1 : 0\n } finally {\n // Both flushes run even when something above throws, and stdout precedes\n // stderr so the report reads in order. The exit code above is computed\n // before this block, so it is unaffected.\n for (const l of lines)\n if (typeof l === 'string') ui.hint(l)\n else ui.line(l[0], l[1])\n for (const p of problems) ui.error(p)\n if (ownUi)\n ui.outro(\n problems.length > 0\n ? 'Done, with problems'\n : check\n ? 'Checked'\n : 'Your clones carry the current context',\n problems.length > 0 ? 'warn' : 'done'\n )\n }\n } catch (e) {\n return reportError(e)\n }\n}\n","import { mkdir, rm, rmdir } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\n\nimport {\n type AgentTarget,\n type Guarantee,\n TARGETS,\n type TargetContext,\n} from './agents.ts'\nimport { exists, readOrNull, writeFileAtomic } from './fs.ts'\nimport {\n describeGuarantee,\n ensureGuarantees,\n missingGuarantees,\n} from './json-guarantees.ts'\nimport { workspacePackageManager } from './pinned.ts'\nimport type { Manifest } from './types.ts'\n\n/** What one target file turned out to be, as `sync` and `validate` say it. */\nexport interface TargetOutcome {\n /** Workspace-relative: `org/<repo>/.claude/settings.json`. */\n label: string\n status: 'updated' | 'unchanged' | 'stale' | 'invalid' | 'removed'\n /** What is missing (stale) or why the file is refused (invalid). */\n detail: string | null\n}\n\ntype OwnedFile = { file: string; label: string } & (\n { guarantees: readonly Guarantee[] } | { content: string } | { retired: true }\n)\n\n/** What a whole file lacks against what rness writes; null when equal. */\nfunction wholeDiff(existing: string | null, content: string): string | null {\n if (existing === content) return null\n return existing === null ? 'missing' : 'differs from what rness writes'\n}\n\n/**\n * What the targets' files depend on in this workspace (spec 0019 §5), `.rness`\n * where the targets themselves reach it.\n */\nasync function contextOf(root: string): Promise<TargetContext> {\n return {\n packageManager: await workspacePackageManager(join(root, '.rness')),\n }\n}\n\n/** Paths never depend on the context: enough to list them. */\nconst PATHS_ONLY: TargetContext = { packageManager: 'npm' }\n\n/**\n * Every file the given targets own a part of: the workspace root's first\n * (spec 0015 §2.1), then one per target and per repository of the catalogue\n * that is cloned under `org/`. The root of a clone only — a nested scope's\n * path to `.rness` is not verified (spec 0011 §5). Nothing where there is no\n * `org/`: a standalone checkout of `.rness` (its CI) has no workspace root of\n * its own, as `checkBlocks` has no block to check there.\n */\nasync function filesOf(\n root: string,\n manifest: Manifest,\n targets: readonly AgentTarget[]\n): Promise<OwnedFile[]> {\n const files: OwnedFile[] = []\n if (!(await exists(join(root, 'org')))) return files\n const ctx = await contextOf(root)\n for (const target of targets)\n for (const owned of target.files(ctx))\n if (owned.at === 'root')\n files.push({\n ...owned,\n file: join(root, ...owned.file.split('/')),\n label: owned.file,\n })\n for (const repo of Object.keys(manifest.repos)) {\n if (!(await exists(join(root, 'org', repo)))) continue\n for (const target of targets)\n for (const owned of target.files(ctx))\n if (owned.at === 'clones')\n files.push({\n ...owned,\n file: join(root, 'org', repo, ...owned.file.split('/')),\n label: `org/${repo}/${owned.file}`,\n })\n }\n return files\n}\n\nfunction declared(manifest: Manifest): AgentTarget[] {\n return (manifest.agents ?? []).flatMap((name) =>\n Object.hasOwn(TARGETS, name) ? [TARGETS[name] as AgentTarget] : []\n )\n}\n\n/** The files holding the generated block, in every clone. */\nexport const BLOCK_FILES: readonly string[] = ['AGENTS.md', 'CLAUDE.md']\n\n/**\n * Every file `sync` writes in a clone, relative to it: the block's, and the\n * declared agents' (spec 0011 §3.3). Not the workspace root's: it is in no\n * repository (spec 0015 §2.1).\n */\nexport function writtenFiles(manifest: Manifest): string[] {\n return [\n ...BLOCK_FILES,\n ...declared(manifest).flatMap((t) =>\n t\n .files(PATHS_ONLY)\n .filter((f) => f.at === 'clones')\n .map((f) => f.file)\n ),\n ]\n}\n\n/**\n * Compile the declared agents into every clone (spec 0011 §3.3), or with\n * `check` only say what is missing. Unsupported names are the caller's to\n * refuse; they are skipped here.\n */\nexport async function agentTargets(\n root: string,\n manifest: Manifest,\n opts: { check: boolean }\n): Promise<TargetOutcome[]> {\n const outcomes: TargetOutcome[] = []\n for (const owned of await filesOf(root, manifest, declared(manifest))) {\n const { file, label } = owned\n const existing = await readOrNull(file)\n if ('retired' in owned) {\n // A file rness wrote whole in an earlier release and no longer writes\n // (spec 0028 §7: the `done` skill). Absent: nothing to say. Present:\n // it would keep a retired command alive, so it goes, and its directory\n // with it when that leaves it empty.\n if (existing === null) continue\n if (opts.check) {\n outcomes.push({\n label,\n status: 'stale',\n detail: 'no longer written by rness; remove it',\n })\n continue\n }\n await rm(file)\n await rmdir(dirname(file)).catch(() => undefined)\n outcomes.push({ label, status: 'removed', detail: null })\n continue\n }\n if ('content' in owned) {\n // A whole file (spec 0016 §3.2): written when missing or different.\n const diff = wholeDiff(existing, owned.content)\n if (diff === null)\n outcomes.push({ label, status: 'unchanged', detail: null })\n else if (opts.check)\n outcomes.push({ label, status: 'stale', detail: diff })\n else {\n await mkdir(dirname(file), { recursive: true })\n await writeFileAtomic(file, owned.content)\n outcomes.push({ label, status: 'updated', detail: null })\n }\n continue\n }\n const { guarantees } = owned\n if (opts.check) {\n const missing = missingGuarantees(existing, guarantees)\n if ('invalid' in missing)\n outcomes.push({ label, status: 'invalid', detail: missing.invalid })\n else if (missing.length > 0)\n outcomes.push({\n label,\n status: 'stale',\n detail: missing.map(describeGuarantee).join('; '),\n })\n else outcomes.push({ label, status: 'unchanged', detail: null })\n continue\n }\n const ensured = ensureGuarantees(existing, guarantees)\n if (ensured.kind === 'invalid') {\n outcomes.push({ label, status: 'invalid', detail: ensured.reason })\n continue\n }\n if (ensured.kind === 'unchanged') {\n outcomes.push({ label, status: 'unchanged', detail: null })\n continue\n }\n await mkdir(dirname(file), { recursive: true })\n await writeFileAtomic(file, ensured.text)\n outcomes.push({ label, status: 'updated', detail: null })\n }\n return outcomes\n}\n\n/**\n * Files that still carry every value of a target the team no longer\n * declares, or its whole content. rness cannot tell its entries from the\n * team's, so it leaves them and says where they are (spec 0011 §3.4). Nothing when `agents` was never\n * set: a file written by hand is none of rness's business then.\n */\nexport async function leftoverTargets(\n root: string,\n manifest: Manifest\n): Promise<string[]> {\n if (manifest.agents === null) return []\n const agents = manifest.agents\n const undeclared = Object.values(TARGETS).filter(\n (t) => !agents.includes(t.name)\n )\n const leftovers: string[] = []\n for (const owned of await filesOf(root, manifest, undeclared)) {\n if ('retired' in owned) continue\n const existing = await readOrNull(owned.file)\n if (existing === null) continue\n if ('content' in owned) {\n if (existing === owned.content) leftovers.push(owned.label)\n continue\n }\n const missing = missingGuarantees(existing, owned.guarantees)\n if (!('invalid' in missing) && missing.length === 0)\n leftovers.push(owned.label)\n }\n return leftovers\n}\n","import { readFileSync, statSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport type { TargetContext, TargetFile } from './agents.ts'\nimport { PINNED_BIN } from './delegate.ts'\nimport { type PackageManager, localRunner } from './pm.ts'\n\n/** The Claude Code plugin rness writes, whole (spec 0016 §3, 0019 §2). */\nconst PLUGIN = '.claude/skills/rness'\n\n/**\n * The manifest also carries the agent-plugins.org `$schema` and the fields\n * it recommends (spec 0027 §5), so a scanner that looks for an Agent Plugins\n * manifest finds one; Claude Code 2.1.286 validates it without a remark.\n * No version: it would make every release rewrite the file.\n */\nconst PLUGIN_JSON = `${JSON.stringify(\n {\n $schema: 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json',\n name: 'rness',\n description:\n 'The rness workspace in Claude Code: /rness:status, /rness:adr, /rness:spec, /rness:plan.',\n author: { name: 'rness-dev', url: 'https://rness.dev' },\n homepage: 'https://rness.dev',\n repository: 'https://github.com/rness-dev/rness',\n license: 'MIT',\n keywords: [\n 'rness',\n 'agents',\n 'claude-code',\n 'adr',\n 'specification',\n 'plan',\n ],\n // The contract of the mod's `$.state` (spec 0029 §3.1).\n types: './types/index.d.ts',\n },\n null,\n 2\n)}\\n`\n\n/**\n * The `status` skill, `rness` being the path of `.rness` from the project\n * directory. One fixed command — the arguments never reach a shell — named\n * exactly in `allowed-tools`, so it runs without a prompt. Nothing in it\n * depends on the version; only its last line depends on the workspace's\n * package manager (spec 0019 §5), so an upgrade rewrites it only when that\n * text changes.\n */\nfunction statusSkill(rness: string, pm: PackageManager): string {\n const command = `node \"\\${CLAUDE_PROJECT_DIR}/${rness}/${PINNED_BIN}\" status --cwd \"\\${CLAUDE_PROJECT_DIR}\"`\n return `---\nname: status\ndescription: The status of every decision, specification, plan and other tracked document of the rness workspace, one table per directory. Read-only.\nargument-hint: '[tab]'\ndisable-model-invocation: true\nallowed-tools: Bash(${command})\n---\n\n!\\`${command}\\`\n\nShow the output above to the user as it is: the heading and the tables,\nnothing added, nothing summarised, no other tool. Arguments: \\`$ARGUMENTS\\`.\nWhen they name a tab, show only that tab's section. If the output says the\nmodule cannot be found, say instead that ${rness} is not installed next to\nthis repository.\n\nEnd with this line: _For the view with tabs and scrolling: here, Ctrl+Z,\nthen \\`npx @rness/cli status\\` (q to close), then \\`fg\\`; or in another\nterminal, from the workspace's \\`.rness/\\`: \\`${localRunner(pm)} rness status\\`._\n`\n}\n\n/**\n * A skill that walks the workspace's lifecycle (spec 0019 §3, the grammar of\n * spec 0028 §7): a procedure the developer or the model starts, the rules\n * left in `CONVENTIONS.md`.\n */\ninterface Lifecycle {\n name: string\n description: string\n hint: string\n /** The `status` tab it injects, and the collection `doc new` allocates in. */\n tab: 'adr' | 'specs' | 'plans'\n /** Its instructions, `.rness` reached at `rness`, `allocate` the fixed `doc new` line. */\n body: (rness: string, allocate: string) => string\n}\n\n/**\n * Who moves a status, and what gets committed: the same words in every\n * lifecycle skill. A status follows the work, whoever does it; accepting a\n * decision stays the developer's, and `/rness:plan from` is their word for\n * a specification (spec 0028 §8). A commit holds only what the agent alone\n * changed, so a teammate's work in progress is never swept in.\n */\nconst STATUS_RULE = `Move a status yourself when the work calls for it, and whenever the\ndeveloper says so: a plan \\`In progress\\` as you start its tasks,\n\\`Completed\\` once its proofs pass under \\`check\\`; a specification\n\\`Implemented\\` with its last plan; a document \\`Superseded\\` by the one that\nreplaces it. Accepting an ADR is the developer's; a specification is\n\\`Approved\\` by \\`/rness:plan from NNNN\\`, which is their word for it.`\n\nconst COMMIT_RULE = `Commit each file you changed, in its own repository, and only the files\nyou alone changed: add them by name, never \\`git add -A\\` nor \\`commit -a\\`.\nA file that had uncommitted changes before your first edit (\\`git status\\`\ntells you), or that someone else changed since, stays uncommitted: say\nwhich. Never push.`\n\n/** The session that writes a document, and its agent, recorded in it (spec 0020 §3.1, 0022 §3). */\nconst SESSION_LINE = `\\`{ id: \\${CLAUDE_SESSION_ID}, agent: <model> }\\` at the end of\n \\`sessions:\\` in the front matter, unless that id is already there;\n \\`<model>\\` is the model you run as, as Claude Code names it, after\n \\`Claude\\`: for example \\`Claude Opus 5.5\\``\n\n/**\n * How a new document gets its file (spec 0028 §9): the CLI allocates the\n * number, the skill names and fills the file. The command is fixed and\n * pre-approved; no argument of the developer's reaches a shell.\n */\nconst allocateStep = (allocate: string, collection: string): string =>\n `Allocate the file: run \\`${allocate}\\` from the project directory, where\n Claude Code was opened (pre-approved above as typed; \\`CLAUDE_PROJECT_DIR\\`\n is not set in your shell, so the path is relative). It writes\n \\`${collection}/NNNN-untitled.md\\` with the next number, the front matter\n and the opening sections, and prints the path. Rename it to\n \\`NNNN-<slug>.md\\`, the slug a few lowercase words of the title joined by\n hyphens, and write the title as \\`# NNNN — <title>\\`. Never choose the\n number yourself.`\n\nconst HOOK_LINE = (rness: string): string =>\n `The rness hook checks every edit under \\`${rness}/\\`: fix what it reports.`\n\nconst LIFECYCLE: readonly Lifecycle[] = [\n {\n name: 'adr',\n description:\n 'Record a decision of the rness workspace as an ADR in .rness/adr/ — a choice expensive to reverse or that creates a lasting constraint — or reopen one. Use when the developer asks for an ADR, or when the conversation reaches such a decision.',\n hint: '[create <subject> | open NNNN]',\n tab: 'adr',\n body: (\n rness,\n allocate\n ) => `You keep the decisions of this workspace: the ADRs in \\`${rness}/adr/\\`. The table\nabove lists the existing ones, newest first. Arguments: \\`$ARGUMENTS\\`.\n\nThe first word is the verb, when a reference (\\`0010\\`, or a path) follows\nit; a bare reference is \\`open\\`; any other words are the subject of a\n\\`create\\` (\\`open source licensing\\` is a subject):\n\n- \\`create [subject]\\`, or nothing: a new ADR, numbered by rness.\n- \\`open NNNN\\`: reopen ADR NNNN. An \\`Accepted\\` ADR is never edited: offer a\n new one that supersedes it. \\`Rejected\\` and \\`Superseded\\` are history too.\n\nCreating:\n\n1. If the developer did not ask for an ADR in so many words, propose one in\n a single line — its title, and why the choice is hard to reverse — and\n wait for a yes.\n2. Read \\`${rness}/CONVENTIONS.md\\` and \\`${rness}/adr/0000-template.md\\`: they hold the\n rules and the sections; this skill is only the procedure.\n3. The subject is the arguments, else the decision just discussed. Context,\n alternatives or consequences missing from the conversation: ask for\n them, one question at a time. Never invent them.\n4. ${allocateStep(allocate, 'adr')}\n5. Fill it: \\`repo\\` the repositories under \\`org/\\` it affects; the template's\n sections, their guidance lines removed; an ADR it replaces named in\n Context — that one becomes \\`Superseded\\`, with \\`superseded_by:\\`, only once\n the new ADR is \\`Accepted\\`. Add ${SESSION_LINE}.\n6. ${HOOK_LINE(rness)}\n\nOpening: read the ADR and amend what the developer asks, in place while it\nis \\`Proposed\\`; add the session line above. Nothing of the file's history is\nrewritten: a decision that changed is a new ADR.\n\nAfter writing: give the path and the Decision section. A new ADR stays\n\\`Proposed\\` until the developer accepts it.\n\n${STATUS_RULE}\n\n${COMMIT_RULE}\n`,\n },\n {\n name: 'spec',\n description:\n 'Write a specification of the rness workspace in .rness/specs/ — the outcome wanted and its scope, before any plan — or reopen one. Use when the developer asks for a spec, or when agreed work is too large to start without one.',\n hint: '[create <subject> | open NNNN]',\n tab: 'specs',\n body: (\n rness,\n allocate\n ) => `You keep the specifications of this workspace, in \\`${rness}/specs/\\`. The table\nabove lists the existing ones, newest first. Arguments: \\`$ARGUMENTS\\`.\n\nThe first word is the verb, when a reference (\\`0028\\`, or a path) follows\nit; a bare reference is \\`open\\`; any other words are the subject of a\n\\`create\\`:\n\n- \\`create [subject]\\`, or nothing: a new specification, numbered by rness.\n- \\`open NNNN\\`: reopen specification NNNN. One that is \\`Implemented\\`,\n \\`Superseded\\` or \\`Rejected\\` is not edited: offer a new one.\n\nCreating:\n\n1. If the developer did not ask for a specification in so many words,\n propose one in a single line and wait for a yes.\n2. Read \\`${rness}/CONVENTIONS.md\\`, then the most recent specification above: match\n its front matter, sections and tone.\n3. The subject is the arguments, else the work just discussed. The problem,\n what is in and out of scope, the ADRs it rests on: ask what the\n conversation does not say, one question at a time.\n4. ${allocateStep(allocate, 'specs')}\n5. Fill it: \\`repo\\`, and \\`adr:\\` linking the decisions it rests on — or the\n rationale in the body when none does; the sections it opened with\n (Summary, Scope, Out of scope, Alternatives considered, To verify,\n Tests), or the most recent specification's when the team's differ. What\n was checked in this session (a document read, a command run) is written\n as verified, with the date; everything else as a proposal or an open\n question. Add ${SESSION_LINE}.\n6. ${HOOK_LINE(rness)}\n\nOpening: read the specification and amend what the developer asks — a\nsection, a scope, an open question answered — \\`updated\\` today, the session\nline added. A status moves only as the developer says, or by\n\\`/rness:plan from\\`.\n\nAfter writing: give the path and the summary. A new specification starts\n\\`Draft\\`: \\`Proposed\\` for review; \\`/rness:plan from NNNN\\` approves it and\nplans it.\n\n${STATUS_RULE}\n\n${COMMIT_RULE}\n`,\n },\n {\n name: 'plan',\n description:\n 'The plans of the rness workspace in .rness/plans/ — a plan from a specification (from, which approves it), from the conversation (create), reopened (open), or closed on evidence (check). Use when the developer asks for a plan, to approve a specification, or to check the work of a plan.',\n hint: '[create <subject> | from <spec> | open NNNN | check NNNN]',\n tab: 'plans',\n body: (\n rness,\n allocate\n ) => `You keep the plans of this workspace, in \\`${rness}/plans/\\`. The table above\nlists the existing ones, newest first. Arguments: \\`$ARGUMENTS\\`.\n\nThe first word is the verb, when a reference (\\`0037\\`, or a path) follows\nit — \\`check\\` alone means the plan \\`In progress\\`; a bare reference is\n\\`open\\`; any other words are the subject of a \\`create\\`:\n\n- \\`from NNNN\\`: a plan from specification NNNN, which this approves.\n- \\`create [subject]\\`, or nothing: a plan from the conversation, for work\n too small for a specification; \\`spec:\\` is left empty.\n- \\`open NNNN\\`: reopen plan NNNN.\n- \\`check NNNN\\`: run the proofs of plan NNNN; close it when they all pass.\n\n\\`from\\`:\n\n1. Read the specification, \\`${rness}/CONVENTIONS.md\\`, and the most recent plan\n above: match its front matter and sections. A specification that is\n \\`Implemented\\`, \\`Superseded\\` or \\`Rejected\\` is refused: say its status,\n write nothing. A plan of it that is neither \\`Completed\\` nor \\`Abandoned\\`:\n reopen it rather than write a second.\n2. The developer typed this command: that is their approval, and the\n specification moves from \\`Draft\\` or \\`Proposed\\` to \\`Approved\\`, \\`updated\\`\n today, in the same commit as the plan — no confirmation question. If\n you are proposing it yourself, propose it in a single line and wait for\n a yes first: the approval is theirs, never yours.\n3. Read the code and the repositories the specification touches: every\n task names real files and real commands.\n4. ${allocateStep(allocate, 'plans')}\n5. Fill it: \\`spec:\\` linking the specification; tasks in order, as\n checkboxes, each with the files, what changes, and the command that\n proves it (a test, a build, a run) — the last tasks the documentation\n the work makes inaccurate, then the release when the repository has\n one; where the plan decides something the specification leaves open, the\n section it opened with says so. Add ${SESSION_LINE}.\n6. ${HOOK_LINE(rness)}\n\n\\`create\\`: as \\`from\\`, without a specification. If the developer did not ask\nfor a plan in so many words, propose one in a single line and wait for a\nyes. The body says what the work is and why it needs no specification.\n\n\\`open\\`: read the plan and its specification; amend what the developer\nasks — a task added, split or reworded, a blocker recorded — \\`updated\\`\ntoday, the session line added; move \\`Draft\\` to \\`Ready\\` or \\`Blocked\\` as they\nsay. A \\`Completed\\` or \\`Abandoned\\` plan is not reopened: offer a new plan of\nthe same specification.\n\n\\`check\\`:\n\n1. The plan: the one named, else the one \\`In progress\\`. Several or none:\n ask.\n2. The developer asked for the check, or the plan's last task has just\n passed in this session: run it. Otherwise propose it in a single line\n and wait for a yes.\n3. Read the plan, its specification and \\`${rness}/CONVENTIONS.md\\`.\n4. Evidence first. For each task, what proves it: its command run now, or\n its result read in this session. Never mark a task done on belief. A\n check has no cache: run twice, it proves twice.\n5. Every task proven:\n - the plan: \\`status: Completed\\`, \\`updated\\` today, the checkboxes of the\n proven tasks ticked, and a section \\`Verification (YYYY-MM-DD)\\` — what\n ran, what it showed, what could not run and why;\n - the specification: \\`Implemented\\` once every plan of it is\n \\`Completed\\`; \\`updated\\` today;\n - the plan and the specification: add ${SESSION_LINE};\n - the smallest set of documents the work makes inaccurate: \\`${rness}/docs/\\`,\n the READMEs of the repositories it changed.\n6. A task not proven: nothing moves, the plan stays \\`In progress\\`. Say,\n task by task, what passed and what remains. A blocker the developer\n names is a move of its own: \\`Blocked\\`, the blocker written in the plan.\n7. ${HOOK_LINE(rness)}\n\nAfter writing: give the path and the list of tasks, or the statuses moved.\nA new plan starts \\`Draft\\`, and becomes \\`Ready\\` once the developer agrees\nwith it or asks you to carry it out.\n\n${STATUS_RULE}\n\n${COMMIT_RULE}\n`,\n },\n]\n\n/** The skill rness wrote up to 0.17 and `/rness:plan check` replaced (spec 0028 §8). */\nconst RETIRED_SKILLS = ['done'] as const\n\n/**\n * One lifecycle skill. Its two commands are fixed — the arguments never\n * reach a shell — and named exactly in `allowed-tools`, so they run without\n * a prompt whoever invokes the skill: the status table it opens with, and\n * the allocation of a new document. No\n * `disable-model-invocation`: the model may propose it, and writes nothing\n * without a yes (spec 0019 §3.1).\n */\nfunction lifecycleSkill(rness: string, s: Lifecycle): string {\n const command = `node \"\\${CLAUDE_PROJECT_DIR}/${rness}/${PINNED_BIN}\" status ${s.tab} --cwd \"\\${CLAUDE_PROJECT_DIR}\"`\n // The second fixed line: the allocation of spec 0028 §9, no argument in\n // it. Typed by the model in its own shell, where Claude Code sets no\n // CLAUDE_PROJECT_DIR (verified 2026-10-02): the path is relative to the\n // project directory, as every path of this file is.\n const allocate = `node \"${rness}/${PINNED_BIN}\" doc new ${s.tab}`\n return `---\nname: ${s.name}\ndescription: ${s.description}\nargument-hint: '${s.hint}'\nallowed-tools: Bash(${command}), Bash(${allocate})\n---\n\n!\\`${command}\\`\n\n${s.body(rness, allocate)}`\n}\n\n/**\n * The mod's folder in the package (spec 0029 §3.1): from the sources\n * (`src/core/` → `../../mod`) and from the bundle (`dist/` → `../mod`), the\n * way `scaffoldDir` finds `scaffold/`.\n */\nfunction modDir(): string {\n let dir = dirname(fileURLToPath(import.meta.url))\n for (let i = 0; i < 4; i += 1) {\n const candidate = join(dir, 'mod')\n try {\n if (statSync(join(candidate, 'hooks', 'hooks.json')).isFile())\n return candidate\n } catch {\n // keep walking\n }\n dir = dirname(dir)\n }\n throw new Error('mod directory not found next to the @rness/cli package')\n}\n\n/** The mod's files `sync` writes, by their path in the plugin. */\nconst MOD_FILES = [\n 'hooks/hooks.json',\n 'hooks/register.tsx',\n 'types/index.d.ts',\n] as const\n\n/** The one line of the module that differs between places: where `.rness` is. */\nconst RNESS_LINE = \"const RNESS = '.rness'\"\n\nlet modSources: ReadonlyMap<string, string> | null = null\n\n/** The mod's files as shipped, read once. */\nfunction modSource(rel: (typeof MOD_FILES)[number]): string {\n if (modSources === null) {\n const dir = modDir()\n modSources = new Map(\n MOD_FILES.map((f) => [\n f,\n readFileSync(join(dir, ...f.split('/')), 'utf8'),\n ])\n )\n }\n return modSources.get(rel) ?? ''\n}\n\n/**\n * One file of the mod, `rness` being the path of `.rness` from the project\n * directory. The module runs the pinned copy at that one path, as the\n * settings hooks do: never one a clone's own tree could hold.\n */\nfunction modFile(rel: (typeof MOD_FILES)[number], rness: string): string {\n const text = modSource(rel)\n if (rel !== 'hooks/register.tsx') return text\n if (!text.includes(RNESS_LINE))\n throw new Error(`mod/hooks/register.tsx lacks ${RNESS_LINE}`)\n return text.replace(RNESS_LINE, `const RNESS = '${rness}'`)\n}\n\n/** The plugin's files, for a project directory reaching `.rness` at `rness`. */\nexport function pluginFiles(\n rness: string,\n at: TargetFile['at'],\n ctx: TargetContext\n): TargetFile[] {\n return [\n { file: `${PLUGIN}/.claude-plugin/plugin.json`, at, content: PLUGIN_JSON },\n {\n file: `${PLUGIN}/skills/status/SKILL.md`,\n at,\n content: statusSkill(rness, ctx.packageManager),\n },\n ...LIFECYCLE.map((s) => ({\n file: `${PLUGIN}/skills/${s.name}/SKILL.md`,\n at,\n content: lifecycleSkill(rness, s),\n })),\n // Read from disk when the content is asked for, never when only the\n // paths are: `upgrade` lists them after the install, and with pnpm the\n // install has removed the folder this copy runs from (0.20.0 → 0.20.1).\n ...MOD_FILES.map((rel) => ({\n file: `${PLUGIN}/${rel}`,\n at,\n get content() {\n return modFile(rel, rness)\n },\n })),\n ...RETIRED_SKILLS.map((name) => ({\n file: `${PLUGIN}/skills/${name}/SKILL.md`,\n at,\n retired: true as const,\n })),\n ]\n}\n","import { VERSION } from '../version.ts'\nimport { pluginFiles } from './claude-skills.ts'\nimport { PINNED_BIN } from './delegate.ts'\nimport type { PackageManager } from './pm.ts'\n\n/**\n * A value a target guarantees in a JSON file it shares with the team (spec\n * 0011 §3.4): the list at `path` contains `contains` — a string, or an object\n * compared deeply (spec 0015 §2.3) — or the key at `path` is present, set to\n * `value` when missing, never replaced (spec 0014 §3). rness owns the value,\n * never the file. `label` names an object entry in messages.\n */\nexport type Guarantee =\n | { path: readonly string[]; contains: unknown; label?: string }\n | { path: readonly string[]; value: unknown }\n\n/**\n * One file of a target: relative to the root of each clone, or to the\n * workspace root, once (spec 0015 §2.1). rness either guarantees values in\n * it — the team's file — or owns it whole, byte for byte (spec 0016 §3.2).\n */\nexport type TargetFile = {\n file: string\n at: 'clones' | 'root'\n} & (\n | { guarantees: readonly Guarantee[] }\n | { content: string }\n /** A file a former rness wrote whole and this one no longer does: removed when present. */\n | { retired: true }\n)\n\n/** What a target's files depend on in one workspace (spec 0019 §5). */\nexport interface TargetContext {\n /** The manager `.rness` installs with. */\n packageManager: PackageManager\n}\n\n/** What rness compiles for one agent, in each repository of the workspace. */\nexport interface AgentTarget {\n /** As `agents` in rness.json names it. */\n name: string\n /** As the question offers it. */\n label: string\n /** Its files in a workspace. Their paths never depend on the context. */\n files: (ctx: TargetContext) => readonly TargetFile[]\n}\n\nexport type HookEvent =\n 'session-start' | 'pre-tool-use' | 'post-tool-use' | 'session-end'\n\n/**\n * The line Claude Code runs for a hook (spec 0015 §2.2), `rness` being the\n * path of `.rness` from the project directory: the pinned copy when it is\n * installed; else, at session start, a line saying why the context is not\n * loaded — there is no rness to say it. Fixed across versions: the entry is\n * compared as a whole, so a changed line would be appended next to the old\n * one and run twice (§2.3). What the hook does changes in `rness hook`.\n */\nexport function hookLine(rness: string, event: HookEvent): string {\n const run = `f=\"$CLAUDE_PROJECT_DIR/${rness}/${PINNED_BIN}\"; if [ -f \"$f\" ]; then node \"$f\" hook ${event};`\n if (event !== 'session-start') return `${run} fi`\n const missing = JSON.stringify({\n systemMessage: `rness: ${rness} is not installed, so the workspace context is not loaded. Clone the workspace, then install its dependencies in .rness.`,\n })\n return `${run} else echo '${missing}'; fi`\n}\n\n/** The four hook entries, for a project directory reaching `.rness` at `rness`. */\nfunction hooks(rness: string): Guarantee[] {\n return [\n {\n path: ['hooks', 'SessionStart'],\n contains: {\n hooks: [\n {\n type: 'command',\n command: hookLine(rness, 'session-start'),\n timeout: 10,\n },\n ],\n },\n label: 'the rness session-start hook',\n },\n {\n // Before an edit: refused when it would change what sync generates,\n // or break the contract of .rness (spec 0029 §4).\n path: ['hooks', 'PreToolUse'],\n contains: {\n matcher: 'Edit|Write',\n hooks: [\n {\n type: 'command',\n command: hookLine(rness, 'pre-tool-use'),\n timeout: 10,\n },\n ],\n },\n label: 'the rness pre-tool-use hook',\n },\n {\n path: ['hooks', 'PostToolUse'],\n contains: {\n matcher: 'Edit|Write',\n hooks: [\n {\n type: 'command',\n command: hookLine(rness, 'post-tool-use'),\n timeout: 10,\n },\n ],\n },\n label: 'the rness post-tool-use hook',\n },\n {\n path: ['hooks', 'SessionEnd'],\n contains: {\n hooks: [\n {\n type: 'command',\n command: hookLine(rness, 'session-end'),\n timeout: 10,\n },\n ],\n },\n label: 'the rness session-end hook',\n },\n ]\n}\n\n/**\n * The agents this version can compile for (spec 0011 §4, tier 1). Any other\n * agent that reads `AGENTS.md` works with the block alone.\n */\nexport const TARGETS: Readonly<Record<string, AgentTarget>> = {\n claude: {\n name: 'claude',\n label: 'Claude Code',\n files: (ctx) => [\n {\n file: '.claude/settings.json',\n at: 'clones',\n guarantees: [\n // Read the context repository from a repository without a prompt.\n // Resolved against the project directory, and applied once Claude\n // Code has trusted it (verified on 2.1.284, spec 0011 §7).\n {\n path: ['permissions', 'additionalDirectories'],\n contains: '../../.rness',\n },\n ...hooks('../../.rness'),\n ],\n },\n {\n file: '.mcp.json',\n at: 'clones',\n guarantees: [\n // The pinned copy, by a path relative to the repository — the\n // directory Claude Code starts the server in (spec 0014 §6). Not\n // pre-approved in settings: each developer approves it once, since\n // a repository approving its own command would run any change to\n // it unasked (spec 0014 §3, 0.9.1).\n {\n path: ['mcpServers', 'rness'],\n value: {\n command: 'node',\n args: [\n '../../.rness/node_modules/@rness/cli/dist/bin/rness.js',\n 'mcp',\n ],\n },\n },\n ],\n },\n ...pluginFiles('../../.rness', 'clones', ctx),\n // A session opened at the workspace root reads this file, one opened\n // in a clone does not (spec 0011 §1): the hooks only, `.rness` inside.\n {\n file: '.claude/settings.json',\n at: 'root',\n guarantees: hooks('.rness'),\n },\n ...pluginFiles('.rness', 'root', ctx),\n ],\n },\n}\n\nexport const SUPPORTED_AGENTS: readonly string[] = Object.keys(TARGETS)\n\n/** The names this version has no target for, in their order. */\nexport function unsupportedAgents(names: readonly string[]): string[] {\n return names.filter((n) => !Object.hasOwn(TARGETS, n))\n}\n\nexport function unsupportedMessage(name: string): string {\n return `rness.json: agent \"${name}\" is not supported by @rness/cli ${VERSION} (supported: ${SUPPORTED_AGENTS.join(', ')})`\n}\n","import { isDeepStrictEqual } from 'node:util'\n\nimport type { Guarantee } from './agents.ts'\n\n/**\n * Guaranteed values in a JSON file rness shares with the team (spec 0011\n * §3.4): what is missing is added, nothing else is removed, rewritten or\n * reordered, and a file rness cannot read is never overwritten. Pure: text in,\n * text out.\n */\nexport type Ensured =\n | { kind: 'created' | 'updated' | 'unchanged'; text: string }\n | { kind: 'invalid'; reason: string }\n\ntype Json = Record<string, unknown>\ntype Parsed = { ok: true; data: Json } | { ok: false; reason: string }\n\nfunction isObject(value: unknown): value is Json {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction parse(text: string): Parsed {\n let data: unknown\n try {\n data = JSON.parse(text)\n } catch {\n return { ok: false, reason: 'not valid JSON' }\n }\n return isObject(data)\n ? { ok: true, data }\n : { ok: false, reason: 'not a JSON object' }\n}\n\n/**\n * Walk to the object holding `g`'s last key, creating the objects on the way\n * when `create`.\n */\nfunction parentOf(\n root: Json,\n g: Guarantee,\n create: boolean\n):\n | { kind: 'node'; node: Json }\n | { kind: 'absent' }\n | { kind: 'invalid'; reason: string } {\n let node = root\n for (const [i, key] of g.path.slice(0, -1).entries()) {\n const next = node[key]\n if (next === undefined) {\n if (!create) return { kind: 'absent' }\n node[key] = {}\n } else if (!isObject(next))\n return {\n kind: 'invalid',\n reason: `${g.path.slice(0, i + 1).join('.')} is not an object`,\n }\n node = node[key] as Json\n }\n return { kind: 'node', node }\n}\n\n/**\n * Whether `g` holds in `root` — and, with `create`, make it hold: an entry\n * appended to its list, or its key set when missing. `changed` says whether\n * anything was written; a key already present, whatever its value, holds.\n */\nfunction apply(\n root: Json,\n g: Guarantee,\n create: boolean\n): { holds: boolean; changed: boolean } | { invalid: string } {\n const found = parentOf(root, g, create)\n if (found.kind === 'absent') return { holds: false, changed: false }\n if (found.kind === 'invalid') return { invalid: found.reason }\n const parent = found.node\n const last = g.path[g.path.length - 1] ?? ''\n const value = parent[last]\n if ('value' in g) {\n if (value !== undefined) return { holds: true, changed: false }\n if (!create) return { holds: false, changed: false }\n parent[last] = structuredClone(g.value)\n return { holds: true, changed: true }\n }\n if (value === undefined) {\n if (!create) return { holds: false, changed: false }\n parent[last] = [structuredClone(g.contains)]\n return { holds: true, changed: true }\n }\n if (!Array.isArray(value))\n return { invalid: `${g.path.join('.')} is not a list` }\n if (value.some((entry) => isDeepStrictEqual(entry, g.contains)))\n return { holds: true, changed: false }\n if (!create) return { holds: false, changed: false }\n value.push(structuredClone(g.contains))\n return { holds: true, changed: true }\n}\n\n/** The text's own indentation, line ending and final newline, reused on output. */\nfunction styleOf(text: string): {\n indent: string\n eol: string\n final: boolean\n} {\n const indent = text\n .split(/\\r?\\n/)\n .slice(1)\n .map((l) => /^[ \\t]+/.exec(l)?.[0])\n .find((w) => w !== undefined)\n return {\n indent: indent ?? ' ',\n eol: text.includes('\\r\\n') ? '\\r\\n' : '\\n',\n final: text.endsWith('\\n'),\n }\n}\n\nexport function ensureGuarantees(\n existing: string | null,\n guarantees: readonly Guarantee[]\n): Ensured {\n const parsed: Parsed =\n existing === null ? { ok: true, data: {} } : parse(existing)\n if (!parsed.ok) return { kind: 'invalid', reason: parsed.reason }\n let changed = false\n for (const g of guarantees) {\n const r = apply(parsed.data, g, true)\n if ('invalid' in r) return { kind: 'invalid', reason: r.invalid }\n changed ||= r.changed\n }\n if (existing === null)\n return {\n kind: 'created',\n text: `${JSON.stringify(parsed.data, null, 2)}\\n`,\n }\n if (!changed) return { kind: 'unchanged', text: existing }\n const { indent, eol, final } = styleOf(existing)\n const body = JSON.stringify(parsed.data, null, indent).split('\\n').join(eol)\n return { kind: 'updated', text: final ? `${body}${eol}` : body }\n}\n\n/** What `ensureGuarantees` would add, or why it would refuse the file. */\nexport function missingGuarantees(\n existing: string | null,\n guarantees: readonly Guarantee[]\n): Guarantee[] | { invalid: string } {\n if (existing === null) return [...guarantees]\n const parsed = parse(existing)\n if (!parsed.ok) return { invalid: parsed.reason }\n const missing: Guarantee[] = []\n for (const g of guarantees) {\n const r = apply(parsed.data, g, false)\n if ('invalid' in r) return { invalid: r.invalid }\n if (!r.holds) missing.push(g)\n }\n return missing\n}\n\nexport function describeGuarantee(g: Guarantee): string {\n if ('value' in g) return `${g.path.join('.')} is missing`\n const what =\n g.label ??\n (typeof g.contains === 'string' ? g.contains : JSON.stringify(g.contains))\n return `${g.path.join('.')} lacks ${what}`\n}\n","import { execFile } from 'node:child_process'\nimport { readFile } from 'node:fs/promises'\nimport { basename, join } from 'node:path'\nimport { promisify } from 'node:util'\n\nimport { readPinnedCli } from './delegate.ts'\nimport { exists, writeFileAtomic } from './fs.ts'\nimport {\n type PackageManager,\n installDependencies,\n isPackageManager,\n rnessCommand,\n} from './pm.ts'\nimport { warn } from './style.ts'\nimport { agentHintLines } from './transport.ts'\nimport { findWorkspace } from './workspace.ts'\n\nconst execFileP = promisify(execFile)\n\nconst PACKAGE = '@rness/cli'\n\n/** A released version, pre-releases included; never a range or a tag. */\nexport const EXACT_VERSION = /^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$/\n\n/** Negative when `a` is the older version. A pre-release is older than its release. */\nexport function compareVersions(a: string, b: string): number {\n const split = (v: string): [number[], string | null] => {\n const dash = v.indexOf('-')\n const core = dash === -1 ? v : v.slice(0, dash)\n return [core.split('.').map(Number), dash === -1 ? null : v.slice(dash + 1)]\n }\n const [coreA, preA] = split(a)\n const [coreB, preB] = split(b)\n for (let i = 0; i < 3; i += 1) {\n const diff = (coreA[i] ?? 0) - (coreB[i] ?? 0)\n if (diff !== 0) return diff\n }\n if (preA === preB) return 0\n if (preA === null) return 1\n if (preB === null) return -1\n return preA.localeCompare(preB, 'en', { numeric: true })\n}\n\nexport interface Pin {\n /** What `package.json` says: an exact version in a workspace rness created. */\n spec: string\n field: 'devDependencies' | 'dependencies'\n}\n\nasync function readPackageJson(\n rnessDir: string\n): Promise<Record<string, unknown> | null> {\n try {\n const parsed: unknown = JSON.parse(\n await readFile(join(rnessDir, 'package.json'), 'utf8')\n )\n return parsed !== null && typeof parsed === 'object'\n ? (parsed as Record<string, unknown>)\n : null\n } catch {\n return null\n }\n}\n\n/** The `@rness/cli` entry of `.rness/package.json` — the one place the version is written (spec 0006). */\nexport async function readPin(rnessDir: string): Promise<Pin | null> {\n const pkg = await readPackageJson(rnessDir)\n if (pkg === null) return null\n for (const field of ['devDependencies', 'dependencies'] as const) {\n const deps = pkg[field]\n if (deps === null || typeof deps !== 'object') continue\n const spec = (deps as Record<string, unknown>)[PACKAGE]\n if (typeof spec === 'string') return { spec, field }\n }\n return null\n}\n\n/**\n * Replace the pinned version in place: every other byte of `package.json` —\n * its indentation, its inline objects, its key order — is the user's.\n */\nexport async function writePin(\n rnessDir: string,\n from: string,\n to: string\n): Promise<void> {\n const file = join(rnessDir, 'package.json')\n const text = await readFile(file, 'utf8')\n const entry = new RegExp(\n `(\"${PACKAGE}\"\\\\s*:\\\\s*\")${from.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}(\")`\n )\n if (!entry.test(text))\n throw new Error(`\"${PACKAGE}\": \"${from}\" not found in package.json`)\n await writeFileAtomic(file, text.replace(entry, `$1${to}$2`))\n}\n\nconst LOCKFILES: readonly (readonly [string, PackageManager])[] = [\n ['pnpm-lock.yaml', 'pnpm'],\n ['yarn.lock', 'yarn'],\n ['bun.lock', 'bun'],\n ['bun.lockb', 'bun'],\n ['package-lock.json', 'npm'],\n]\n\n/** The package manager a workspace installs with: `packageManager`, else its lockfile, else npm. */\nexport async function workspacePackageManager(\n rnessDir: string\n): Promise<PackageManager> {\n const declared = (await readPackageJson(rnessDir))?.['packageManager']\n if (typeof declared === 'string') {\n const name = declared.split('@')[0] ?? ''\n if (isPackageManager(name)) return name\n }\n for (const [lockfile, pm] of LOCKFILES)\n if (await exists(join(rnessDir, lockfile))) return pm\n return 'npm'\n}\n\n/**\n * Whether the workspace carries a lockfile **this** manager can install from.\n * A frozen install is per-manager: `npm ci` needs `package-lock.json` and\n * fails outright next to a `pnpm-lock.yaml`, which is the common case when the\n * manager running `create` is not the one the workspace declares.\n */\nexport async function hasLockfile(\n rnessDir: string,\n pm: PackageManager\n): Promise<boolean> {\n for (const [lockfile, owner] of LOCKFILES)\n if (owner === pm && (await exists(join(rnessDir, lockfile)))) return true\n return false\n}\n\n/**\n * An exact pin that is not the installed copy: someone pulled an upgrade and\n * did not reinstall, or never installed. Null when they agree, and when the\n * pin is a range — it says nothing precise about what should be installed.\n */\nexport async function pinDrift(\n rnessDir: string\n): Promise<{ pin: string; installed: string | null } | null> {\n const pin = await readPin(rnessDir)\n if (pin === null || !EXACT_VERSION.test(pin.spec)) return null\n const installed = (await readPinnedCli(rnessDir))?.version ?? null\n return installed === pin.spec ? null : { pin: pin.spec, installed }\n}\n\n/**\n * The line the launcher prints when the workspace around `cwd` pins one\n * version and holds another (spec 0006 §4): the teammate who pulled an\n * upgrade and did not reinstall. Null outside a workspace, and without drift.\n */\nexport async function driftWarning(cwd: string): Promise<string | null> {\n let root: string\n let rnessDir: string\n try {\n const ws = await findWorkspace(cwd)\n root = ws.root\n rnessDir = ws.rnessDir\n } catch {\n return null\n }\n const drift = await pinDrift(rnessDir)\n if (drift === null) return null\n const pm = await workspacePackageManager(rnessDir)\n return warn(\n `${basename(root)}/.rness pins @rness/cli ${drift.pin} but ${drift.installed ?? 'nothing'} is installed — run ${pm} install in .rness`\n )\n}\n\n/** A delegated child is killed after this long without finishing (spec 0008 §5). */\nexport const CHILD_DEADLINE_MS = 120_000\n\n/**\n * The environment of a delegated child. Its output is piped and the parent\n * owns the terminal, so a prompt from `ssh` or from git's credential helper is\n * invisible and blocks forever. `GIT_SSH_COMMAND` is composed, not replaced:\n * a user's own agent command (1Password, a named key) must survive.\n */\nexport function childEnv(\n env: NodeJS.ProcessEnv = process.env\n): NodeJS.ProcessEnv {\n return {\n ...env,\n GIT_SSH_COMMAND: `${env['GIT_SSH_COMMAND'] ?? 'ssh'} -o BatchMode=yes`,\n GIT_TERMINAL_PROMPT: '0',\n }\n}\n\nexport interface InstallOutcome {\n installed: boolean\n pin: string\n /** Why it did not install; null when it did. */\n reason: string | null\n}\n\nexport interface EnsureOptions {\n env?: NodeJS.ProcessEnv\n announce?: (pin: string) => void\n install?: (\n pm: PackageManager,\n dir: string,\n opts: { frozen: boolean }\n ) => Promise<void>\n}\n\n/**\n * Bring `.rness/node_modules` back to the pin (spec 0008 §4). The version was\n * decided by the pull request that moved the pin, so this asks nothing. Null\n * when there is no drift. A failure is reported, never thrown: the caller\n * falls back to the warning and runs the command anyway.\n */\nexport async function ensureInstalled(\n rnessDir: string,\n opts: EnsureOptions = {}\n): Promise<InstallOutcome | null> {\n const drift = await pinDrift(rnessDir)\n if (drift === null) return null\n const env = opts.env ?? process.env\n if (env['RNESS_NO_INSTALL'] === '1')\n return { installed: false, pin: drift.pin, reason: 'RNESS_NO_INSTALL=1' }\n const pm = await workspacePackageManager(rnessDir)\n const frozen = await hasLockfile(rnessDir, pm)\n const install = opts.install ?? installDependencies\n opts.announce?.(drift.pin)\n try {\n await install(pm, rnessDir, { frozen })\n return { installed: true, pin: drift.pin, reason: null }\n } catch (e) {\n return {\n installed: false,\n pin: drift.pin,\n reason: e instanceof Error ? e.message : String(e),\n }\n }\n}\n\nexport interface PinnedSyncResult {\n code: number\n stdout: string\n stderr: string\n}\n\n/** `sync --yes` through the installed copy, its output kept. Null when nothing is installed. */\nexport async function runPinnedSync(\n root: string\n): Promise<PinnedSyncResult | null> {\n const installed = await readPinnedCli(join(root, '.rness'))\n if (installed === null) return null\n const pinned = join(installed.dir, ...installed.bin.split('/'))\n if (!(await exists(pinned)))\n return {\n code: 1,\n stdout: '',\n stderr: `@rness/cli in .rness is not installed correctly (missing ${installed.bin}); reinstall in .rness/\\n`,\n }\n try {\n const { stdout, stderr } = await execFileP(\n process.execPath,\n [pinned, 'sync', '--yes'],\n {\n cwd: root,\n maxBuffer: 16 * 1024 * 1024,\n env: childEnv(),\n timeout: CHILD_DEADLINE_MS,\n killSignal: 'SIGKILL',\n }\n )\n return { code: 0, stdout, stderr }\n } catch (e) {\n const err = e as {\n code?: number\n killed?: boolean\n stdout?: string\n stderr?: string\n }\n const deadline =\n err.killed === true\n ? `rness sync in .rness did not finish within ${CHILD_DEADLINE_MS / 1000}s and was stopped\\n`\n : ''\n return {\n code: typeof err.code === 'number' ? err.code : 1,\n stdout: err.stdout ?? '',\n stderr: `${err.stderr ?? ''}${deadline}`,\n }\n }\n}\n\nconst SYNC_VERBS = ['updated', 'unchanged', 'stale'] as const\n\n/**\n * `3 blocks: 2 updated, 1 unchanged`, the verbs always in that order —\n * nothing after the count when none.\n */\nfunction counted(noun: string, counts: ReadonlyMap<string, number>): string {\n const total = [...counts.values()].reduce((a, b) => a + b, 0)\n const detail = SYNC_VERBS.filter((verb) => counts.has(verb))\n .map((verb) => `${counts.get(verb) ?? 0} ${verb}`)\n .join(', ')\n return `${total} ${noun}${total === 1 ? '' : 's'}${detail === '' ? '' : `: ${detail}`}`\n}\n\n/**\n * What a sync printed, in one line: `3 blocks: 2 updated, 1 unchanged`, then\n * the agent files when there are any — `; 2 agent files: 2 unchanged`. A\n * block is an `AGENTS.md` or a `CLAUDE.md`; any other file is an agent's\n * (spec 0011). The lines about neither (`not cloned: …`) are returned as\n * they are.\n */\nexport function summariseSync(stdout: string): {\n summary: string\n others: string[]\n} {\n const blocks = new Map<string, number>()\n const agentFiles = new Map<string, number>()\n const others: string[] = []\n for (const line of stdout.split('\\n')) {\n if (line.trim() === '') continue\n const m = /^(updated|unchanged|stale)\\s+(\\S+)/.exec(line)\n if (m === null) {\n others.push(line)\n continue\n }\n const [, verb = '', path = ''] = m\n const counts = /(^|\\/)(AGENTS|CLAUDE)\\.md$/.test(path) ? blocks : agentFiles\n counts.set(verb, (counts.get(verb) ?? 0) + 1)\n }\n return {\n summary: [\n counted('block', blocks),\n ...(agentFiles.size > 0 ? [counted('agent file', agentFiles)] : []),\n ].join('; '),\n others,\n }\n}\n\n/**\n * What the parent makes of a delegated sync (spec 0008 §2.1). A pinned copy\n * older than 0.5.0 clones catalogue repositories nobody picked and exits 1 when\n * one fails; it cannot be made to exit 0, so the blocks decide. One block line\n * on stdout means the sync did its job: what the child wrote to stderr is then\n * context, not the command's outcome.\n */\nexport function syncOutcome(\n result: PinnedSyncResult,\n opts: { sshWorks?: boolean } = {}\n): { code: number; hints: string[]; errors: string[] } {\n const { others } = summariseSync(result.stdout)\n const wrote = /^(updated|unchanged|stale)\\s/m.test(result.stdout)\n const stderr = result.stderr\n .split('\\n')\n .map((l) => l.trimEnd())\n .filter((l) => l.trim() !== '')\n const hints = wrote ? [...others, ...stderr] : others\n if (\n opts.sshWorks === true &&\n /Permission denied \\(publickey\\)/.test(result.stderr)\n )\n hints.push(...agentHintLines())\n return {\n code: wrote ? 0 : result.code,\n hints,\n errors: wrote ? [] : stderr,\n }\n}\n\n/**\n * Run `sync --yes` through the copy installed in `.rness/`. With nothing\n * installed, `fallback` runs instead (`create --skip-install`); without a\n * fallback that is an error, never the caller's own code standing in for the\n * pinned copy (spec 0003 §2.2).\n */\nexport async function syncPinned(\n root: string,\n shown: string,\n fallback?: () => Promise<number>\n): Promise<number> {\n const rnessDir = join(root, '.rness')\n const installed = await readPinnedCli(rnessDir)\n if (installed === null) {\n if (fallback !== undefined) return fallback()\n process.stderr.write(\n `@rness/cli is not installed in ${shown}/.rness; install in .rness/, then ${rnessCommand()} sync\\n`\n )\n return 1\n }\n const pinned = join(installed.dir, ...installed.bin.split('/'))\n if (!(await exists(pinned))) {\n process.stderr.write(\n `@rness/cli in ${shown}/.rness is not installed correctly (missing ${installed.bin}); reinstall in .rness/\\n`\n )\n return 1\n }\n try {\n const { stdout, stderr } = await execFileP(\n process.execPath,\n [pinned, 'sync', '--yes'],\n {\n cwd: root,\n maxBuffer: 16 * 1024 * 1024,\n env: childEnv(),\n timeout: CHILD_DEADLINE_MS,\n killSignal: 'SIGKILL',\n }\n )\n process.stdout.write(stdout)\n if (stderr !== '') process.stderr.write(stderr)\n return 0\n } catch (e) {\n const err = e as { code?: number; stdout?: string; stderr?: string }\n if (err.stdout !== undefined && err.stdout !== '')\n process.stdout.write(err.stdout)\n if (err.stderr !== undefined && err.stderr !== '')\n process.stderr.write(err.stderr)\n return typeof err.code === 'number' ? err.code : 1\n }\n}\n","import { TARGETS } from './agents.ts'\nimport type { Prompts } from './terminal.ts'\n\nexport const AGENTS_QUESTION = 'Which agents does your team use?'\n\n/**\n * The one question that fills `agents` in rness.json (spec 0011 §3.2): the\n * targets this version compiles, none required. [] is an answer — \"none, do\n * not ask again\"; null is a cancel.\n */\nexport async function askAgents(p: Prompts): Promise<string[] | null> {\n const answer = await p.multiselect<string>({\n message: AGENTS_QUESTION,\n options: Object.values(TARGETS).map((t) => ({\n value: t.name,\n label: t.label,\n })),\n required: false,\n })\n if (p.isCancel(answer)) return null\n return Array.isArray(answer) ? answer : []\n}\n","import { basename, join } from 'node:path'\n\nimport type { CommandDeps } from '../core/deps.ts'\nimport { exists } from '../core/fs.ts'\nimport {\n CONTEXT_REPO,\n loadManifest,\n parseRepoSpec,\n workspaceName,\n} from '../core/manifest.ts'\nimport type { GitCredentials } from '../core/provider.ts'\nimport { openGitProvider } from '../core/providers.ts'\nimport {\n type AddRepositoryResult,\n addRepository,\n workspaceDirs,\n} from '../core/repos.ts'\nimport { defaultTerminal } from '../core/terminal.ts'\nimport {\n CHECKING,\n defaultTransport,\n httpsFlagLine,\n isSshUrl,\n passphraseHint,\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 { 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 (\n manifest: Manifest,\n url: string\n ): Promise<GitCredentials | null> =>\n (provider ??=\n (await openGitProvider(manifest)) ?? undefined)?.credentialsFor(url) ??\n null\n const cwd = opts.cwd ?? process.cwd()\n if (opts.ssh === true && opts.https === true) {\n process.stderr.write('--ssh and --https cannot be combined\\n')\n return 2\n }\n try {\n const ws = await findWorkspace(cwd)\n const manifest = await loadManifest(ws.rnessDir)\n // The owner of a bare `<repo>`; a blank workspace has none (spec 0012).\n const org = manifest.org\n\n // The name is checked before anything else runs; the host comes later.\n let parsed: { name: string; url: string }\n try {\n parsed = parseRepoSpec(spec, org, transport.hosts.https)\n } catch (e) {\n process.stderr.write(`${e instanceof Error ? e.message : String(e)}\\n`)\n return 2\n }\n // The context repository holds the catalogue and is already cloned as\n // `<root>/.rness`. Adding it would put a second, diverging copy under\n // `org/`, list the catalogue inside itself, and give `.rness/AGENTS.md` a\n // generated member block next to the shared one (spec 0009). The name\n // decides, whatever organization it came from: every spelling lands on\n // the same directory and the same catalogue key.\n if (parsed.name === CONTEXT_REPO) {\n process.stderr.write(\n `${CONTEXT_REPO} is the workspace context, not a member repository — it is already cloned at ${basename(ws.root)}/${CONTEXT_REPO}\\n`\n )\n return 2\n }\n const interactive = opts.yes !== true\n const ownUi = deps.ui === undefined\n if (interactive && !terminal.isTty()) {\n process.stderr.write(\n 'rness add clones and writes files; pass --yes to run without a prompt\\n'\n )\n return 2\n }\n\n const ui: Ui =\n deps.ui ?? (interactive ? await makeUi(terminal) : { ...plainUi })\n if (ownUi)\n ui.intro(\n `Add ${parsed.name} to workspace ${workspaceName(manifest, ws.root)}`\n )\n // Only SSH can make git ask something on the terminal (a passphrase).\n if (opts.host !== undefined || opts.https === true) ui.gitIsSilent = true\n let host = opts.host\n if (host === undefined && opts.ssh === true) host = transport.hosts.ssh\n if (host === undefined && opts.https === true) host = transport.hosts.https\n if (host === undefined && FULL_URL.test(spec)) host = transport.hosts.https\n if (host === undefined) {\n const { access, unattended } = await testGithubSsh(\n transport,\n interactive,\n () => ui.line(...CHECKING)\n )\n if (unattended || !access.ok) ui.gitIsSilent = true\n else ui.hint(passphraseHint(), 'stderr')\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(manifest, 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 { statSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\n/**\n * Files shipped in `scaffold/`, POSIX-relative. `_gitignore` is renamed to\n * `.gitignore` when copied (npm would rename a packed `.gitignore`).\n */\nexport const SCAFFOLD_FILES: readonly string[] = [\n 'AGENTS.md',\n 'CONVENTIONS.md',\n 'README.md',\n 'WORKSPACE.md',\n 'rness.json',\n 'package.json',\n '_gitignore',\n '.githooks/pre-commit',\n '.github/workflows/validate.yml',\n '.github/dependabot.yml',\n 'pnpm-workspace.yaml',\n 'adr/0000-template.md',\n 'standards/.gitkeep',\n 'specs/.gitkeep',\n 'plans/.gitkeep',\n 'skills/.gitkeep',\n 'docs/.gitkeep',\n]\n\n/**\n * Absolute path of the shipped scaffold. Works from the sources\n * (`src/core/scaffold.ts` → `../../scaffold`) and from the bundle\n * (`dist/<chunk>.js` or `dist/index.js` → `../scaffold`): walk up from this\n * file until a directory containing `scaffold/rness.json` is the package root.\n */\nexport function scaffoldDir(): string {\n let dir = dirname(fileURLToPath(import.meta.url))\n for (let i = 0; i < 4; i += 1) {\n const candidate = join(dir, 'scaffold')\n try {\n if (statSync(join(candidate, 'rness.json')).isFile()) return candidate\n } catch {\n // keep walking\n }\n dir = dirname(dir)\n }\n throw new Error('scaffold directory not found next to the @rness/cli package')\n}\n","import { chmod, mkdir, readFile, stat, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\n\nimport { SCAFFOLD_FILES, scaffoldDir } from './scaffold.ts'\n\nexport interface ScaffoldTokens {\n version: string\n packageManager: string\n}\n\n/** One file a scaffold version writes into `.rness/`, as it lands there. */\nexport interface ScaffoldFile {\n /** POSIX, relative to `.rness/`. */\n path: string\n content: string\n executable: boolean\n}\n\n// The CI workflow reads the pinned version from package.json (spec 0006 §2).\nconst TOKENISED = new Set(['package.json'])\n\n/**\n * The files the scaffold in `source` writes, rendered: `_gitignore` as\n * `.gitignore`, the tokens of `package.json` filled. `rness.json` is the\n * team's catalogue, never part of it (spec 0013 §1).\n */\nexport async function renderScaffold(\n source: string,\n tokens: ScaffoldTokens\n): Promise<ScaffoldFile[]> {\n const files: ScaffoldFile[] = []\n for (const rel of SCAFFOLD_FILES) {\n if (rel === 'rness.json') continue\n const from = join(source, ...rel.split('/'))\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 files.push({\n path: rel === '_gitignore' ? '.gitignore' : rel,\n content,\n executable: ((await stat(from)).mode & 0o111) !== 0,\n })\n }\n return files\n}\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 for (const file of await renderScaffold(scaffoldDir(), tokens)) {\n const to = join(dest, ...file.path.split('/'))\n await mkdir(dirname(to), { recursive: true })\n await writeFile(to, file.content, 'utf8')\n if (file.executable) await chmod(to, 0o755)\n }\n}\n","import { mkdir, mkdtemp, rename, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join, relative, resolve } from 'node:path'\n\nimport { SUPPORTED_AGENTS, unsupportedAgents } from '../core/agents.ts'\nimport { checkAccess } from '../core/approval.ts'\nimport { askAgents } from '../core/ask-agents.ts'\nimport { BLANK, askProvider } from '../core/ask-provider.ts'\nimport type { CommandDeps } from '../core/deps.ts'\nimport { clone, publish } from '../core/git.ts'\nimport { githubProvider } from '../core/github-oauth-provider.ts'\nimport { MAX_PAGES, PER_PAGE } from '../core/github.ts'\nimport {\n NAME,\n ORG_NAME,\n isMemberRepo,\n loadManifest,\n parseRepoSpec,\n} from '../core/manifest.ts'\nimport {\n buildContext,\n commitContext,\n insideWorkspace,\n installContext,\n targetProblem,\n} from '../core/new-workspace.ts'\nimport { workspacePackageManager } from '../core/pinned.ts'\nimport {\n PACKAGE_MANAGERS,\n type PackageManager,\n detectPackageManager,\n isPackageManager,\n rnessCommand,\n} from '../core/pm.ts'\nimport type {\n GitCredentials,\n Organization,\n Provider,\n} from '../core/provider.ts'\nimport { PROVIDERS, isProviderName, openProvider } from '../core/providers.ts'\nimport { probeRemote, repoUrl } from '../core/remote.ts'\nimport { addRepository } from '../core/repos.ts'\nimport { PRIVATE_MARK, banner, count, 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 passphraseHint,\n sshWorkspaceLines,\n testGithubSsh,\n usingRest,\n usingSentence,\n} from '../core/transport.ts'\nimport type { Manifest, ProviderName } from '../core/types.ts'\nimport { type Ui, makeUi, plainUi } from '../core/ui.ts'\nimport { clonesIn } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\nimport { VERSION } from '../version.ts'\nimport {\n WORKSPACE_NAME,\n createBlank,\n workspaceNameError,\n} from './create-blank.ts'\nimport { loginCommand } from './login.ts'\nimport { syncCommand } from './sync.ts'\n\nexport interface CreateOptions {\n /** The GitHub organization, exact name (`github.com/<org>`); prompted for when absent. */\n org?: string\n /** Comma-separated repositories for the workspace (`<repo>` or `<owner>/<repo>`): catalogue entries are cloned, others added. */\n repos?: string\n pm?: string\n /** Force `git@github.com:` without the SSH test. */\n ssh?: boolean\n /** Force `https://github.com/` without the SSH test. */\n https?: boolean\n /** Internal: remote base; wins over both flags and skips the SSH test. */\n host?: string\n yes?: boolean\n skipInstall?: boolean\n /** Reserved; rejected. */\n template?: string\n /** A workspace with no GitHub organization (spec 0012). */\n blank?: boolean\n /** With `blank`: the workspace directory; prompted for when absent. */\n name?: string\n /** Where the organization lives (`github`, later `gitlab`, `atlassian`); asked when absent in a terminal, `github` otherwise. */\n provider?: string\n /** A new workspace's agents, declared in rness.json (spec 0011 §3.2). */\n agent?: string[]\n /** Internal (tests): directory to resolve from. */\n cwd?: string\n /** Internal (tests): GitHub REST API base. */\n githubApi?: string\n}\n\nexport type { Prompts }\n\n/** What create needs from the terminal; tests replace it with scripted answers. */\nexport type CreateDeps = Terminal\n\nfunction firstLine(text: string): string {\n return (\n text\n .split('\\n')\n .find((l) => l.trim() !== '')\n ?.trim() ?? 'unknown error'\n )\n}\n\nfunction splitSpecs(list: string): string[] {\n return list\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s !== '')\n}\n\n// A cancelled or declined prompt is the user's choice, not a failure: exit 0\n// so `npm create rness` does not wrap it in npm's error report.\nfunction cancelled(ui: Ui): number {\n ui.cancelled()\n return 0\n}\n\n/**\n * The repositories to offer: the organization's, listed from the GitHub API,\n * plus every catalogue repository the API did not return (a private one\n * listed anonymously). Catalogue repositories are pre-selected. A listing that\n * fails is a warning: the catalogue is still offered, and `rness add` adds\n * repositories later. `null` when the user cancels; `prompted` tells whether\n * the picker was shown at all.\n */\nasync function pickRepositories(input: {\n org: string\n provider: Provider\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 let listed: { name: string; private: boolean; archived: boolean }[] = []\n let failed = false\n // The plain look announces the listing; the session look spins on it.\n if (!ui.session) ui.line('listing', `${org} repositories…`)\n try {\n const listing = await ui.step(\n {\n doing: `listing ${org} repositories`,\n sentence: `Listing the repositories of ${org}`,\n quiet: true,\n },\n () => provider.listRepositories(org),\n // What the listing offers, not what GitHub returned: the count and the\n // list below it must agree (spec 0009).\n (l) => [\n 'listed',\n `${count(l.repositories.filter(isMemberRepo).length, ['repository', 'repositories'])} of ${org}`,\n ]\n )\n listed = listing.repositories\n if (listing.owner === 'user')\n ui.hint(\n `only public repositories of ${org} are listed; add private ones later with ${rnessCommand()} add <repo>`\n )\n else if (!provider.authenticated)\n ui.hint(\n `only public repositories are listed; ${rnessCommand()} login lists the private ones you can access`\n )\n if (listing.truncated)\n ui.hint(`listed the first ${MAX_PAGES * PER_PAGE} repositories of ${org}`)\n } catch (e) {\n failed = true\n ui.warn(firstLine(e instanceof Error ? e.message : String(e)))\n }\n const inCatalogue = (name: string): boolean =>\n Object.hasOwn(input.catalogue, name)\n // Every active repository of the organization is a candidate but its context\n // repository, which is already cloned as `<root>/.rness` and is not a member\n // of the workspace it defines (spec 0009). A name beginning with a dot is an\n // ordinary repository: `.github` carries an organization's profile, its\n // issue templates and its shared workflows, and a member works on it like\n // any other. Archived repositories stay out: GitHub makes them read-only, so\n // a block written into one could never be pushed back.\n // GitHub names are case-insensitive, so a name that differs from `NAME` only\n // by case is offered — and declared — in lowercase, as `rness add` would;\n // any other name is shown but cannot be picked yet.\n const byLabel = (a: { label: string }, b: { label: string }): number =>\n a.label.localeCompare(b.label, 'en', { sensitivity: 'base' })\n const candidates = listed.filter(isMemberRepo)\n // A private repository wears a padlock next to its name — visible on every\n // line, where a hint shows on the focused one only. A terminal that cannot\n // draw it falls back to the word, as a hint.\n const padlock = unicode()\n const hint = (isPrivate: boolean, catalogued: boolean): string | null =>\n [isPrivate && !padlock ? 'private' : null, catalogued ? 'in .rness' : null]\n .filter((h) => h !== null)\n .join(' · ') || null\n const declarable = candidates\n .filter((r) => NAME.test(r.name.toLowerCase()))\n .map((r) => {\n const value = r.name.toLowerCase()\n const h = hint(r.private, inCatalogue(value))\n const label = r.private && padlock ? `${r.name} ${PRIVATE_MARK}` : r.name\n return { value, label, ...(h === null ? {} : { hint: h }) }\n })\n const offered = new Set(declarable.map((o) => o.value))\n for (const name of Object.keys(input.catalogue)) {\n if (!offered.has(name))\n declarable.push({ value: name, label: name, hint: 'in .rness' })\n }\n declarable.sort(byLabel)\n const unsupported = candidates\n .filter((r) => !NAME.test(r.name.toLowerCase()))\n .map((r) => ({\n value: r.name,\n label: r.name,\n hint: 'name not supported yet',\n disabled: true,\n }))\n .sort(byLabel)\n // clack renders a disabled option struck through but never its hint, so\n // the reason is printed here.\n if (unsupported.length > 0) {\n const names = unsupported.slice(0, 5).map((o) => o.label)\n const more =\n unsupported.length > names.length\n ? ` and ${unsupported.length - names.length} more`\n : ''\n ui.hint(\n `names rness cannot declare yet (struck through): ${names.join(', ')}${more}`\n )\n }\n if (declarable.length === 0) {\n // After a failed listing its own warning already says why.\n if (!failed) ui.warn(`no repositories to list for ${org}`)\n return { picked: [], prompted: false }\n }\n const initialValues = Object.keys(input.catalogue)\n // Disabled options go last: clack focuses the first option before any key\n // is pressed, and Tab would select it even when it is disabled.\n const answer = await prompts.autocompleteMultiselect<string>({\n message: 'Which repositories do you want in your workspace?',\n options: [...declarable, ...unsupported],\n ...(initialValues.length > 0 ? { initialValues } : {}),\n required: false,\n placeholder: 'Type to filter',\n })\n if (prompts.isCancel(answer)) return null\n const allowed = new Set(declarable.map((o) => o.value))\n return {\n picked: Array.isArray(answer) ? answer.filter((v) => allowed.has(v)) : [],\n prompted: true,\n }\n}\n\ninterface Failure {\n spec: string\n message: string\n}\n\n/**\n * Bring each selected repository into `org/`, in order. A catalogue\n * repository is cloned from its catalogue URL and `rness.json` is left alone;\n * any other goes through `addRepository` (declared, then cloned), as\n * `rness add` would. A failure is reported on one line and the next entry\n * still runs: a typo in `--repos` must not cost the workspace the\n * repositories that do exist, nor the commit and sync that follow.\n */\nasync function cloneSelection(input: {\n root: string\n rnessDir: string\n manifest: Manifest\n org: string\n host: string\n specs: readonly string[]\n provider: Provider\n ui: Ui\n}): Promise<Failure[]> {\n const { ui } = input\n let manifest = input.manifest\n const failures: Failure[] = []\n for (const spec of new Set(input.specs)) {\n try {\n let name: string | null = null\n try {\n name = parseRepoSpec(spec, input.org, input.host).name\n } catch {\n // `addRepository` reports the malformed spec below.\n }\n const entry = name === null ? undefined : manifest.repos[name]\n if (name !== null && entry !== undefined) {\n const repo = name\n await ui.step(\n { doing: `cloning org/${repo}`, git: true },\n () =>\n clone(\n entry.url,\n join(input.root, 'org', repo),\n input.provider.credentialsFor(entry.url)\n ),\n () => ['cloned', `org/${repo}`]\n )\n continue\n }\n const current = manifest\n const result = await ui.step(\n { doing: `cloning ${spec}`, git: true },\n () =>\n addRepository({\n root: input.root,\n rnessDir: input.rnessDir,\n manifest: current,\n spec,\n org: input.org,\n host: input.host,\n scopes: [],\n credentialsFor: (url) => input.provider.credentialsFor(url),\n }),\n (r) => [r.action, `org/${r.name}`]\n )\n manifest = result.manifest\n ui.line('declared', `scope ${result.name} (org/${result.name})`)\n } catch (e) {\n const message = firstLine(e instanceof Error ? e.message : String(e))\n ui.error(`${spec}: ${message}`)\n failures.push({ spec, message })\n }\n }\n return failures\n}\n\n/**\n * Move the staged `.rness` clone into the workspace. A rename is atomic and\n * keeps the clone's origin; across filesystems (`EXDEV`: the temporary\n * directory on another volume) the context is cloned a second time instead.\n */\nasync function placeContext(\n staged: string,\n rnessDir: string,\n url: string,\n credentials: GitCredentials | null\n): Promise<void> {\n try {\n await rename(staged, rnessDir)\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'EXDEV') throw e\n await clone(url, rnessDir, credentials)\n }\n}\n\n/** The flags that name a GitHub workspace, which a blank one has none of. */\nfunction blankConflict(opts: CreateOptions): string | null {\n if (opts.org !== undefined) return '--org'\n if (opts.repos !== undefined) return '--repos'\n if (opts.ssh === true) return '--ssh'\n if (opts.https === true) return '--https'\n if (opts.host !== undefined) return '--host'\n if (opts.provider !== undefined) return '--provider'\n return null\n}\n\n/** Refuses a `--provider` value that names no provider, or one not yet available. */\nfunction providerFlagError(value: string): string | null {\n if (!isProviderName(value))\n return `unknown provider \"${value}\" (${Object.keys(PROVIDERS).join(', ')})`\n if (PROVIDERS[value].available) return null\n const available = Object.values(PROVIDERS)\n .filter((p) => p.available)\n .map((p) => p.name)\n return `provider \"${value}\" is not available yet (available: ${available.join(', ')})`\n}\n\nconst OTHER = Symbol('another organization')\nexport const OTHER_LABEL = 'an organization not listed here…'\n/** Why one may be missing: the list is the approved organizations of the login (plan 0037, task 1). */\nexport const OTHER_HINT = 'not a member, or it has not approved rness yet'\nexport const NOT_APPROVED = 'rness not approved'\n\n/**\n * Logged in, the organization is picked from the login's own and their\n * account rather than typed (spec 0028 §2). An organization the provider\n * does not let rness read wears the padlock of spec 0009's picker, with the\n * hint that tells it from a private repository. `OTHER` leads to the text\n * prompt — the organization of an outside collaborator, a public one the\n * user does not belong to, or a listing that failed — as does having\n * nothing to offer; null is a cancel.\n */\nasync function chooseOrganization(\n provider: Provider,\n prompts: Prompts\n): Promise<{ org: string; canGrant: boolean | null } | typeof OTHER | null> {\n if (!provider.authenticated) return OTHER\n let organizations: Organization[]\n let self: string | undefined\n try {\n self = (await provider.identity())?.login\n organizations = await provider.listOrganizations()\n } catch {\n return OTHER\n }\n if (organizations.length === 0 && self === undefined) return OTHER\n const padlock = unicode()\n const options: { value: string; label: string; hint?: string }[] =\n organizations.map((o) => ({\n value: o.login,\n label: !o.approved && padlock ? `${o.login} ${PRIVATE_MARK}` : o.login,\n ...(o.approved ? {} : { hint: NOT_APPROVED }),\n }))\n if (self !== undefined)\n options.push({ value: self, label: self, hint: 'your account' })\n options.push({ value: '', label: OTHER_LABEL, hint: OTHER_HINT })\n const answer = await prompts.select<string>({\n message: 'Which GitHub organization?',\n options,\n })\n if (prompts.isCancel(answer)) return null\n if (typeof answer !== 'string' || answer === '') return OTHER\n const picked = organizations.find((o) => o.login === answer)\n return { org: answer, canGrant: picked?.canGrant ?? null }\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: Provider\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 const clock = {\n ...(deps.open === undefined ? {} : { open: deps.open }),\n ...(deps.sleep === undefined ? {} : { sleep: deps.sleep }),\n ...(deps.now === undefined ? {} : { now: deps.now }),\n }\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<Provider> =>\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 const agentFlags = [...new Set(opts.agent ?? [])]\n const unknownAgent = unsupportedAgents(agentFlags)[0]\n if (unknownAgent !== undefined) {\n process.stderr.write(\n `unknown agent \"${unknownAgent}\" (supported: ${SUPPORTED_AGENTS.join(', ')})\\n`\n )\n return 2\n }\n if (opts.provider !== undefined) {\n const named = providerFlagError(opts.provider)\n if (named !== null) {\n process.stderr.write(`${named}\\n`)\n return 2\n }\n }\n if (opts.ssh === true && opts.https === true) {\n process.stderr.write('--ssh and --https cannot be combined\\n')\n return 2\n }\n if (opts.blank === true) {\n const clash = blankConflict(opts)\n if (clash !== null) {\n process.stderr.write(`--blank cannot be combined with ${clash}\\n`)\n return 2\n }\n if (opts.name !== undefined && !WORKSPACE_NAME.test(opts.name)) {\n process.stderr.write(`${workspaceNameError(opts.name)}\\n`)\n return 2\n }\n }\n // A malformed flag is refused before any question is asked about the rest.\n if (opts.org !== undefined && !ORG_NAME.test(opts.org)) {\n process.stderr.write(\n `organization name \"${opts.org}\" is not a valid GitHub organization name\\n`\n )\n return 2\n }\n let pm: PackageManager =\n opts.pm !== undefined && isPackageManager(opts.pm)\n ? opts.pm\n : detectPackageManager()\n const interactive = opts.yes !== true && terminal.isTty()\n // The plain look unless this is a wizard in a real terminal (spec 0007 §5b).\n const ui = interactive ? await makeUi(terminal) : { ...plainUi }\n // The SSH test runs at most once, and only when its answer is needed.\n let sshTest: SshTest | undefined\n const testSsh = async (): Promise<SshAccess> => {\n if (sshTest === undefined) {\n sshTest = await testGithubSsh(transport, interactive, () =>\n ui.line(...CHECKING)\n )\n // Unattended SSH never asks anything: git steps may animate.\n if (sshTest.unattended) ui.gitIsSilent = true\n else if (sshTest.access.ok) ui.hint(passphraseHint(), 'stderr')\n }\n return sshTest.access\n }\n // Whether this machine's SSH access to github.com was proved. A delegated\n // child that then fails on publickey is missing an agent, not a key\n // (spec 0008 §2.1).\n const sshWorks = (): boolean => sshTest?.access.ok === true\n const chooseHost = async (): Promise<string> => {\n // Only SSH can make git ask something on the terminal (a passphrase).\n if (opts.host !== undefined || opts.https === true) ui.gitIsSilent = true\n if (opts.host !== undefined) return opts.host\n if (opts.ssh === true) return transport.hosts.ssh\n if (opts.https === true) return transport.hosts.https\n const access = await testSsh()\n const github = access.ok ? null : await getProvider()\n const login = github?.authenticated\n ? (await github.identity())?.login\n : undefined\n ui.line('using', usingRest(access, login), usingSentence(access, login))\n if (!access.ok) ui.gitIsSilent = true\n return access.ok ? transport.hosts.ssh : transport.hosts.https\n }\n let loaded: Prompts | undefined\n const prompts = async (): Promise<Prompts> =>\n (loaded ??= await terminal.prompts())\n let staging: string | undefined\n // '' off a terminal, so scripts and tests see nothing of it.\n if (interactive) process.stdout.write(banner(VERSION))\n ui.intro('Create a workspace')\n try {\n // In a terminal, before the first question: no answer could fix it.\n if (interactive && (await insideWorkspace(cwd))) {\n process.stderr.write(\n 'already inside an rness workspace; create runs from outside one\\n'\n )\n return 1\n }\n\n // Where the organization lives, or nowhere: the blank workspace is the\n // last answer of the first question (spec 0028 §2). The flag, an\n // organization or repositories on the command line settle it unasked.\n let blank = opts.blank === true\n let chosenProvider: ProviderName = 'github'\n if (opts.provider !== undefined && isProviderName(opts.provider))\n chosenProvider = opts.provider\n else if (\n !blank &&\n interactive &&\n opts.org === undefined &&\n opts.repos === undefined\n ) {\n const answer = await askProvider(await prompts())\n if (typeof answer !== 'string') return cancelled(ui)\n if (answer === BLANK) blank = true\n else chosenProvider = answer\n }\n if (blank)\n return await createBlank({\n name: opts.name,\n agents: agentFlags,\n cwd,\n pm,\n interactive,\n mayWrite: opts.yes === true || terminal.isTty(),\n skipInstall: opts.skipInstall === true,\n ui,\n prompts,\n })\n\n let prompted = false\n let org = opts.org\n if (org === undefined && !interactive) {\n process.stderr.write('rness create needs --org <name> without a prompt\\n')\n return 2\n }\n // Anonymous, and about to list repositories: offer the login first — it is\n // what lists the private ones, and the user's organizations to pick from.\n if (\n interactive &&\n opts.repos === undefined &&\n !(await getProvider()).authenticated\n ) {\n const p = await prompts()\n const login = await p.confirm({\n message:\n 'Log in to GitHub to list your organizations and 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, ...clock }\n )\n if (code !== 0) return code\n provider = await githubProvider(opts.githubApi)\n }\n }\n // What the listing knew of the identity's role there (spec 0028 §3).\n let canGrant: boolean | null = null\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.org\n canGrant = chosen.canGrant\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 // Access to the organization before anything reads it (spec 0028 §3):\n // the probe below must see a private `.rness` through a token the\n // organization has approved, or it would start a second one.\n const outcome = await checkAccess({\n org,\n provider: await getProvider(),\n ui,\n interactive,\n prompts,\n canGrant,\n deps: clock,\n })\n if (outcome === 'cancelled') return cancelled(ui)\n\n const host = await chooseHost()\n const contextUrl = repoUrl(host, org, '.rness')\n let 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 // A join takes the organization's agents; declaring one is a change to\n // its rness.json, made from inside the workspace (spec 0011 §3.2).\n if (joining && agentFlags.length > 0) {\n process.stderr.write(\n `${org}/.rness exists: --agent only applies to a new workspace; after joining, run ${rnessCommand()} sync${agentFlags.map((a) => ` --agent ${a}`).join('')}\\n`\n )\n return 2\n }\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 = {\n contract: 1,\n provider: chosenProvider,\n org,\n agents: null,\n boards: null,\n repos: {},\n scopes: {},\n }\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 // The catalogue names the provider; the clone above had only GitHub.\n if (deps.provider === undefined)\n gitProvider = await openProvider(catalogue, {\n ...(opts.githubApi === undefined ? {} : { apiBase: opts.githubApi }),\n })\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 // A new workspace's agents: named, or asked with the other questions,\n // before the first write. They do not count as the confirmation.\n if (!joining) {\n if (agentFlags.length > 0) catalogue.agents = agentFlags\n else if (interactive) {\n const answer = await askAgents(await prompts())\n if (answer === null) return cancelled(ui)\n catalogue.agents = answer\n }\n }\n if (interactive && !prompted) {\n const p = await prompts()\n const ok = await p.confirm({\n message: `Create workspace ${org} in ./${shown}?`,\n })\n if (p.isCancel(ok) || ok !== true) return cancelled(ui)\n }\n\n const rnessDir = join(root, '.rness')\n const install = (): Promise<void> =>\n installContext({ ui, pm, rnessDir, skip: opts.skipInstall === true })\n\n if (joining) {\n await mkdir(root, { recursive: true })\n await placeContext(\n await staged(),\n rnessDir,\n contextUrl,\n gitProvider.credentialsFor(contextUrl)\n )\n ui.line('cloned', `${shown}/.rness (joined ${org})`)\n // The workspace declares the manager it installs with (`packageManager`,\n // else the lockfile it committed). Joining adopts it: installing with\n // the one that happened to launch `create` would drop a second lockfile\n // beside the committed one (spec 0009 §5). `--pm` still wins.\n if (opts.pm === undefined) pm = await workspacePackageManager(rnessDir)\n // The pin is the team's, in the repository just cloned. Joining aligns\n // on it and says nothing: moving an organization's version is a\n // maintainer's act, not something asked of whoever arrives\n // (spec 0008 §2).\n await install()\n await mkdir(join(root, 'org'), { recursive: true })\n const failures = await cloneSelection({\n root,\n rnessDir,\n manifest: catalogue,\n org,\n host,\n specs,\n provider: gitProvider,\n ui,\n })\n const code = await syncBlocks(\n ui,\n root,\n shown,\n () => syncCommand({ yes: true, cwd: root }),\n sshWorks()\n )\n if (code !== 0) return code\n // What is left to do, never what just scrolled past: the `cloned` lines\n // are right above (spec 0009 §6).\n const cloned = await clonesIn(root)\n const remaining = Object.keys(catalogue.repos).filter(\n (name) => !cloned.has(name)\n )\n const rness = rnessCommand()\n const next = [\n `cd ${shown}`,\n // The comment above its command, as the new-workspace note does: a\n // line that wraps in a narrow terminal is a line nobody reads.\n ...(remaining.length > 0\n ? [\n `# clone the catalogue repositories you did not pick: ${remaining.join(', ')}`,\n `${rness} sync --all`,\n ]\n : []),\n ...failures.map(\n (f) => `${rness} add ${f.spec} # failed: ${f.message}`\n ),\n ]\n if (ui.session) ui.note('Next steps', next)\n else process.stdout.write(`\\n${next.map((l) => ` ${l}`).join('\\n')}\\n`)\n ui.outro(`You joined ${org} — your workspace is in ${shown}/`)\n return failures.length > 0 ? 1 : 0\n }\n\n // Phase 1 — creating the workspace itself; a failure is rolled back. Past\n // it the workspace exists and is worth keeping, whatever a repository\n // does next.\n const built = await buildContext({\n ui,\n root,\n shown,\n manifest: catalogue,\n pm,\n skipInstall: opts.skipInstall === true,\n kind: 'new workspace',\n })\n if (!built) return 1\n\n // Phase 2 — the repositories. Nothing here is rolled back.\n await mkdir(join(root, 'org'), { recursive: true })\n const failures = await cloneSelection({\n root,\n rnessDir,\n manifest: catalogue,\n org,\n host,\n specs,\n provider: gitProvider,\n ui,\n })\n\n await commitContext({ ui, rnessDir, shown })\n\n const code = await syncBlocks(\n ui,\n root,\n shown,\n () => syncCommand({ yes: true, cwd: root }),\n sshWorks()\n )\n if (code !== 0) return code\n\n // Teammates join once <org>/.rness is on GitHub. Logged in, in a\n // terminal, rness offers to put it there; otherwise it says how, with\n // nothing but git (spec 0004 §3b).\n const name = org\n const published = interactive\n ? await publishContext({\n ui,\n prompts: await prompts(),\n provider: gitProvider,\n org: name,\n rnessDir,\n url: contextUrl,\n })\n : false\n if (published === null) return cancelled(ui)\n const rness = rnessCommand()\n const next = [\n `cd ${shown}/.rness`,\n // What was asked for and did not happen, as the command that retries\n // it — the workspace is complete otherwise.\n ...failures.map((f) => `${rness} add ${f.spec} # failed: ${f.message}`),\n ...(published\n ? []\n : [\n `# create the empty private repository ${org}/.rness on github.com, then:`,\n `git remote add origin ${contextUrl} && git push -u origin main`,\n // git first: everyone has it. The GitHub CLI second, for those\n // who do — it creates the repository and pushes in one step.\n '# or, with the GitHub CLI (gh) installed, in one step:',\n `gh repo create ${org}/.rness --private --source . --push`,\n ]),\n // How this command was launched (npm when rness was typed directly),\n // whatever --pm installed with.\n `# then, for every teammate: ${detectPackageManager()} create rness ${org}`,\n ]\n if (ui.session) {\n ui.note('Next steps', next)\n ui.outro(`Workspace for ${org} is ready in ${shown}/`)\n } else\n process.stdout.write(\n [\n '',\n `Workspace for \\`${org}\\` is ready in ${shown}/.`,\n '',\n 'Next:',\n ...next.map((line) => ` ${line}`),\n '',\n ].join('\\n')\n )\n return failures.length > 0 ? 1 : 0\n } catch (e) {\n return reportError(e)\n } finally {\n // The staged context is either moved into place or no longer needed.\n if (staging !== undefined)\n await rm(staging, { recursive: true, force: true }).catch(() => undefined)\n }\n}\n","import { canOpenBrowser, openInBrowser } from './browser.ts'\nimport { rnessCommand } from './pm.ts'\nimport type { OrganizationAccess, Provider } from './provider.ts'\nimport type { Prompts } from './terminal.ts'\nimport type { Ui } from './ui.ts'\n\n/** How often the membership is asked while the approval is awaited. */\nexport const APPROVAL_INTERVAL_MS = 5_000\n/** How long the wait lasts; the device flow's code lasts 15 minutes. */\nexport const APPROVAL_WAIT_MS = 10 * 60_000\n\nexport function approvalQuestion(org: string): string {\n return `Open github.com to approve rness for ${org} now?`\n}\n\n/** The clock and the browser, injected so a test drives the wait. */\nexport interface ApprovalDeps {\n open?: (url: string) => void\n sleep?: (ms: number) => Promise<void>\n now?: () => number\n}\n\n/** `cancelled` is the user's: nothing is written after it. */\nexport type AccessOutcome = OrganizationAccess | 'cancelled'\n\n/**\n * Access to the organization, before anything reads it (spec 0028 §3): a\n * member is said as whom; an organization that restricts OAuth apps and has\n * not approved rness is offered the approval page in the browser, and the\n * membership is polled until it answers or ten minutes pass. The order\n * matters: the probe of `<org>/.rness` and the listing come after, so a\n * private `.rness` is never read as absent through a token that cannot see\n * it yet.\n */\nexport async function checkAccess(input: {\n org: string\n provider: Provider\n ui: Ui\n interactive: boolean\n prompts: () => Promise<Prompts>\n /** The identity's role, when the listing knew it; null: the provider would not say. */\n canGrant: boolean | null\n deps?: ApprovalDeps\n}): Promise<AccessOutcome> {\n const { org, provider, ui } = input\n if (!provider.authenticated) return 'unknown'\n const login = (await provider.identity())?.login\n const as = login === undefined ? '' : ` (as ${login})`\n const member = (): void =>\n ui.line('member', `${org}${as}`, `You are a member of ${org}${as}`)\n const access = await provider.organizationAccess(org)\n if (access === 'member') {\n member()\n return access\n }\n if (access !== 'restricted') return access\n\n const url = provider.approvalUrl()\n ui.warn(\n `${org} has not approved rness, so its private repositories are hidden`\n )\n if (!input.interactive || url === null) {\n ui.hint(\n url === null\n ? `an owner of ${org} has to approve the app your token belongs to`\n : `an owner approves it at ${url}`,\n 'stderr'\n )\n return 'restricted'\n }\n const p = await input.prompts()\n const ok = await p.confirm({\n message: approvalQuestion(org),\n initialValue: true,\n })\n if (p.isCancel(ok)) return 'cancelled'\n if (ok !== true) {\n ui.hint(`approve it later: ${url}`, 'stderr')\n return 'restricted'\n }\n\n ui.line('open', url, `Open ${url} and approve rness for ${org}`)\n if (canOpenBrowser()) (input.deps?.open ?? openInBrowser)(url)\n const sleep =\n input.deps?.sleep ??\n ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))\n const now = input.deps?.now ?? Date.now\n // An owner approves it themself on the page; a member can only ask there,\n // and so can anyone whose role the provider would not say: waiting for an\n // owner is true of them all.\n const who = input.canGrant === true ? org : `an owner of ${org}`\n const waiting = `for ${who} to approve rness on github.com`\n if (!ui.session) ui.line('waiting', `${waiting}…`)\n // Ctrl+C while waiting is a cancel, as at any question: nothing written,\n // exit 0, not the 130 of a killed process. The session look's spinner\n // already treats it so; the plain look listens for the time of the wait.\n let interrupted = false\n let wake = (): void => undefined\n const interrupt = (): void => {\n interrupted = true\n wake()\n }\n if (!ui.session) process.once('SIGINT', interrupt)\n let outcome: OrganizationAccess | 'timeout' | 'cancelled'\n try {\n outcome = await ui.step(\n {\n doing: `waiting ${waiting}`,\n sentence: `Waiting ${waiting}`,\n quiet: true,\n },\n async (): Promise<OrganizationAccess | 'timeout' | 'cancelled'> => {\n const deadline = now() + APPROVAL_WAIT_MS\n for (;;) {\n await Promise.race([\n sleep(APPROVAL_INTERVAL_MS),\n new Promise<void>((resolve) => {\n wake = resolve\n }),\n ])\n if (interrupted) return 'cancelled'\n const again = await provider.organizationAccess(org)\n // `unknown` is a request that failed: asked again until the deadline.\n if (again === 'member' || again === 'not-member') return again\n if (now() >= deadline) return 'timeout'\n }\n },\n (r) => (r === 'member' ? ['member', `${org}${as}`] : null)\n )\n } finally {\n process.off('SIGINT', interrupt)\n }\n if (outcome === 'cancelled') return outcome\n if (outcome === 'member') {\n if (!ui.session) member()\n return outcome\n }\n if (outcome === 'not-member') return outcome\n ui.warn(\n `${org} still has not approved rness; its private repositories stay hidden this time`\n )\n // The run goes on and makes the workspace: what is missing afterwards is\n // its private repositories, which `add` brings in.\n ui.hint(\n `once an owner approves it, add its private repositories with ${rnessCommand()} add <repo>`,\n 'stderr'\n )\n return 'restricted'\n}\n","import { PROVIDERS } from './providers.ts'\nimport type { Prompts } from './terminal.ts'\nimport type { ProviderName } from './types.ts'\n\nexport const PROVIDER_QUESTION = 'Where does your organization live?'\n/** The answer that is no provider at all: the blank workspace of spec 0012. */\nexport const BLANK = 'blank'\nexport const BLANK_LABEL = 'No organization yet: a blank local workspace'\n\n/**\n * The first question of the wizard (spec 0028 §2): where the organization\n * lives, and the blank workspace as the answer \"nowhere\" (spec 0012 §1\n * folded in). The providers not yet implemented are listed, disabled, so\n * the choice is visibly a later one (spec 0017 §2.2); a cancel is the clack\n * symbol.\n */\nexport async function askProvider(\n p: Prompts\n): Promise<ProviderName | typeof BLANK | symbol> {\n return p.select<ProviderName | typeof BLANK>({\n message: PROVIDER_QUESTION,\n options: [\n ...Object.values(PROVIDERS).map((entry) => ({\n value: entry.name,\n label: entry.available ? entry.label : `${entry.label} (coming later)`,\n disabled: !entry.available,\n })),\n { value: BLANK, label: BLANK_LABEL, disabled: false },\n ],\n })\n}\n","import { mkdir, readdir, rm, stat } from 'node:fs/promises'\nimport { dirname, join, relative } from 'node:path'\n\nimport { reportError } from '../report.ts'\nimport { VERSION } from '../version.ts'\nimport { exists } from './fs.ts'\nimport { commitAll, init } from './git.ts'\nimport { writeManifest } from './manifest.ts'\nimport { hasLockfile } from './pinned.ts'\nimport {\n type PackageManager,\n installDependencies,\n packageManagerVersion,\n rnessCommand,\n} from './pm.ts'\nimport { copyScaffold } from './scaffold-copy.ts'\nimport { CREATE_SUBJECT, scaffoldMessage } from './scaffold-git.ts'\nimport type { Manifest } from './types.ts'\nimport type { Ui } from './ui.ts'\nimport { findWorkspace } from './workspace.ts'\n\n/**\n * The steps `create` takes to bring a workspace into being, shared by the\n * organization path and the blank one (spec 0012): where it may go, the\n * context scaffolded and installed, then committed.\n */\n\nexport async function isEmptyDir(dir: string): Promise<boolean> {\n return (await readdir(dir)).length === 0\n}\n\nexport async function insideWorkspace(dir: string): Promise<boolean> {\n try {\n await findWorkspace(dir)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Why `root` cannot receive a new workspace, as the one-line message the\n * guards print; `null` when it can. Both ends of the operation count: the\n * directory create runs in, and the parent of the target — either one inside\n * a workspace would nest a second `.rness` under the first.\n */\nexport async function targetProblem(\n cwd: string,\n root: string,\n pm: PackageManager\n): Promise<string | null> {\n const shown = relative(cwd, root) || '.'\n if ((await insideWorkspace(cwd)) || (await insideWorkspace(dirname(root))))\n return 'already inside an rness workspace; create runs from outside one'\n if (!(await exists(root))) return null\n if (await exists(join(root, '.rness', 'rness.json'))) {\n // A join whose install failed leaves exactly this: a context clone and\n // no dependencies. Re-running create cannot help — point at the install\n // that finishes the job instead of at `rness add`.\n if (!(await exists(join(root, '.rness', 'node_modules'))))\n return `${shown} holds an rness workspace whose dependencies are not installed; cd ${shown}/.rness && ${pm} install, then ${rnessCommand()} sync`\n return `${shown} already holds an rness workspace (.rness/); run ${rnessCommand()} add inside it to add repositories`\n }\n if (!(await stat(root)).isDirectory()) return `${shown} is not a directory`\n if (!(await isEmptyDir(root))) return `${shown} is not empty`\n return null\n}\n\n/** Install the dependencies of `.rness/`, or say how to when `skip`. */\nexport async function installContext(input: {\n ui: Ui\n pm: PackageManager\n rnessDir: string\n skip: boolean\n}): Promise<void> {\n const { ui, pm, rnessDir } = input\n if (input.skip) {\n // Naming the manager says what to run by hand — and, on a join, which\n // one the workspace declared (spec 0009 §5).\n ui.line('skipped', `install with ${pm} (--skip-install)`)\n return\n }\n // A joined workspace carries the lockfile its clone brought, so the\n // install is frozen and leaves the working tree clean (spec 0008 §2). A\n // new workspace has no lockfile yet and resolves freely.\n const frozen = await hasLockfile(rnessDir, pm)\n await ui.step(\n { doing: `installing dependencies with ${pm}` },\n () => installDependencies(pm, rnessDir, { frozen }),\n () => ['installed', `dependencies with ${pm}`]\n )\n}\n\n/**\n * Create `root` and a new `.rness/` in it: the scaffold, `manifest`, the\n * install. False when a step failed: the error is reported and everything\n * this call wrote is removed, so the retry the message asks for is not\n * refused.\n */\nexport async function buildContext(input: {\n ui: Ui\n root: string\n shown: string\n manifest: Manifest\n pm: PackageManager\n skipInstall: boolean\n /** What the `created` line calls it: `new workspace`, `blank workspace`. */\n kind: string\n}): Promise<boolean> {\n const { ui, root, shown, pm } = input\n const rnessDir = join(root, '.rness')\n // Resolved before anything touches the filesystem: a missing package\n // manager binary must not leave an empty `<shown>/` behind.\n const pmVersion = await packageManagerVersion(pm)\n await mkdir(root, { recursive: true })\n try {\n await copyScaffold(rnessDir, {\n version: VERSION,\n packageManager: `${pm}@${pmVersion}`,\n })\n await writeManifest(rnessDir, input.manifest)\n ui.line('created', `${shown}/.rness (${input.kind})`)\n await installContext({ ui, pm, rnessDir, skip: input.skipInstall })\n return true\n } catch (e) {\n // Report the cause before the consequence: the original error first,\n // then the rollback note. Everything under `rnessDir` was written by\n // this call, so removing it is safe; `root` goes too when it is left\n // empty (this call created it, or found it empty), or the retry the\n // message asks for would be refused with \"<shown> is not empty\". A\n // failing `rm` is swallowed rather than thrown, since it must never\n // mask the original error.\n reportError(e)\n await rm(rnessDir, { recursive: true, force: true }).catch(() => undefined)\n if (await isEmptyDir(root).catch(() => false))\n await rm(root, { recursive: true, force: true }).catch(() => undefined)\n process.stderr.write(\n `removed ${shown}/.rness after the failure; fix it and retry\\n`\n )\n return false\n }\n}\n\n/** Make `.rness/` a repository with one commit; a failure is a warning. */\nexport async function commitContext(input: {\n ui: Ui\n rnessDir: string\n shown: string\n}): Promise<void> {\n const { ui, rnessDir, shown } = input\n await init(rnessDir)\n try {\n // The first scaffold commit: the base of every later scaffold merge\n // (spec 0013 §1).\n await commitAll(rnessDir, scaffoldMessage(CREATE_SUBJECT, VERSION))\n ui.line('committed', `${shown}/.rness`)\n } catch (e) {\n ui.warn(\n `${e instanceof Error ? e.message : String(e)} — commit ${shown}/.rness yourself`\n )\n }\n}\n","import { execFile } from 'node:child_process'\nimport { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport { promisify } from 'node:util'\n\nimport type { ScaffoldFile } from './scaffold-copy.ts'\n\n/**\n * The scaffold as git history in `.rness/` (spec 0013): the commits in which\n * rness wrote the scaffold, found by their subject; the commit holding a\n * target version's scaffold, built on the last one; the three-way merge git\n * does from there.\n */\n\nconst execFileP = promisify(execFile)\n\nexport const CREATE_SUBJECT = 'chore: rness workspace context'\nconst SCAFFOLD_SUBJECT = /^chore: rness scaffold (\\S+)$/\nexport const SCAFFOLD_TRAILER = 'Rness-Scaffold'\n\ninterface Ran {\n code: number\n stdout: string\n stderr: string\n}\n\n/** git in `dir` only (no walking up), with extra environment; never throws. */\nasync function run(\n dir: string,\n args: readonly string[],\n env: Record<string, string> = {}\n): Promise<Ran> {\n try {\n const { stdout, stderr } = await execFileP('git', [...args], {\n cwd: dir,\n env: {\n ...process.env,\n ...env,\n GIT_TERMINAL_PROMPT: '0',\n GIT_CEILING_DIRECTORIES: dirname(resolve(dir)),\n },\n maxBuffer: 16 * 1024 * 1024,\n })\n return { code: 0, stdout, stderr }\n } catch (e) {\n const err = e as { code?: unknown; stdout?: string; stderr?: string }\n return {\n code: typeof err.code === 'number' ? err.code : 1,\n stdout: err.stdout ?? '',\n stderr: err.stderr ?? String(e),\n }\n }\n}\n\nasync function must(\n dir: string,\n args: readonly string[],\n env: Record<string, string> = {}\n): Promise<string> {\n const r = await run(dir, args, env)\n if (r.code !== 0) {\n const first =\n r.stderr.split('\\n').find((l) => l.trim() !== '') ?? 'unknown error'\n throw new Error(`git ${args[0] ?? ''} failed: ${first.trim()}`)\n }\n return r.stdout.trim()\n}\n\n/** The message of a scaffold commit: its subject names the version. */\nexport function scaffoldMessage(subject: string, version: string): string {\n return `${subject}\\n\\n${SCAFFOLD_TRAILER}: ${version}`\n}\n\n/**\n * Commit everything in `rnessDir` — the end of an upgrade, which found it\n * clean (spec 0013 §8). The hooks run: a refusal hands back what they said,\n * and leaves everything staged. Nothing to commit and no merge: `nothing`.\n */\nexport async function commitUpgrade(\n rnessDir: string,\n message: string\n): Promise<\n { kind: 'committed' | 'nothing' } | { kind: 'refused'; output: string }\n> {\n const add = await run(rnessDir, ['add', '-A'])\n if (add.code !== 0) return { kind: 'refused', output: add.stderr.trim() }\n const staged = await run(rnessDir, ['diff', '--cached', '--quiet'])\n if (staged.code === 0 && !(await mergeInProgress(rnessDir)))\n return { kind: 'nothing' }\n const commit = await run(rnessDir, ['commit', '-q', '-m', message])\n if (commit.code !== 0)\n return {\n kind: 'refused',\n output: `${commit.stdout}\\n${commit.stderr}`.trim(),\n }\n return { kind: 'committed' }\n}\n\n/** Whether a merge waits for its commit in `dir` (`MERGE_HEAD` exists). */\nexport async function mergeInProgress(dir: string): Promise<boolean> {\n const r = await run(dir, ['rev-parse', '-q', '--verify', 'MERGE_HEAD'])\n return r.code === 0\n}\n\n/**\n * The last commit in which rness wrote the scaffold (spec 0013 §1): the most\n * recent `chore: rness scaffold <v>`, else a root `chore: rness workspace\n * context`. The subject decides: a squash carries the trailer in its body\n * but mixes the team's edits in. Null when there is none — adoption.\n */\nexport async function findScaffoldBase(\n rnessDir: string\n): Promise<{ commit: string; version: string | null } | null> {\n // Topological order: a child before its parent, whatever the commit dates\n // (two commits in the same second otherwise come in either order). A merge\n // in progress counts: the commit recording it runs the pre-commit hook\n // before it exists (spec 0013 §8).\n const merging = await mergeInProgress(rnessDir)\n const log = await run(rnessDir, [\n 'log',\n '--topo-order',\n `--format=%H%x1f%P%x1f%s%x1f%(trailers:key=${SCAFFOLD_TRAILER},valueonly,separator=%x2C)%x1e`,\n 'HEAD',\n ...(merging ? ['MERGE_HEAD'] : []),\n ])\n if (log.code !== 0) return null\n const commits = log.stdout\n .split('\\x1e')\n .map((r) => r.trim())\n .filter((r) => r !== '')\n .map((r) => {\n const [hash = '', parents = '', subject = '', trailer = ''] =\n r.split('\\x1f')\n return { hash, parents: parents.trim(), subject, trailer: trailer.trim() }\n })\n for (const c of commits) {\n const m = SCAFFOLD_SUBJECT.exec(c.subject)\n if (m !== null) return { commit: c.hash, version: m[1] ?? null }\n }\n const root = commits.find(\n (c) => c.parents === '' && c.subject === CREATE_SUBJECT\n )\n if (root === undefined) return null\n return {\n commit: root.hash,\n version: root.trailer === '' ? null : root.trailer,\n }\n}\n\n/**\n * The commit holding `version`'s scaffold: the base's tree with `files`\n * written over it, the base as parent (none on adoption). Built with a\n * temporary index — the working tree and the real index are untouched.\n */\nexport async function buildScaffoldCommit(\n rnessDir: string,\n base: string | null,\n files: readonly ScaffoldFile[],\n version: string\n): Promise<string> {\n const scratch = await mkdtemp(join(tmpdir(), 'rness-scaffold-'))\n const env = { GIT_INDEX_FILE: join(scratch, 'index') }\n try {\n await must(\n rnessDir,\n ['read-tree', ...(base === null ? ['--empty'] : [base])],\n env\n )\n for (const [i, file] of files.entries()) {\n const tmp = join(scratch, `blob-${i}`)\n await writeFile(tmp, file.content, 'utf8')\n const blob = await must(rnessDir, [\n 'hash-object',\n '-w',\n '--no-filters',\n '--',\n tmp,\n ])\n await must(\n rnessDir,\n [\n 'update-index',\n '--add',\n '--cacheinfo',\n `${file.executable ? '100755' : '100644'},${blob},${file.path}`,\n ],\n env\n )\n }\n const tree = await must(rnessDir, ['write-tree'], env)\n return await must(rnessDir, [\n 'commit-tree',\n tree,\n ...(base === null ? [] : ['-p', base]),\n '-m',\n scaffoldMessage(`chore: rness scaffold ${version}`, version),\n ])\n } finally {\n await rm(scratch, { recursive: true, force: true })\n }\n}\n\nexport type ScaffoldChange = 'added' | 'updated' | 'merged' | 'removed'\n\nasync function blobAt(\n rnessDir: string,\n rev: string,\n path: string\n): Promise<string | null> {\n const r = await run(rnessDir, [\n 'rev-parse',\n '--verify',\n '--quiet',\n `${rev}:${path}`,\n ])\n return r.code === 0 ? r.stdout.trim() : null\n}\n\n/**\n * `git merge --no-commit` of a scaffold commit: what changed, and what\n * conflicts. `updated` is a file the team never touched since `base`,\n * `merged` one it had edited; without a base, histories are unrelated.\n */\nexport async function mergeScaffold(\n rnessDir: string,\n commit: string,\n base: string | null\n): Promise<{ conflicts: string[]; changes: Array<[ScaffoldChange, string]> }> {\n await run(rnessDir, [\n 'merge',\n '--no-commit',\n '--no-ff',\n ...(base === null ? ['--allow-unrelated-histories'] : []),\n commit,\n ])\n const conflicts = (\n await must(rnessDir, ['diff', '--name-only', '--diff-filter=U'])\n )\n .split('\\n')\n .filter((l) => l !== '')\n const changes: Array<[ScaffoldChange, string]> = []\n const status = await must(rnessDir, [\n 'diff',\n '--cached',\n '--name-status',\n 'HEAD',\n ])\n for (const line of status.split('\\n')) {\n const [letter = '', path = ''] = line.split('\\t')\n if (path === '' || conflicts.includes(path)) continue\n if (letter === 'A') changes.push(['added', path])\n else if (letter === 'D') changes.push(['removed', path])\n else if (letter === 'M') {\n const untouched =\n base !== null &&\n (await blobAt(rnessDir, 'HEAD', path)) ===\n (await blobAt(rnessDir, base, path))\n changes.push([untouched ? 'updated' : 'merged', path])\n }\n }\n return { conflicts, changes }\n}\n\n/** A one-commit checkout (CI): the history to read is not there. */\nexport async function isShallow(rnessDir: string): Promise<boolean> {\n const r = await run(rnessDir, ['rev-parse', '--is-shallow-repository'])\n return r.code === 0 && r.stdout.trim() === 'true'\n}\n\n/** Whether `rnessDir` is itself a git repository (not merely inside one). */\nexport async function isRepository(rnessDir: string): Promise<boolean> {\n const r = await run(rnessDir, ['rev-parse', '--show-toplevel'])\n if (r.code !== 0) return false\n // Real paths on both sides: /tmp is a link to /private/tmp on macOS.\n const real = (p: string) => realpath(p).catch(() => resolve(p))\n return (await real(r.stdout.trim())) === (await real(rnessDir))\n}\n\n/**\n * Adoption only: `<dir>/.gitkeep` holds a directory open until it has files.\n * Where `HEAD` already tracks something in that directory, the scaffold\n * commit leaves it out, so the merge does not add a placeholder the team\n * never needed.\n */\nexport async function withoutRedundantKeeps(\n rnessDir: string,\n files: readonly ScaffoldFile[]\n): Promise<ScaffoldFile[]> {\n const kept: ScaffoldFile[] = []\n for (const file of files) {\n if (file.path.endsWith('/.gitkeep')) {\n const dir = file.path.slice(0, -'/.gitkeep'.length)\n const listed = await run(rnessDir, [\n 'ls-tree',\n '--name-only',\n 'HEAD',\n '--',\n `${dir}/`,\n ])\n if (listed.code === 0 && listed.stdout.trim() !== '') continue\n }\n kept.push(file)\n }\n return kept\n}\n","import {\n runPinnedSync,\n summariseSync,\n syncOutcome,\n syncPinned,\n} from './pinned.ts'\nimport { rnessCommand } from './pm.ts'\nimport type { Ui } from './ui.ts'\n\n/**\n * `sync --yes` through the copy installed in `.rness/` (spec 0003 §2.2), said\n * the way `ui` speaks. The plain look passes the child's lines through, as it\n * always did. The session look keeps them to itself and says them in one —\n * `Synced 3 blocks: 2 updated, 1 unchanged` — since the child, whose stdout\n * is a pipe, can only print the plain look. `inPlace` runs when nothing is\n * installed (`create --skip-install`), or when delegation is off.\n */\nexport async function syncBlocks(\n ui: Ui,\n root: string,\n shown: string,\n inPlace?: () => Promise<number>,\n sshWorks?: boolean\n): Promise<number> {\n // Delegation off (`rness-dev`, `RNESS_NO_DELEGATE=1`): the sources under\n // test write the blocks, not the published copy the install just pinned.\n if (process.env['RNESS_NO_DELEGATE'] === '1' && inPlace !== undefined)\n return inPlace()\n if (!ui.session)\n return ui.step({ doing: 'syncing the blocks', git: true }, () =>\n syncPinned(root, shown, inPlace)\n )\n const result = await ui.step(\n {\n doing: 'syncing the blocks',\n sentence: 'Writing the rness block into every AGENTS.md',\n },\n () => runPinnedSync(root),\n (r) =>\n r === null || r.code !== 0\n ? null\n : (() => {\n const { summary } = summariseSync(r.stdout)\n return ['synced', summary, `Synced ${summary}`] as const\n })()\n )\n if (result === null) {\n if (inPlace !== undefined) return inPlace()\n ui.error(\n `@rness/cli is not installed in ${shown}/.rness; install in .rness/, then ${rnessCommand()} sync`\n )\n return 1\n }\n const outcome = syncOutcome(result, { sshWorks: sshWorks === true })\n for (const line of outcome.hints) ui.hint(line)\n for (const line of outcome.errors) ui.error(line)\n return outcome.code\n}\n","import { mkdir } from 'node:fs/promises'\nimport { join, relative, resolve } from 'node:path'\n\nimport { askAgents } from '../core/ask-agents.ts'\nimport {\n buildContext,\n commitContext,\n targetProblem,\n} from '../core/new-workspace.ts'\nimport { type PackageManager, rnessCommand } from '../core/pm.ts'\nimport { syncBlocks } from '../core/sync-blocks.ts'\nimport type { Prompts } from '../core/terminal.ts'\nimport type { Ui } from '../core/ui.ts'\nimport { syncCommand } from './sync.ts'\n\n/**\n * A blank workspace's directory name: one path segment of letters, digits,\n * `.`, `_` and `-`, not `.` or `..`, no leading `-`. Case is kept: it names a\n * local directory, not a GitHub account.\n */\nexport const WORKSPACE_NAME = /^(?!\\.{1,2}$)[A-Za-z0-9._][A-Za-z0-9._-]*$/\n\nexport function workspaceNameError(name: string): string {\n return `workspace name \"${name}\" may only contain letters, digits, '.', '_' and '-', not starting with '-'`\n}\n\n/**\n * `rness create --blank`: a workspace with no GitHub organization\n * (spec 0012) — `.rness/` scaffolded with a `rness.json` without `org`, an\n * empty `org/`, the root `AGENTS.md` and `CLAUDE.md`. No login, SSH test,\n * probe or listing: the install of `.rness/` is the only network access.\n * Every prompt comes before the first write.\n */\nexport async function createBlank(input: {\n /** Already checked against `WORKSPACE_NAME`; prompted for when absent. */\n name: string | undefined\n /** `--agent`, already checked; asked for in the wizard when empty. */\n agents: readonly string[]\n cwd: string\n pm: PackageManager\n /** A wizard in a terminal: questions may be asked. */\n interactive: boolean\n /** `--yes`, or a terminal: allowed to write. */\n mayWrite: boolean\n skipInstall: boolean\n ui: Ui\n prompts: () => Promise<Prompts>\n}): Promise<number> {\n const { cwd, pm, ui } = input\n let name = input.name\n let prompted = false\n if (name === undefined) {\n if (!input.interactive) {\n process.stderr.write(\n 'rness create --blank needs a <name> without a prompt\\n'\n )\n return 2\n }\n const p = await input.prompts()\n const answer = await p.text({\n message: 'What should the workspace be called?',\n placeholder: 'my-workspace',\n validate: (value) => {\n const v = value?.trim() ?? ''\n return WORKSPACE_NAME.test(v) ? undefined : workspaceNameError(v)\n },\n })\n if (p.isCancel(answer) || typeof answer !== 'string') {\n ui.cancelled()\n return 0\n }\n name = answer.trim()\n prompted = true\n }\n\n const root = resolve(cwd, name)\n const shown = relative(cwd, root) || '.'\n const problem = await targetProblem(cwd, root, pm)\n if (problem !== null) {\n process.stderr.write(`${problem}\\n`)\n return 1\n }\n if (!input.mayWrite) {\n process.stderr.write(\n 'rness create writes files; pass --yes to run without a prompt\\n'\n )\n return 2\n }\n // The team's agents, before the first write (spec 0011 §3.2). The question\n // does not count as the confirmation.\n let agents: string[] | null =\n input.agents.length > 0 ? [...input.agents] : null\n if (agents === null && input.interactive) {\n agents = await askAgents(await input.prompts())\n if (agents === null) {\n ui.cancelled()\n return 0\n }\n }\n if (input.interactive && !prompted) {\n const p = await input.prompts()\n const ok = await p.confirm({\n message: `Create blank workspace ${name} in ./${shown}?`,\n })\n if (p.isCancel(ok) || ok !== true) {\n ui.cancelled()\n return 0\n }\n }\n\n const built = await buildContext({\n ui,\n root,\n shown,\n manifest: {\n contract: 1,\n provider: null,\n org: null,\n agents,\n boards: null,\n repos: {},\n scopes: {},\n },\n pm,\n skipInstall: input.skipInstall,\n kind: 'blank workspace',\n })\n if (!built) return 1\n await mkdir(join(root, 'org'), { recursive: true })\n await commitContext({ ui, rnessDir: join(root, '.rness'), shown })\n const code = await syncBlocks(ui, root, shown, () =>\n syncCommand({ yes: true, cwd: root })\n )\n if (code !== 0) return code\n\n // No organization to publish to: say how to bring repositories in, and how\n // the workspace becomes an organization's once there is one.\n const next = [\n `cd ${shown}`,\n '# bring a repository in: <owner>/<repo> on GitHub, or any git URL',\n `${rnessCommand()} add <owner>/<repo>`,\n '# to share it: set \"org\" in .rness/rness.json, then push .rness to github.com/<org>/.rness',\n ]\n if (ui.session) {\n ui.note('Next steps', next)\n ui.outro(`Workspace ${name} is ready in ${shown}/`)\n } else\n process.stdout.write(\n [\n '',\n `Workspace \\`${name}\\` is ready in ${shown}/.`,\n '',\n 'Next:',\n ...next.map((line) => ` ${line}`),\n '',\n ].join('\\n')\n )\n return 0\n}\n","import { join } from 'node:path'\n\nimport { isCurrentBlock, renderBlock } from './block.ts'\nimport { assembleContext } from './context.ts'\nimport { exists, readOrNull } from './fs.ts'\nimport { findBlock } from './merge.ts'\nimport { rnessCommand } from './pm.ts'\nimport type { Manifest } from './types.ts'\n\nexport interface CheckBlocksInput {\n root: string\n rnessDir: string\n manifest: Manifest\n org: string\n}\n\n/**\n * What a target's `AGENTS.md` turned out to be. `stale` and `malformed` are\n * problems, `missing-dir` and `no-block` only warnings; `current` says\n * nothing and carries no message.\n */\nexport type BlockStatus =\n 'current' | 'stale' | 'malformed' | 'missing-dir' | 'no-block'\n\nexport interface BlockCheck {\n label: string\n status: BlockStatus\n /** The line the plain look prints; null when the block is current. */\n message: string | null\n}\n\nexport interface CheckBlocksResult {\n problems: string[]\n warnings: string[]\n /** One entry per target, in the order they were checked (spec 0007 §5c). */\n checks: BlockCheck[]\n}\n\nconst PROBLEM: ReadonlySet<BlockStatus> = new Set(['stale', 'malformed'])\n\n/**\n * Compare every present block with a fresh render (spec 0003 §4.6): a\n * different hash is a problem, a missing block only a warning, and nothing\n * is checked where no `org/` directory exists (a standalone context checkout).\n */\nexport async function checkBlocks({\n root,\n rnessDir,\n manifest,\n org,\n}: CheckBlocksInput): Promise<CheckBlocksResult> {\n const checks: BlockCheck[] = []\n const note = (\n label: string,\n status: BlockStatus,\n message: string | null = null\n ): void => {\n checks.push({ label, status, message })\n }\n // The two flat arrays are a view over `checks`, so a line printed today\n // cannot drift from what the terminal renders.\n const derive = (): CheckBlocksResult => ({\n problems: checks\n .filter((c) => PROBLEM.has(c.status) && c.message !== null)\n .map((c) => c.message as string),\n warnings: checks\n .filter((c) => !PROBLEM.has(c.status) && c.message !== null)\n .map((c) => c.message as string),\n checks,\n })\n if (!(await exists(join(root, 'org')))) return derive()\n\n // The root carries the global block twice: in AGENTS.md, and in CLAUDE.md\n // with no `@AGENTS.md` pointer left (spec 0011 §2). A scope, in AGENTS.md.\n const targets: Array<{\n scope: string | null\n dir: string\n depth: number\n file: string\n label: string\n }> = [\n { scope: null, dir: root, depth: 0, file: 'AGENTS.md', label: 'AGENTS.md' },\n { scope: null, dir: root, depth: 0, file: 'CLAUDE.md', label: 'CLAUDE.md' },\n ]\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 file: 'AGENTS.md',\n label: `${entry.path}/AGENTS.md`,\n })\n }\n\n for (const t of targets) {\n if (!(await exists(t.dir))) {\n note(\n t.label,\n 'missing-dir',\n `${t.label}: directory not present, block not checked`\n )\n continue\n }\n const text = await readOrNull(join(t.dir, t.file))\n const lines = text === null ? [] : text.split(/\\r?\\n/)\n const found = findBlock(lines)\n if (found.kind === 'none') {\n note(\n t.label,\n 'no-block',\n `${t.label}: no rness block yet (run ${rnessCommand()} sync)`\n )\n continue\n }\n if (found.kind === 'error') {\n note(t.label, 'malformed', `${t.label}: ${found.message}`)\n continue\n }\n const context = await assembleContext({\n rnessDir,\n manifest,\n scope: t.scope,\n })\n const fresh = renderBlock({\n scope: t.scope,\n org,\n depth: t.depth,\n context,\n })\n // Two ways to be stale: the header no longer matches a fresh render, or the\n // body no longer matches its own header — a hand edit inside the block.\n const pointerLeft =\n t.file === 'CLAUDE.md' && lines.some((l) => l.trim() === '@AGENTS.md')\n if (\n isCurrentBlock(lines.slice(found.begin, found.end + 1), fresh.hash) &&\n !pointerLeft\n )\n note(t.label, 'current')\n else\n note(\n t.label,\n 'stale',\n `${t.label}: stale rness block (run ${rnessCommand()} sync)`\n )\n }\n return derive()\n}\n","import { clearAuth, readAuth } from '../core/auth.ts'\nimport { approvalUrl } from '../core/device-flow.ts'\nimport { removeGitSetup } from '../core/setup-git.ts'\nimport { status } from '../core/style.ts'\nimport { reportError } from '../report.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: ${approvalUrl()}\\n`)\n return 0\n } catch (e) {\n return reportError(e)\n }\n}\n","import { execFile } from 'node:child_process'\nimport { mkdtemp, readFile, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { basename, join, relative } from 'node:path'\nimport { promisify } from 'node:util'\n\nimport { writtenFiles } from '../core/agent-targets.ts'\nimport { readPinnedCli } from '../core/delegate.ts'\nimport { exists, writeFileAtomic } from '../core/fs.ts'\nimport { changedPaths, isClean } from '../core/git.ts'\nimport { loadManifest } from '../core/manifest.ts'\nimport {\n EXACT_VERSION,\n compareVersions,\n readPin,\n workspacePackageManager,\n writePin,\n} from '../core/pinned.ts'\nimport {\n type PackageManager,\n installDependencies,\n packageManagerVersion,\n rnessCommand,\n} from '../core/pm.ts'\nimport { renderScaffold } from '../core/scaffold-copy.ts'\nimport {\n buildScaffoldCommit,\n commitUpgrade,\n findScaffoldBase,\n isRepository,\n mergeInProgress,\n mergeScaffold,\n withoutRedundantKeeps,\n} from '../core/scaffold-git.ts'\nimport { scaffoldDir } from '../core/scaffold.ts'\nimport { status } from '../core/style.ts'\nimport { syncBlocks } from '../core/sync-blocks.ts'\nimport { type Terminal, defaultTerminal } from '../core/terminal.ts'\nimport 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'\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/** `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/** What upgrade takes from outside; tests replace where the scaffold comes from. */\nexport interface UpgradeDeps {\n /** The directory holding `version`'s scaffold, and how to clean it up. */\n scaffoldFor?: (\n version: string,\n rnessDir: string\n ) => Promise<{ dir: string; cleanup?: () => Promise<void> }>\n}\n\n/**\n * Where `version`'s scaffold is read from (spec 0013 §2): the running copy\n * when it is that version, the copy installed in `.rness` when it is (the\n * pin already moved by pull request), else the published package, through\n * `npm pack` — npm follows the user's registry configuration.\n */\nasync function scaffoldFor(\n version: string,\n rnessDir: string\n): Promise<{ dir: string; cleanup?: () => Promise<void> }> {\n if (version === VERSION) return { dir: scaffoldDir() }\n const installed = await readPinnedCli(rnessDir)\n const inside = installed === null ? null : join(installed.dir, 'scaffold')\n if (\n installed?.version === version &&\n inside !== null &&\n (await exists(join(inside, 'package.json')))\n )\n return { dir: inside }\n const scratch = await mkdtemp(join(tmpdir(), 'rness-pack-'))\n const cleanup = () => rm(scratch, { recursive: true, force: true })\n try {\n const { stdout } = await execFileP(\n 'npm',\n [\n 'pack',\n `@rness/cli@${version}`,\n '--pack-destination',\n scratch,\n '--silent',\n ],\n { timeout: 60_000 }\n )\n const tarball = stdout.trim().split('\\n').at(-1) ?? ''\n await execFileP('tar', ['-xzf', join(scratch, tarball), '-C', scratch])\n return { dir: join(scratch, 'package', 'scaffold'), cleanup }\n } catch (e) {\n await cleanup()\n throw new Error(\n `cannot get the @rness/cli ${version} scaffold (npm pack): ${e instanceof Error ? e.message.split('\\n')[0] : String(e)}`,\n { cause: e }\n )\n }\n}\n\n/** The `packageManager` line the workspace declares, kept through every merge. */\nasync function declaredManager(\n rnessDir: string,\n pm: PackageManager\n): Promise<string> {\n try {\n const pkg = JSON.parse(\n await readFile(join(rnessDir, 'package.json'), 'utf8')\n ) as { packageManager?: unknown }\n if (typeof pkg.packageManager === 'string') return pkg.packageManager\n } catch {\n // the install below reports an unreadable package.json\n }\n return `${pm}@${await packageManagerVersion(pm)}`\n}\n\n/** A clone whose files sync writes changed: its path from `cwd`, and those files. */\ninterface CloneChanges {\n dir: string\n paths: string[]\n}\n\n/**\n * The clones where the sync changed a file it writes — never the developer's\n * other files. Other repositories, other review flows: `upgrade` commits\n * none of them, the next steps say what to add (spec 0013 §8).\n */\nasync function clonesToCommit(\n root: string,\n cwd: string,\n manifest: Manifest,\n files: readonly string[]\n): Promise<CloneChanges[]> {\n const clones: CloneChanges[] = []\n for (const repo of Object.keys(manifest.repos)) {\n const dir = join(root, 'org', repo)\n if (!(await exists(dir))) continue\n try {\n const paths = await changedPaths(dir, files)\n if (paths.length > 0)\n clones.push({ dir: relative(cwd, dir) || '.', paths })\n } catch {\n // Not a repository: sync reported it already.\n }\n }\n return clones\n}\n\n/**\n * The files the sync writes in a clone. The sync ran in the copy just\n * installed, whose release may write files this copy does not know — 0.13.0\n * named two of the plugin's six files after syncing with 0.14.0. That copy is\n * asked (`rness written-files`); a copy too old to answer leaves this copy's\n * own list.\n */\nasync function filesTheSyncWrites(\n root: string,\n rnessDir: string,\n manifest: Manifest\n): Promise<string[]> {\n const own = writtenFiles(manifest)\n const pinned = await readPinnedCli(rnessDir)\n if (pinned === null) return own\n try {\n const { stdout } = await execFileP(\n process.execPath,\n [join(pinned.dir, pinned.bin), 'written-files', '--cwd', root],\n {\n cwd: root,\n env: { ...process.env, NO_COLOR: '1', RNESS_NO_INSTALL: '1' },\n timeout: 10_000,\n }\n )\n const theirs: unknown = JSON.parse(stdout)\n if (Array.isArray(theirs) && theirs.every((f) => typeof f === 'string'))\n return [...new Set([...own, ...theirs])]\n } catch {\n // An older copy has no such command: this copy's list is what there is.\n }\n return own\n}\n\n/**\n * The next steps: what `upgrade` did not do. A refused commit is the\n * maintainer's to make, and the command's exit code.\n */\nfunction finish(\n ui: Ui,\n cwd: string,\n rnessDir: string,\n label: string,\n target: string,\n ending: {\n commit: 'committed' | 'nothing' | 'refused'\n clones: readonly CloneChanges[]\n }\n): number {\n const rel = relative(cwd, rnessDir) || '.'\n const message = `chore: rness ${target}`\n const next: string[] = []\n if (ending.commit === 'committed') next.push(`git -C ${rel} push`)\n if (ending.commit === 'refused')\n next.push(`git -C ${rel} commit -m \"${message}\"`)\n for (const c of ending.clones)\n next.push(\n `git -C ${c.dir} add ${c.paths.join(' ')} && git -C ${c.dir} commit -m \"${message}\"`\n )\n if (ending.commit !== 'nothing')\n next.push('# teammates: git pull — the next rness command installs it')\n if (ui.session) {\n if (next.length > 0) 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.length > 0\n ? ['Next:', ...next.map((line) => ` ${line}`), '']\n : []),\n ].join('\\n')\n )\n return ending.commit === 'refused' ? 1 : 0\n}\n\n/**\n * `rness upgrade [version]`: move a workspace to another `@rness/cli` — merge\n * its scaffold, pin it in `.rness/package.json` (the one place the version is\n * written), install with the workspace's package manager, sync through the\n * new copy (spec 0006 §3), commit `.rness` (spec 0013 §8). Never delegated:\n * 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 deps: UpgradeDeps = {}\n): Promise<number> {\n const cwd = opts.cwd ?? process.cwd()\n if (version !== undefined && !EXACT_VERSION.test(version)) {\n process.stderr.write(\n `version \"${version}\" is not an exact version (for example 0.5.0)\\n`\n )\n return 2\n }\n try {\n const ws = await findWorkspace(cwd)\n const label = `${basename(ws.root)}/.rness`\n const pin = await readPin(ws.rnessDir)\n if (pin === null) {\n process.stderr.write(\n `no @rness/cli entry in ${label}/package.json; add it to devDependencies, then run ${rnessCommand()} upgrade\\n`\n )\n return 1\n }\n const interactive = opts.yes !== true\n if (interactive && !terminal.isTty()) {\n process.stderr.write(\n 'rness upgrade installs and writes files; pass --yes to run without a prompt\\n'\n )\n return 2\n }\n\n const ui = interactive ? await makeUi(terminal) : { ...plainUi }\n ui.intro(`Upgrade workspace ${basename(ws.root)}`)\n const target =\n version ??\n (await ui.step(\n { doing: 'asking the registry for the latest release', quiet: true },\n () => latestVersion(),\n (v) => (v === null ? null : ['latest', `@rness/cli ${v}`])\n ))\n if (target === null) {\n process.stderr.write(\n `cannot reach the registry; name the version: ${rnessCommand()} upgrade <version>\\n`\n )\n return 1\n }\n const installed = (await readPinnedCli(ws.rnessDir))?.version ?? null\n // The scaffold is merged with git (spec 0013 §2): `.rness` must be a\n // repository with nothing uncommitted.\n if (!(await isRepository(ws.rnessDir))) {\n process.stderr.write(`${label} is not a git repository\\n`)\n return 1\n }\n if (await mergeInProgress(ws.rnessDir)) {\n process.stderr.write(\n `${label} has a merge in progress; commit it, or abort it with git -C ${relative(cwd, ws.rnessDir) || '.'} merge --abort, then ${rnessCommand()} upgrade\\n`\n )\n return 1\n }\n if (!(await isClean(ws.rnessDir))) {\n process.stderr.write(\n `${label} has uncommitted changes; commit or stash them, then ${rnessCommand()} upgrade\\n`\n )\n return 1\n }\n const base = await findScaffoldBase(ws.rnessDir)\n const scaffoldCurrent = base !== null && base.version === target\n if (pin.spec === target && installed === target && scaffoldCurrent) {\n if (ui.session) ui.outro(`Already at ${target}`)\n else process.stdout.write(`already at ${target}\\n`)\n return 0\n }\n const downgrading =\n EXACT_VERSION.test(pin.spec) && compareVersions(target, pin.spec) < 0\n if (downgrading && version === undefined) {\n process.stderr.write(\n `${label} pins @rness/cli ${pin.spec}, newer than the latest release ${target}; to downgrade: ${rnessCommand()} upgrade ${target}\\n`\n )\n return 1\n }\n\n const pm = await workspacePackageManager(ws.rnessDir)\n if (pin.spec === target && installed === target)\n ui.line(\n 'scaffold',\n `@rness/cli ${target} — merging it into ${label}`,\n `Merging the @rness/cli ${target} scaffold into ${label}`\n )\n else 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 // 1. The scaffold of the target version, merged with git (spec 0013).\n let merged = false\n if (!scaffoldCurrent) {\n const source = await (deps.scaffoldFor ?? scaffoldFor)(\n target,\n ws.rnessDir\n )\n try {\n const files = await renderScaffold(source.dir, {\n version: target,\n packageManager: await declaredManager(ws.rnessDir, pm),\n })\n if (base === null)\n ui.line(\n 'adopting',\n `the @rness/cli ${target} scaffold (no scaffold commit in ${label} yet)`,\n `Adopting the @rness/cli ${target} scaffold — ${label} has no scaffold commit yet`\n )\n else\n ui.line(\n 'merging',\n `the @rness/cli ${target} scaffold`,\n `Merging the @rness/cli ${target} scaffold`\n )\n const commit = await buildScaffoldCommit(\n ws.rnessDir,\n base?.commit ?? null,\n base === null\n ? await withoutRedundantKeeps(ws.rnessDir, files)\n : files,\n target\n )\n const result = await mergeScaffold(\n ws.rnessDir,\n commit,\n base?.commit ?? null\n )\n for (const [change, path] of result.changes) ui.line(change, path)\n if (result.conflicts.length > 0) {\n for (const path of result.conflicts) ui.error(`conflict ${path}`)\n const rel = relative(cwd, ws.rnessDir) || '.'\n ui.hint(\n `resolve them in ${rel} (git checkout --ours <file> keeps yours, --theirs takes the scaffold's, or edit), git add, git commit, then ${rnessCommand()} upgrade again`,\n 'stderr'\n )\n return 1\n }\n merged = true\n } finally {\n await source.cleanup?.()\n }\n }\n\n // 2. The pin — a merge usually moved it already. Restored when the\n // install fails, unless a merge is in progress: `git merge --abort` then.\n const packageFile = join(ws.rnessDir, 'package.json')\n const restore = new Map<string, string>([\n [packageFile, await readFile(packageFile, 'utf8')],\n ])\n const moved = await readPin(ws.rnessDir)\n if (moved !== null && moved.spec !== target)\n await writePin(ws.rnessDir, moved.spec, target)\n\n // Only the scaffold was behind: the pinned copy is already installed.\n const mustInstall = !(pin.spec === target && installed === target)\n if (mustInstall) {\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 const message = e instanceof Error ? e.message : String(e)\n ui.error(message)\n // After a merge, `git merge --abort` puts package.json back; rewriting\n // it here, even byte for byte, would make git refuse the abort.\n if (!merged) {\n for (const [file, text] of restore) await writeFileAtomic(file, text)\n ui.hint(\n `restored ${relative(cwd, packageFile) || packageFile}`,\n 'stderr'\n )\n }\n if (merged)\n ui.hint(\n `the scaffold merge is still staged; undo it with: git -C ${relative(cwd, ws.rnessDir) || '.'} merge --abort`,\n 'stderr'\n )\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\n // Whatever the upgrade had to do: a release may add to the agent files\n // as well as to the blocks (spec 0013 §8). The installed copy is a child\n // 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 // 3. The commit, the end of the upgrade (spec 0013 §8): `.rness` was\n // clean, so everything in it now is the upgrade's.\n const message = `chore: rness ${target}`\n const committed = await commitUpgrade(ws.rnessDir, message)\n if (committed.kind === 'committed')\n ui.line(\n 'committed',\n `${label} — ${message}`,\n `Committed ${label}: ${message}`\n )\n if (committed.kind === 'refused') {\n ui.error(\n `the commit of ${label} was refused; everything is staged — deal with what git said, then commit`\n )\n for (const line of committed.output.split('\\n'))\n if (line.trim() !== '') ui.hint(line, 'stderr')\n }\n return finish(ui, cwd, ws.rnessDir, label, target, {\n commit: committed.kind,\n clones: await (async () => {\n const manifest = await loadManifest(ws.rnessDir)\n return clonesToCommit(\n ws.root,\n cwd,\n manifest,\n await filesTheSyncWrites(ws.root, ws.rnessDir, manifest)\n )\n })(),\n })\n } catch (e) {\n return reportError(e)\n }\n}\n","import { stat } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nimport { PULSE, contractOf } from './board-declaration.ts'\nimport { readmeDeclarations } from './board-migration.ts'\nimport { containedPath } from './contained.ts'\nimport type { Manifest } from './types.ts'\n\n/** Directories of `.rness/` that are never a collection: not documents with a status. */\nconst NEVER = new Set(['standards', 'skills', 'node_modules'])\n\nasync function isDirectory(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isDirectory()\n } catch {\n return false\n }\n}\n\n/**\n * What `validate` says of the boards against the files (spec 0031 §5, §6):\n * a board `rness.json` refused; a collection that is no directory of\n * `.rness/`, or one never a collection; a collection on two boards; a\n * `readme` or `updates` not there or out of `.rness`; a README that still\n * declares what `rness.json` declares now; a preset not created yet named\n * after no collection (spec 0033 §4). One line each.\n */\nexport async function checkBoards(\n rnessDir: string,\n manifest: Manifest\n): Promise<string[]> {\n const problems = (manifest.refused ?? []).map((r) => r.reason)\n const holders = new Map<string, string>()\n const all: string[] = []\n const isCollection = async (dir: string): Promise<boolean> =>\n !NEVER.has(dir) &&\n (contractOf(dir) !== undefined || (await isDirectory(join(rnessDir, dir))))\n for (const [name, entry] of Object.entries(manifest.boards ?? {})) {\n if (typeof entry === 'number') continue\n const at = `boards.${name}`\n if (typeof entry === 'string') {\n // A preset's name: Agent Pulse takes all, a collection's board its own.\n if (name === PULSE) all.push(name)\n else if (!(await isCollection(name)))\n problems.push(\n `\"${at}\" names no collection of .rness: a collection's board is named after its directory`\n )\n else holders.set(name, name)\n continue\n }\n if (entry.collections === 'all') all.push(name)\n else\n for (const collection of Object.keys(entry.collections)) {\n const key = `\"${at}.collections.${collection}\"`\n if (NEVER.has(collection))\n problems.push(\n `${key} is no collection: ${[...NEVER].join(', ')} never are`\n )\n else if (\n contractOf(collection) === undefined &&\n !(await isDirectory(join(rnessDir, collection)))\n )\n problems.push(`${key} names no directory of .rness`)\n const other = holders.get(collection)\n if (other !== undefined)\n problems.push(\n `${key} is on ${other} too: a collection is on one board at most`\n )\n else holders.set(collection, name)\n for (const k of Object.keys(\n await readmeDeclarations(rnessDir, collection).catch(() => ({}))\n ))\n problems.push(\n `${collection}/README.md: \"${k}\" is declared in rness.json now — rness sync moves it`\n )\n }\n for (const key of ['readme', 'updates'] as const) {\n const path = entry[key]\n if (path === null) continue\n try {\n await containedPath(rnessDir, path)\n } catch (e) {\n problems.push(\n (e as NodeJS.ErrnoException).code === 'ENOENT'\n ? `\"${at}.${key}\" names ${path}, which is not there`\n : `\"${at}.${key}\": ${e instanceof Error ? e.message : String(e)}`\n )\n }\n }\n }\n if (all.length > 1)\n problems.push(\n `${all.map((n) => `\"boards.${n}\"`).join(' and ')} each take every collection (\"all\"): a collection is on one board at most`\n )\n return problems\n}\n","import { type TargetOutcome, agentTargets } from './agent-targets.ts'\nimport { unsupportedAgents, unsupportedMessage } from './agents.ts'\nimport { type CheckBlocksResult, checkBlocks } from './blocks.ts'\nimport { checkBoards } from './board-checks.ts'\nimport { checkContract } from './contract.ts'\nimport { workspaceName } from './manifest.ts'\nimport { rnessCommand } from './pm.ts'\nimport { PROVIDERS, unsupportedProviderMessage } from './providers.ts'\nimport { scopeChain } from './scope.ts'\nimport type { Manifest, Workspace } from './types.ts'\n\nexport interface WorkspaceCheck {\n /** One line each, as `validate` prints them off a terminal. */\n problems: string[]\n blocks: CheckBlocksResult\n targets: TargetOutcome[]\n}\n\n/**\n * The problems `rness validate` reports: extends cycles (thrown), the\n * front-matter contract, stale or malformed blocks, agents this copy cannot\n * compile, and values a declared target guarantees but a file lacks (spec\n * 0011 §3). Read-only. Shared with the session-start hook (spec 0015 §3).\n */\nexport async function checkWorkspace(\n ws: Workspace,\n manifest: Manifest\n): Promise<WorkspaceCheck> {\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 problems = await checkContract(ws.rnessDir)\n problems.push(...(await checkBoards(ws.rnessDir, manifest)))\n const blocks = await checkBlocks({\n root: ws.root,\n rnessDir: ws.rnessDir,\n manifest,\n org: workspaceName(manifest, ws.root),\n })\n problems.push(...blocks.problems)\n for (const name of unsupportedAgents(manifest.agents ?? []))\n problems.push(unsupportedMessage(name))\n if (manifest.provider !== null && !PROVIDERS[manifest.provider].available)\n problems.push(unsupportedProviderMessage(manifest.provider))\n const targets = await agentTargets(ws.root, manifest, { check: true })\n for (const o of targets)\n if (o.status === 'stale')\n problems.push(\n `${o.label}: ${o.detail ?? ''} (run ${rnessCommand()} sync)`\n )\n else if (o.status === 'invalid')\n problems.push(`${o.label}: ${o.detail ?? 'unreadable'}`)\n return { problems, blocks, targets }\n}\n","import { checkWorkspace } from '../core/check-workspace.ts'\nimport type { CommandDeps } from '../core/deps.ts'\nimport { loadManifest, workspaceName } from '../core/manifest.ts'\nimport { EXACT_VERSION, readPin } from '../core/pinned.ts'\nimport { rnessCommand } from '../core/pm.ts'\nimport {\n findScaffoldBase,\n isRepository,\n isShallow,\n} from '../core/scaffold-git.ts'\nimport { warn } from '../core/style.ts'\nimport { defaultTerminal } from '../core/terminal.ts'\nimport { makeUi } from '../core/ui.ts'\nimport { findWorkspace } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\n\nexport interface ValidateOptions {\n /** Internal (tests): directory to resolve from; default `process.cwd()`. */\n cwd?: string\n}\n\n/**\n * `rness validate`: manifest, extends cycles, front-matter contract, stale\n * blocks. Returns the exit code.\n *\n * Off a terminal — CI, a git hook, an agent, a pipe — it writes the bytes it\n * always has (spec 0007 rule 1), and never loads a prompt library: that path\n * is ADR 0004's trust anchor. In a real terminal it speaks through the same\n * reporter as the interactive commands (spec 0007 §5c): a count of the blocks\n * that are current, a line for each that is not, and the verdict as the outro.\n */\nexport async function validateCommand(\n opts: ValidateOptions,\n deps: Partial<CommandDeps> = {}\n): Promise<number> {\n const cwd = opts.cwd ?? process.cwd()\n try {\n const ws = await findWorkspace(cwd)\n const manifest = await loadManifest(ws.rnessDir)\n const org = workspaceName(manifest, ws.root)\n const { problems, blocks, targets } = await checkWorkspace(ws, manifest)\n\n // The scaffold (spec 0013 §4): a warning, never a problem — and nothing\n // in a one-commit CI checkout, whose history is not there to read.\n const scaffoldWarnings: string[] = []\n if ((await isRepository(ws.rnessDir)) && !(await isShallow(ws.rnessDir))) {\n const pin = await readPin(ws.rnessDir)\n const base = await findScaffoldBase(ws.rnessDir)\n if (base === null || base.version === null)\n scaffoldWarnings.push(\n `the scaffold is not tracked in .rness yet: run ${rnessCommand()} upgrade`\n )\n else if (\n pin !== null &&\n EXACT_VERSION.test(pin.spec) &&\n pin.spec !== base.version\n )\n scaffoldWarnings.push(\n `the @rness/cli ${pin.spec} scaffold is not merged here: run ${rnessCommand()} upgrade`\n )\n }\n\n const ui = await makeUi(deps.terminal ?? defaultTerminal)\n if (!ui.session) {\n for (const p of problems) process.stderr.write(`${p}\\n`)\n for (const w of [...blocks.warnings, ...scaffoldWarnings])\n process.stderr.write(`${warn(w)}\\n`)\n if (problems.length > 0) return 1\n process.stdout.write('context ok\\n')\n return 0\n }\n\n ui.intro(`Validate ${org}`)\n // One line per target, as `sync` reports one per file it walked: the two\n // commands cross the same targets, so they read the same (spec 0007 §5c).\n // A conforming block is grey — green means something was written, and on a\n // large organization that is what must stand out (spec 0007 §4).\n // The root CLAUDE.md follows the root AGENTS.md, as in `sync`: its line\n // is said only when its status differs.\n const rootStatus = blocks.checks.find(\n (c) => c.label === 'AGENTS.md'\n )?.status\n const shown = blocks.checks.filter(\n (c) => !(c.label === 'CLAUDE.md' && c.status === rootStatus)\n )\n for (const c of shown)\n if (c.message === null) ui.line('current', c.label)\n else if (c.status === 'stale' || c.status === 'malformed')\n ui.error(c.message)\n else ui.warn(c.message)\n for (const o of targets)\n if (o.status === 'unchanged') ui.line('current', o.label)\n for (const p of problems) if (!blocks.problems.includes(p)) ui.error(p)\n for (const w of scaffoldWarnings) ui.warn(w)\n ui.outro(\n problems.length > 0 ? 'Context mismatch' : 'Context OK',\n problems.length > 0 ? 'error' : 'done'\n )\n return problems.length > 0 ? 1 : 0\n } catch (e) {\n return reportError(e)\n }\n}\n","import { Command, CommanderError, Option } from 'commander'\n\nimport { type AddOptions, addCommand } from './commands/add.ts'\nimport {\n type BoardOptions,\n boardPushCommand,\n boardRunCommand,\n pulseCreateCommand,\n} from './commands/board.ts'\nimport { type ContextOptions, contextCommand } from './commands/context.ts'\nimport { type CreateOptions, createCommand } from './commands/create.ts'\nimport { docNewCommand } from './commands/doc.ts'\nimport { gitCredentialCommand } from './commands/git-credential.ts'\nimport { hookCommand } from './commands/hook.ts'\nimport { type LoginOptions, loginCommand } from './commands/login.ts'\nimport { logoutCommand } from './commands/logout.ts'\nimport { type McpOptions, mcpCommand } from './commands/mcp.ts'\nimport { type StatusOptions, statusCommand } from './commands/status.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 { writtenFilesCommand } from './commands/written-files.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\n/** A former command run as its new one: said once, on stderr (spec 0033 §2). */\nfunction formerly(was: string, now: string): void {\n process.stderr.write(`${was} is now ${now}\\n`)\n}\n\n/** `note`, the agent's journal (spec 0030 §4): loaded only when a note is written. */\nfunction noteCommandOf(parent: Command, state: RunState, former?: string) {\n parent\n .command('note [text]')\n .description(\n 'A note on the plan in progress: an approach, a deviation, a blocker, done (the text, or stdin)'\n )\n .option('--plan <path>', 'the plan, when several are in progress')\n .option('--kind <kind>', 'approach, deviation, blocker or done')\n .option(\n '--session <session>',\n 'the session, when CLAUDE_CODE_SESSION_ID is not set'\n )\n .addOption(new Option('--github-api <base>').hideHelp())\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(\n async (\n text: string | undefined,\n opts: {\n plan?: string\n kind?: string\n session?: string\n cwd?: string\n githubApi?: string\n }\n ) => {\n if (former !== undefined) formerly(former, 'rness note')\n const { noteCommand } = await import('./commands/note.ts')\n state.code = await noteCommand({\n ...opts,\n ...(text === undefined ? {} : { text }),\n })\n }\n )\n}\n\n/** `run`, what the hooks start detached: what each board declares (spec 0032 §4). */\nfunction runCommand(parent: Command, state: RunState, former?: string) {\n parent\n .command('run <event>', { hidden: true })\n .requiredOption('--session <id>')\n .option(\n '--path <path>',\n 'the document edited (repeatable)',\n (value: string, previous: string[] = []) => [...previous, value]\n )\n .option('--scope <scope>', \"the session's scope; absent, the root's\")\n .option('--clone <name>', 'the clone the session worked in')\n .addOption(new Option('--github-api <base>').hideHelp())\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(\n async (\n event: string,\n opts: {\n session: string\n path?: string[]\n scope?: string\n clone?: string\n cwd?: string\n githubApi?: string\n }\n ) => {\n if (former !== undefined) formerly(former, 'rness board run')\n const { path, ...rest } = opts\n state.code = await boardRunCommand({\n ...rest,\n event,\n paths: path ?? [],\n })\n }\n )\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('status')\n .description(\n 'Show the status of every decision, specification and plan, a tab per directory'\n )\n .argument('[tab]', 'open on this tab: adr, specs, plans, …')\n .option('--json', 'print JSON instead: what the Claude Code plugin draws')\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (tab: string | undefined, opts: StatusOptions) => {\n state.code = await statusCommand(tab, opts)\n })\n\n // What the lifecycle skills allocate a number with (spec 0028 §9).\n const doc = program\n .command('doc')\n .description('Documents of the workspace: doc new <collection>')\n doc\n .command('new')\n .description(\n 'Write the next numbered document of a collection (adr, specs, plans) and print its path'\n )\n .argument('<collection>', 'adr, specs or plans')\n .option('--title <text>', 'the title; the file name takes its slug')\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(\n async (collection: string, opts: { title?: string; cwd?: string }) => {\n state.code = await docNewCommand(collection, opts)\n }\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(\n '--agent <name>',\n 'declare an agent in rness.json, then write its files (repeatable; supported: claude)',\n (value: string, previous: string[] = []) => [...previous, value]\n )\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 const board = program\n .command('board')\n .description(\n 'The boards of rness.json: the documents of .rness/ on the provider'\n )\n board\n .command('push')\n .description(\n 'Create the boards rness.json declares and the provider lacks, then bring every board up to date with .rness/'\n )\n .option('-y, --yes', 'create the boards not created yet without asking')\n .addOption(new Option('--github-api <base>').hideHelp())\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (opts: BoardOptions) => {\n state.code = await boardPushCommand(opts)\n })\n runCommand(board, state)\n noteCommandOf(program, state)\n\n // The former `rness pulse` (spec 0033 §2): hidden, each command run as its\n // new one, said once on stderr.\n const pulse = program.command('pulse', { hidden: true })\n pulse\n .command('create')\n .argument('[collection]')\n .option('-y, --yes')\n .addOption(new Option('--github-api <base>').hideHelp())\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (collection: string | undefined, opts: BoardOptions) => {\n state.code = await pulseCreateCommand(collection, opts)\n })\n pulse\n .command('sync')\n .addOption(new Option('--github-api <base>').hideHelp())\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (opts: BoardOptions) => {\n formerly('rness pulse sync', 'rness board push')\n state.code = await boardPushCommand(opts)\n })\n noteCommandOf(pulse, state, 'rness pulse note')\n runCommand(pulse, state, 'rness pulse run')\n // Ended with 0.21.x (plan 0048): a 0.20 hook's detached child exits 0.\n pulse\n .command('mark')\n .allowUnknownOption()\n .allowExcessArguments()\n .action(() => {\n state.code = 0\n })\n\n program\n .command('mcp')\n .description(\n 'Serve the workspace context to agents over MCP (stdio; read-only but for rness_note, when a board keeps a journal)'\n )\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (opts: McpOptions) => {\n state.code = await mcpCommand(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 // What `upgrade` asks of the copy it installed: the files its sync writes.\n program\n .command('written-files', { hidden: true })\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (opts: { cwd?: string }) => {\n state.code = await writtenFilesCommand(opts)\n })\n\n // What Claude Code runs for the hooks the Claude target writes (spec 0015).\n program\n .command('hook', { hidden: true })\n .argument(\n '<event>',\n 'session-start, pre-tool-use, post-tool-use or session-end'\n )\n .action(async (event: string) => {\n state.code = await hookCommand(event)\n })\n\n program\n .command('upgrade')\n .alias('update')\n .description(\n 'Move this workspace to another @rness/cli: pin it in .rness/package.json, install, sync'\n )\n .argument('[version]', 'an exact version (default: the latest release)')\n .option('-y, --yes', 'do not ask for confirmation')\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (version: string | undefined, opts: UpgradeOptions) => {\n state.code = await upgradeCommand(version, opts)\n })\n\n program\n .command('create')\n .description(\n \"Create or join a GitHub organization's workspace, or a blank one with --blank\"\n )\n .argument(\n '[name]',\n 'the GitHub organization, same as --org; with --blank, the workspace directory'\n )\n .option(\n '--org <name>',\n 'the GitHub organization, exact name (github.com/<name>)'\n )\n .option(\n '--repos <list>',\n 'comma-separated repositories for your workspace (catalogue entries are cloned, others added)'\n )\n .option(\n '--provider <name>',\n 'where the organization lives: github (gitlab, atlassian later)'\n )\n .option(\n '--pm <name>',\n `package manager for .rness/ (${PACKAGE_MANAGERS.join(', ')}; default: the one running this command)`\n )\n .option(\n '--ssh',\n 'force git@github.com: (default: SSH when it works, else HTTPS)'\n )\n .option('--https', 'force https://github.com/')\n .option(\n '--blank',\n 'a local workspace with no GitHub organization: .rness/, an empty org/, the root files'\n )\n .option(\n '--agent <name>',\n \"a new workspace's agent, declared in rness.json (repeatable; supported: claude)\",\n (value: string, previous: string[] = []) => [...previous, value]\n )\n .option('--skip-install', 'do not install .rness/ dependencies')\n .option('-y, --yes', 'do not ask for confirmation')\n .option('--template <name>', 'reserved')\n .addOption(new Option('--host <base>').hideHelp())\n .addOption(new Option('--github-api <base>').hideHelp())\n .addOption(new Option('--cwd <dir>').hideHelp())\n .action(async (orgArg: string | undefined, opts: CreateOptions) => {\n // Blank, the positional names the directory; --org is refused there.\n if (opts.blank === true) {\n state.code = await createCommand(\n orgArg === undefined ? opts : { ...opts, name: orgArg }\n )\n return\n }\n if (\n orgArg !== undefined &&\n opts.org !== undefined &&\n orgArg !== opts.org\n ) {\n process.stderr.write(\n `organization given twice: \"${orgArg}\" and --org \"${opts.org}\"\\n`\n )\n state.code = 2\n return\n }\n const org = opts.org ?? orgArg\n state.code = await createCommand(\n org === undefined ? opts : { ...opts, org }\n )\n })\n\n return program\n}\n\n/**\n * Parse user arguments and run the matching command. Returns the exit code\n * and never calls process.exit: 0 success, 1 handled error, 2 bad usage.\n */\nexport async function run(argv: string[]): Promise<number> {\n const state: RunState = { code: 0 }\n const program = buildProgram(state)\n if (argv.length === 0) {\n process.stdout.write(banner(VERSION) + program.helpInformation())\n return 0\n }\n try {\n await program.parseAsync(argv, { from: 'user' })\n } catch (e) {\n if (e instanceof CommanderError) {\n // Commander 15 reuses `commander.help`'s code for both the successful\n // `--help` path and error paths (e.g. `help wat`, a lone `--`), so the\n // exit code it already computed is the only reliable signal here.\n return e.exitCode === 0 ? 0 : 2\n }\n throw e\n }\n return state.code\n}\n","import { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nimport { collectMarkdown } from '../core/collect.ts'\nimport { STATUSES } from '../core/contract.ts'\nimport { documentNumber } from '../core/documents.ts'\nimport { scaffoldDir } from '../core/scaffold.ts'\nimport type { CollectionName } from '../core/types.ts'\nimport { findWorkspace } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\n\n/** The collections whose documents are numbered: the ones with a status. */\nconst NUMBERED = Object.keys(STATUSES) as CollectionName[]\n\n/** The sections a new document opens with, by collection; an ADR's come from its template. */\nconst SECTIONS: Partial<Record<CollectionName, readonly string[]>> = {\n specs: [\n 'Summary',\n 'Scope',\n 'Out of scope',\n 'Alternatives considered',\n 'To verify',\n 'Tests',\n ],\n plans: ['Decided here, where the specification leaves it open', 'Tasks'],\n}\n\n/** A few lowercase words of the title joined by hyphens, as the skills make it. */\nexport function slugOf(title: string): string {\n const slug = title\n .normalize('NFKD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 60)\n .replace(/-+$/g, '')\n return slug === '' ? 'untitled' : slug\n}\n\nfunction today(): string {\n return new Date().toISOString().slice(0, 10)\n}\n\n/** The `## ` headings of an ADR template, in order: its sections without their guidance. */\nfunction headingsOf(template: string): string[] {\n return [...template.matchAll(/^## (.+)$/gm)].map((m) => (m[1] ?? '').trim())\n}\n\nasync function adrSections(rnessDir: string): Promise<string[]> {\n const own = join(rnessDir, 'adr', '0000-template.md')\n const shipped = join(scaffoldDir(), 'adr', '0000-template.md')\n for (const file of [own, shipped]) {\n try {\n const sections = headingsOf(await readFile(file, 'utf8'))\n if (sections.length > 0) return sections\n } catch {\n // the next one\n }\n }\n return ['Context', 'Decision', 'Alternatives Considered', 'Consequences']\n}\n\n/**\n * Write a new document, never over a file: the next number names a file\n * present only when two sessions allocate at once, and then the second one\n * writes nothing (`wx` decides, atomically). Prints the path, or why not.\n */\nexport async function writeDocument(\n file: string,\n text: string\n): Promise<number> {\n try {\n await writeFile(file, text, { flag: 'wx' })\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e\n process.stderr.write(`${file} exists; nothing written\\n`)\n return 1\n }\n process.stdout.write(`${file}\\n`)\n return 0\n}\n\n/**\n * `rness doc new <collection> [--title]` (spec 0028 §9): the next number of\n * the collection, the file with the collection's front matter and opening\n * sections, its path printed. The number comes from the files present, so\n * every runtime and a bare terminal get the same one; never overwrites.\n */\nexport async function docNewCommand(\n collection: string,\n opts: { title?: string; cwd?: string }\n): Promise<number> {\n if (!(NUMBERED as string[]).includes(collection)) {\n process.stderr.write(\n `${collection} is not a numbered collection of this workspace (${NUMBERED.join(', ')})\\n`\n )\n return 2\n }\n const name = collection as CollectionName\n try {\n const ws = await findWorkspace(opts.cwd ?? process.cwd())\n const dir = join(ws.rnessDir, name)\n // A collection the scaffold made empty, or a workspace without it yet.\n await mkdir(dir, { recursive: true })\n let highest = 0\n for (const item of await collectMarkdown(dir)) {\n const number = documentNumber(item.rel)\n if (number !== null) highest = Math.max(highest, Number(number))\n }\n const number = String(highest + 1).padStart(4, '0')\n const title = opts.title?.trim() || 'Untitled'\n const file = join(dir, `${number}-${slugOf(title)}.md`)\n const status = STATUSES[name]?.[0] ?? 'Draft'\n const date = today()\n const front = [\n '---',\n `date: ${date}`,\n `status: ${status}`,\n \"repo: ''\",\n // An ADR is never updated once accepted: no `updated` (CONVENTIONS.md).\n ...(name === 'adr' ? [] : [`updated: ${date}`]),\n '---',\n ]\n const sections =\n name === 'adr' ? await adrSections(ws.rnessDir) : (SECTIONS[name] ?? [])\n const body = [\n `# ${number} — ${title}`,\n // The rule under the title, as the ADR and specification templates draw it.\n ...(name === 'plans' ? [] : ['', '---']),\n ...sections.flatMap((s) => ['', `## ${s}`]),\n ]\n return await writeDocument(file, `${[...front, '', ...body].join('\\n')}\\n`)\n } catch (e) {\n return reportError(e)\n }\n}\n","import { resolveToken } from '../core/auth.ts'\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = []\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer)\n return Buffer.concat(chunks).toString('utf8')\n}\n\n/**\n * `rness git-credential <get|store|erase>`: git's credential-helper protocol\n * (spec 0004 §5). Only `get` for https://github.com is answered, with the\n * token of this machine; everything else is silence, which tells git to look\n * elsewhere. `input` is what git writes on stdin.\n */\nexport async function gitCredentialCommand(\n operation: string,\n input?: string\n): Promise<number> {\n if (operation !== 'get') return 0\n const fields = new Map<string, string>()\n for (const line of (input ?? (await readStdin())).split('\\n')) {\n const eq = line.indexOf('=')\n if (eq > 0) fields.set(line.slice(0, eq), line.slice(eq + 1).trimEnd())\n }\n if (fields.get('protocol') !== 'https' || fields.get('host') !== 'github.com')\n return 0\n const resolved = await resolveToken().catch(() => null)\n if (resolved === null) return 0\n process.stdout.write(`username=x-access-token\\npassword=${resolved.token}\\n`)\n return 0\n}\n","import { realpath } from 'node:fs/promises'\nimport { isAbsolute, posix, relative, resolve, sep } from 'node:path'\nimport type { Readable, Writable } from 'node:stream'\n\nimport { type Spawn, detached, takeFailure } from '../board/detached.ts'\nimport { recordStart, takeNotices } from '../board/journal-state.ts'\nimport { BLOCK_FILES } from '../core/agent-targets.ts'\nimport type { BoardDeclaration, HookEvent } from '../core/board-declaration.ts'\nimport { takeModNotice } from '../core/claude-code.ts'\nimport { COLLECTIONS } from '../core/context.ts'\nimport { checkContract } from '../core/contract.ts'\nimport {\n type Replayed,\n editRefusal,\n ownedRefusal,\n ownedWhole,\n replayEdit,\n writeRefusal,\n} from '../core/edit-guard.ts'\nimport { readOrNull } from '../core/fs.ts'\nimport { loadManifest, parseManifest } from '../core/manifest.ts'\nimport { type NamedBoard, readBoards } from '../core/preset-board.ts'\nimport { cloneHolding } from '../core/repos.ts'\nimport { safetyNet } from '../core/safety-net.ts'\nimport { resolveScope, scopeChain } from '../core/scope.ts'\nimport { documentsIn, plansInProgress } from '../core/status.ts'\nimport type { Manifest, Workspace } from '../core/types.ts'\nimport { findWorkspace } from '../core/workspace.ts'\nimport { noteLines, scopeBanner } from './snapshot.ts'\n\n/**\n * `rness hook <event>`: what Claude Code runs for the hooks the Claude\n * target writes (spec 0015). Never installs, delegates or writes a file:\n * `hook` is one of the launcher's own commands (`OWN_COMMANDS`).\n */\n\nexport interface HookIo {\n input: Readable & { isTTY?: boolean }\n output: Writable\n error: Writable\n env: NodeJS.ProcessEnv\n /** Runs `rness <args>` detached (the boards); tests record instead. */\n spawn?: Spawn\n}\n\ntype Input = Record<string, unknown>\n\n/** The hook's JSON on stdin; `{}` from a terminal or for anything else. */\nasync function readInput(input: HookIo['input']): Promise<Input> {\n if (input.isTTY === true) return {}\n let text = ''\n for await (const chunk of input) text += String(chunk)\n try {\n const data: unknown = JSON.parse(text)\n return data !== null && typeof data === 'object' && !Array.isArray(data)\n ? (data as Input)\n : {}\n } catch {\n return {}\n }\n}\n\nconst message = (e: unknown): string =>\n e instanceof Error ? e.message : String(e)\n\n/** The session's directory: the input's, else the project's, else ours. */\nfunction cwdOf(input: Input, env: NodeJS.ProcessEnv): string {\n const cwd = input['cwd']\n if (typeof cwd === 'string' && cwd !== '') return cwd\n return env['CLAUDE_PROJECT_DIR'] ?? process.cwd()\n}\n\nconst toPosix = (p: string): string => p.split(sep).join(posix.sep)\n\n/** `claude · <first 8 of session_id>`, with the agent type when there is one. */\nfunction sessionOf(input: Input): string | null {\n const id = input['session_id']\n if (typeof id !== 'string' || id === '') return null\n const type = input['agent_type']\n return [\n 'claude',\n ...(typeof type === 'string' && type !== '' ? [type] : []),\n id.slice(0, 8),\n ].join(' · ')\n}\n\ntype HookBoard = NamedBoard\n\n/** The boards `rness.json` declares (see {@link readBoards}). */\nconst boardsOf = (ws: Workspace): Promise<HookBoard[]> =>\n readBoards(ws.rnessDir)\n\n/** Whether a board holds a document: one that takes all, any; else one of its collections'. */\nconst holds = (board: BoardDeclaration, path: string): boolean =>\n board.collections === 'all' ||\n Object.hasOwn(board.collections, path.split('/')[0] ?? '')\n\n/**\n * Starts `board run <event>` detached (spec 0032 §4), when the input names\n * a session, some board declares an action at the event, and `rest` finds\n * something for it to do. The hooks never fail the session over it.\n */\nasync function runDetached(\n ws: Workspace,\n input: Input,\n io: HookIo,\n event: HookEvent,\n rest: (\n session: string,\n boards: readonly HookBoard[]\n ) => Promise<string[] | null>\n): Promise<void> {\n try {\n const session = sessionOf(input)\n if (session === null) return\n const boards = (await boardsOf(ws)).filter(\n (b) => (b.declaration.hooks[event] ?? []).length > 0\n )\n if (boards.length === 0) return\n const args = await rest(session, boards)\n if (args !== null)\n (io.spawn ?? detached)(['board', 'run', event, ...args], ws.root)\n } catch {\n // The board is a courtesy: nothing here may reach the session.\n }\n}\n\n/**\n * The journal at session start (spec 0030 §6, §7), with no network: what\n * the model is told, when a board keeps one and the scope has a plan in\n * progress; and the session's start in the clone it works in, for the\n * summary. Never throws.\n */\nasync function journalStart(\n ws: Workspace,\n manifest: Manifest,\n scope: string | null,\n cwd: string,\n input: Input\n): Promise<string[]> {\n try {\n for (const { declaration } of await boardsOf(ws))\n for (const a of declaration.hooks['session-start'] ?? []) {\n if (a.action !== 'journal') continue\n const plans = await plansInProgress(ws, manifest, scope)\n if (plans.length === 0) return []\n const session = sessionOf(input)\n const clone = cloneHolding(ws.root, manifest.repos, cwd)\n const summarised = (declaration.hooks['session-end'] ?? []).some(\n (e) => e.action === 'journal-summary'\n )\n if (session !== null && clone !== null && summarised)\n await recordStart(clone.dir, session)\n // `rness note` reads the session from the Bash tool's\n // environment; `rness_note` cannot, so it is spelt for it.\n const tool =\n session === null\n ? 'rness_note'\n : `rness_note, its session \"${session}\"`\n const which =\n plans.length === 1\n ? plans.join('')\n : `${plans.join(' or ')} (pass --plan)`\n return [\n [\n `Journal: post a note with \\`rness note\\` (or ${tool}) when you choose an approach, deviate from plan ${which}, are blocked, and when done.`,\n `At most ${a.limit}: decisions and their reasons, not steps.`,\n ...(a.to === 'repo'\n ? [\n 'The first note prints the issue to reference; the pull request that completes this plan here carries `Closes <issue>`, an earlier one `Refs <issue>`.',\n ]\n : []),\n ].join(' '),\n ]\n }\n } catch {\n // The journal is a courtesy: nothing here may reach the session.\n }\n return []\n}\n\n/**\n * A banner for the developer and the scope's summary for the model (spec\n * 0015 §3). One JSON object, always, and exit 0: a failure is a line of it.\n */\nasync function sessionStart(\n input: Input,\n io: HookIo\n): Promise<Record<string, unknown>> {\n const cwd = cwdOf(input, io.env)\n let banner: string | null = null\n let context: string[] = []\n let notes: string[]\n try {\n const ws = await findWorkspace(cwd)\n const manifest = await loadManifest(ws.rnessDir)\n const scope = resolveScope(manifest, toPosix(relative(ws.root, cwd)))\n const view = await scopeBanner(ws, manifest, scope)\n banner = view.banner\n const at = toPosix(relative(cwd, ws.rnessDir)) || '.rness'\n context = [\n ...view.lines,\n `These documents are in ${at}: read one there, or with rness_read when the rness MCP server is connected.`,\n ...(await journalStart(ws, manifest, scope, cwd, input)),\n ]\n notes = await safetyNet(ws, manifest)\n // Only when some board has documents of the scope to mark: no process\n // started for nothing.\n await runDetached(\n ws,\n input,\n io,\n 'session-start',\n async (session, boards) => {\n for (const { declaration } of boards)\n for (const a of declaration.hooks['session-start'] ?? [])\n if (\n a.action === 'mark-in-progress' &&\n (\n await documentsIn(\n ws,\n manifest,\n scope,\n a.collections,\n a.statuses\n )\n ).some((p) => holds(declaration, p))\n )\n return [\n '--session',\n session,\n ...(scope === null ? [] : ['--scope', scope]),\n ]\n return null\n }\n )\n } catch (e) {\n notes = [message(e)]\n }\n const failure = await takeFailure()\n if (failure !== null) notes.push(`board not updated — ${failure}`)\n notes.push(...(await takeNotices()))\n const warnings = noteLines(notes)\n const compact = input['source'] === 'compact'\n // For the developer only: the model has nothing to do about it.\n const tooOld = compact ? null : await takeModNotice(io.env)\n const shown = [\n ...(banner !== null && !compact ? [banner] : []),\n ...warnings,\n ...(tooOld !== null ? [tooOld] : []),\n ]\n return {\n ...(shown.length > 0 ? { systemMessage: shown.join('\\n') } : {}),\n hookSpecificOutput: {\n hookEventName: 'SessionStart',\n additionalContext: [...context, ...warnings].join('\\n'),\n },\n }\n}\n\n/** `relative(from, to)` when `to` is inside `from`, else null. */\nfunction inside(from: string, to: string): string | null {\n const rel = relative(from, to)\n return rel === '' || rel.startsWith('..') || isAbsolute(rel)\n ? null\n : toPosix(rel)\n}\n\n/**\n * After an edit (spec 0015 §4): the problems the edited file of `.rness/`\n * now has, or those of `rness.json`. Exit 2 with them on stderr — Claude\n * Code hands them to the model — else 0, silent. The path is checked before\n * anything is read: this runs after every edit of the session.\n */\nasync function postToolUse(input: Input, io: HookIo): Promise<number> {\n const toolInput = input['tool_input']\n const path =\n toolInput !== null && typeof toolInput === 'object'\n ? (toolInput as Input)['file_path']\n : undefined\n if (typeof path !== 'string' || path === '') return 0\n const cwd = cwdOf(input, io.env)\n let ws: Workspace\n try {\n ws = await findWorkspace(cwd)\n } catch {\n return 0\n }\n const rel = await within(ws.rnessDir, resolve(cwd, path))\n if (rel === null) return 0\n const first = rel.split('/')[0] ?? ''\n let problems: string[] = []\n if (rel === 'rness.json') {\n try {\n const manifest = await loadManifest(ws.rnessDir)\n for (const s of Object.keys(manifest.scopes)) scopeChain(manifest, s)\n } catch (e) {\n problems = [message(e)]\n }\n } else if (\n (COLLECTIONS as readonly string[]).includes(first) &&\n rel.endsWith('.md')\n )\n problems = (await checkContract(ws.rnessDir)).filter((p) =>\n p.startsWith(`${rel}:`)\n )\n // Marked after the check, broken or not: the agent is at work on it — by\n // a board that declares `mark` and holds its collection (spec 0032 §2).\n if (rel.endsWith('.md') && rel.includes('/'))\n await runDetached(ws, input, io, 'edit', async (session, boards) =>\n boards.some(\n (b) =>\n (b.declaration.hooks.edit ?? []).some((a) => a.action === 'mark') &&\n holds(b.declaration, rel)\n )\n ? ['--session', session, '--path', rel]\n : null\n )\n if (problems.length === 0) return 0\n io.error.write(\n [\n ...problems.map((p) => `rness: ${p}`),\n `Fix it in ${rel}; rness validate checks the whole workspace.`,\n '',\n ].join('\\n')\n )\n return 2\n}\n\n/** The relative path of `file` in `base`, through real paths too; null outside. */\nasync function within(base: string, file: string): Promise<string | null> {\n // The session may name the file through a link the workspace path does\n // not take (macOS: /tmp and /private/tmp): compare real paths as well.\n return (\n inside(base, file) ??\n inside(\n await realpath(base).catch(() => base),\n await realpath(file).catch(() => file)\n )\n )\n}\n\n/** What a `rness.json` text would make `validate` say: the manifest, then its scopes. */\nfunction manifestProblems(text: string | null): string[] {\n if (text === null) return []\n try {\n const manifest = parseManifest(text)\n for (const s of Object.keys(manifest.scopes)) scopeChain(manifest, s)\n return []\n } catch (e) {\n return [message(e)]\n }\n}\n\n/**\n * The problems an edit of `.rness/<rel>` would add (spec 0029 §4.3): those\n * its text after has and the file now has not. A document already broken\n * stays editable; an edit that fixes part of it passes.\n */\nasync function addedProblems(\n ws: Workspace,\n rel: string,\n before: string | null,\n after: string\n): Promise<string[]> {\n let was: string[]\n let will: string[]\n if (rel === 'rness.json') {\n was = manifestProblems(before)\n will = manifestProblems(after)\n } else {\n const first = rel.split('/')[0] ?? ''\n if (\n !(COLLECTIONS as readonly string[]).includes(first) ||\n !rel.endsWith('.md')\n )\n return []\n const mine = (p: string) => p.startsWith(`${rel}:`)\n was = (await checkContract(ws.rnessDir)).filter(mine)\n will = (await checkContract(ws.rnessDir, { rel, text: after })).filter(mine)\n }\n return will.filter((p) => !was.includes(p))\n}\n\n/**\n * Before an `Edit` or a `Write` (spec 0029 §4): refused, exit 2 with the\n * reason on stderr — Claude Code does not run the tool and the model reads\n * why — when it would change what `sync` generates (the block, the plugin's\n * files) or add a contract problem to `.rness/`. Else 0, silent; and 0 on\n * any failure of its own: the guard never stops a session. The path is\n * checked before anything is read: this runs before every edit.\n */\nasync function preToolUse(input: Input, io: HookIo): Promise<number> {\n const toolInput = input['tool_input']\n if (toolInput === null || typeof toolInput !== 'object') return 0\n const args = toolInput as Input\n const path = args['file_path']\n if (typeof path !== 'string' || path === '') return 0\n try {\n const cwd = cwdOf(input, io.env)\n const ws = await findWorkspace(cwd)\n const file = resolve(cwd, path)\n const label = await within(ws.root, file)\n if (label === null) return 0\n if (ownedWhole(label)) return refuse(io, [ownedRefusal(label)])\n const rel = await within(ws.rnessDir, file)\n const blocked = BLOCK_FILES.includes(posix.basename(label))\n if (rel === null && !blocked) return 0\n const before = await readOrNull(file)\n let after: string\n let spans: Replayed['spans'] | null = null\n if (input['tool_name'] === 'Write') {\n const content = args['content']\n if (typeof content !== 'string') return 0\n after = content\n } else {\n const { old_string, new_string, replace_all } = args\n if (\n before === null ||\n typeof old_string !== 'string' ||\n typeof new_string !== 'string'\n )\n return 0\n const replayed = replayEdit(\n before,\n old_string,\n new_string,\n replace_all === true\n )\n if (replayed === null) return 0\n after = replayed.after\n spans = replayed.spans\n }\n if (blocked && before !== null) {\n const reason =\n spans === null\n ? writeRefusal(label, before, after)\n : editRefusal(label, before, spans)\n if (reason !== null) return refuse(io, [reason])\n }\n if (rel === null) return 0\n const added = await addedProblems(ws, rel, before, after)\n if (added.length === 0) return 0\n return refuse(io, [\n ...added.map((p) => `rness: ${p}`),\n `Fix the edit of ${rel}; rness validate checks the whole workspace.`,\n ])\n } catch {\n return 0\n }\n}\n\nfunction refuse(io: HookIo, lines: readonly string[]): number {\n io.error.write(`${lines.join('\\n')}\\n`)\n return 2\n}\n\n/** Clears the session's marks, detached; says nothing. */\nasync function sessionEnd(input: Input, io: HookIo): Promise<number> {\n try {\n const cwd = cwdOf(input, io.env)\n const ws = await findWorkspace(cwd)\n await runDetached(ws, input, io, 'session-end', async (session, boards) => {\n const summarised = boards.some((b) =>\n (b.declaration.hooks['session-end'] ?? []).some(\n (a) => a.action === 'journal-summary'\n )\n )\n if (!summarised) return ['--session', session]\n // The summary's plan is the scope's; its commits, the clone's.\n const manifest = await loadManifest(ws.rnessDir)\n const scope = resolveScope(manifest, toPosix(relative(ws.root, cwd)))\n const clone = cloneHolding(ws.root, manifest.repos, cwd)\n return [\n '--session',\n session,\n ...(scope === null ? [] : ['--scope', scope]),\n ...(clone === null ? [] : ['--clone', clone.name]),\n ]\n })\n } catch {\n // No workspace, nothing to clear.\n }\n return 0\n}\n\nexport async function hookCommand(\n event: string,\n io: HookIo = {\n input: process.stdin,\n output: process.stdout,\n error: process.stderr,\n env: process.env,\n }\n): Promise<number> {\n if (\n event !== 'session-start' &&\n event !== 'pre-tool-use' &&\n event !== 'post-tool-use' &&\n event !== 'session-end'\n ) {\n io.error.write(\n `unknown hook event ${JSON.stringify(event)} (known: session-start, pre-tool-use, post-tool-use, session-end)\\n`\n )\n return 1\n }\n const input = await readInput(io.input)\n if (event === 'pre-tool-use') return preToolUse(input, io)\n if (event === 'post-tool-use') return postToolUse(input, io)\n if (event === 'session-end') return sessionEnd(input, io)\n io.output.write(`${JSON.stringify(await sessionStart(input, io))}\\n`)\n return 0\n}\n","import { mkdir, readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nimport { configDir } from './auth.ts'\nimport { writeFileAtomic } from './fs.ts'\n\n/**\n * The Claude Code running a hook, and whether it can load the rness plugin's\n * mod (spec 0029 §3; plan 0041). An older one is told once per version, from\n * the session-start line: a band that says \"update Claude Code\" is a band\n * Claude Code already draws.\n */\n\n/** The oldest Claude Code seen running the mod (plan 0040); 2.1.240 ignored it. */\nexport const MOD_FLOOR = '2.1.280'\n\n// Set by the running Claude Code itself, never inherited from a parent\n// session, unlike CLAUDE_CODE_VERSION (verified on 2.1.240 to 2.1.289). The\n// suffix says who runs the command: `_harness` for a hook, `_agent` for the\n// model's Bash tool; the version is the same.\nconst AGENT = /^claude-code_(\\d+)-(\\d+)-(\\d+)_[a-z]+$/\n\n/** `2.1.240` from `AI_AGENT=claude-code_2-1-240_harness`; null for another agent or another form. */\nexport function claudeCodeVersion(env: NodeJS.ProcessEnv): string | null {\n const m = AGENT.exec(env['AI_AGENT'] ?? '')\n return m === null ? null : `${m[1]}.${m[2]}.${m[3]}`\n}\n\n/** True when `version` (`major.minor.patch`) is older than `MOD_FLOOR`. */\nexport function belowModFloor(version: string): boolean {\n const have = version.split('.').map(Number)\n const floor = MOD_FLOOR.split('.').map(Number)\n for (let i = 0; i < 3; i++) {\n const a = have[i] ?? 0\n const b = floor[i] ?? 0\n if (a !== b) return a < b\n }\n return false\n}\n\nconst noticeFile = (): string => join(configDir(), 'claude-code.json')\n\n/** The versions already told; none when the file is missing or unreadable. */\nasync function shownVersions(): Promise<string[]> {\n try {\n const data: unknown = JSON.parse(await readFile(noticeFile(), 'utf8'))\n const shown =\n data !== null && typeof data === 'object'\n ? (data as Record<string, unknown>)['modNoticeShown']\n : undefined\n return Array.isArray(shown)\n ? shown.filter((v): v is string => typeof v === 'string')\n : []\n } catch {\n return []\n }\n}\n\n/**\n * The line for a Claude Code too old for the mod, once per version and\n * machine: the version is recorded in `claude-code.json` of the config\n * directory when the line is returned. Null without a version, at or above\n * the floor, in a session nobody watches (`CLAUDE_CODE_ENTRYPOINT=sdk-…`,\n * which would use up the one time), or once told. Never throws: a file that\n * cannot be written still gives the line, and nothing stops the hook.\n */\nexport async function takeModNotice(\n env: NodeJS.ProcessEnv\n): Promise<string | null> {\n const version = claudeCodeVersion(env)\n if (version === null || !belowModFloor(version)) return null\n if ((env['CLAUDE_CODE_ENTRYPOINT'] ?? '').startsWith('sdk-')) return null\n const shown = await shownVersions()\n if (shown.includes(version)) return null\n try {\n await mkdir(configDir(), { recursive: true, mode: 0o700 })\n await writeFileAtomic(\n noticeFile(),\n `${JSON.stringify({ modNoticeShown: [...shown, version] })}\\n`\n )\n } catch {\n // Not recorded: the line comes again next session, which beats silence.\n }\n return `rness: Claude Code ${version} shows no rness band, footer label or pane; ${MOD_FLOOR} or later does — claude update`\n}\n","import { findBlock } from './merge.ts'\n\n/**\n * What `rness hook pre-tool-use` decides before Claude Code writes a file\n * (spec 0029 §4): pure functions over the file's text and the tool's input.\n */\n\n/** A file's text as an `Edit` or a `Write` would leave it. */\nexport interface Replayed {\n after: string\n /** The character ranges of the text the edit replaces; the whole file for a `Write`. */\n spans: readonly (readonly [number, number])[]\n}\n\n/** The non-overlapping occurrences of `needle` in `text`, as character ranges. */\nfunction occurrences(text: string, needle: string): [number, number][] {\n const spans: [number, number][] = []\n for (\n let i = text.indexOf(needle);\n i !== -1;\n i = text.indexOf(needle, i + needle.length)\n )\n spans.push([i, i + needle.length])\n return spans\n}\n\nconst QUOTES: Readonly<Record<string, string>> = {\n '\\u2018': \"'\",\n '\\u2019': \"'\",\n '\\u201c': '\"',\n '\\u201d': '\"',\n}\n\n/**\n * A text as the Edit tool compares it when the exact string is not found:\n * curly quotes read straight, a CRLF reads as LF. `at` maps each of its\n * characters, and its end, back to the original's offsets.\n */\nfunction loose(text: string): { text: string; at: number[] } {\n let out = ''\n const at: number[] = []\n for (let i = 0; i < text.length; i++) {\n const c = text[i] ?? ''\n if (c === '\\r' && text[i + 1] === '\\n') continue\n out += QUOTES[c] ?? c\n at.push(i)\n }\n at.push(text.length)\n return { text: out, at }\n}\n\n/**\n * An `Edit` replayed as the tool does it: every occurrence under\n * `replace_all`, else exactly one; the exact string first, then as the tool\n * also finds it, straight quotes for curly ones and LF for CRLF (seen\n * 2026-10-04: `product's` sent for a block's `product’s`). Null when the\n * tool would refuse it (nothing found, found twice, an empty `old_string`):\n * it fails on its own.\n */\nexport function replayEdit(\n text: string,\n oldString: string,\n newString: string,\n all: boolean\n): Replayed | null {\n if (oldString === '') return null\n let spans = occurrences(text, oldString)\n if (spans.length === 0) {\n const file = loose(text)\n spans = occurrences(file.text, loose(oldString).text).map(\n ([s, e]): [number, number] => [file.at[s] ?? 0, (file.at[e - 1] ?? 0) + 1]\n )\n }\n if (spans.length === 0 || (!all && spans.length !== 1)) return null\n let after = text\n for (const [s, e] of [...spans].reverse())\n after = `${after.slice(0, s)}${newString}${after.slice(e)}`\n return { after, spans }\n}\n\n/** The whole files rness writes in a project directory (spec 0016 §3.2). */\nconst OWNED = /(?:^|\\/)\\.claude\\/skills\\/rness\\//\n\n/** Whether a workspace-relative path is one of rness's whole files. */\nexport const ownedWhole = (rel: string): boolean => OWNED.test(rel)\n\nexport function ownedRefusal(label: string): string {\n return `rness: ${label} is written whole by rness sync, and the next sync overwrites it. Leave it to rness.`\n}\n\nconst MARKER = /^<!-- rness: (\\S+) -->$/\n\ninterface Block {\n /** Line indexes, inclusive. */\n begin: number\n end: number\n /** Character offsets: the first of BEGIN, the one after END. */\n from: number\n to: number\n lines: string[]\n}\n\nfunction blockOf(text: string): Block | null {\n const lines = text.split(/\\r?\\n/)\n const found = findBlock(lines)\n if (found.kind !== 'one') return null\n const starts = [0]\n for (const m of text.matchAll(/\\r?\\n/g))\n starts.push((m.index ?? 0) + m[0].length)\n const from = starts[found.begin] ?? 0\n const to = (starts[found.end] ?? 0) + (lines[found.end] ?? '').length\n return { begin: found.begin, end: found.end, from, to, lines }\n}\n\n/** The line of a character offset. */\nfunction lineAt(text: string, offset: number): number {\n return text.slice(0, offset).split(/\\r?\\n/).length - 1\n}\n\n/** The source of a block's line: the nearest rule marker above it in the block. */\nfunction sourceOf(block: Block, line: number): string {\n for (let i = Math.min(line, block.end); i > block.begin; i--) {\n const m = MARKER.exec((block.lines[i] ?? '').trimEnd())\n if (m !== null) return `.rness/${m[1] ?? ''}`\n }\n return '.rness/ and rness.json'\n}\n\nfunction blockRefusal(label: string, block: Block, source: string): string {\n return `rness: lines ${block.begin + 1}–${block.end + 1} of ${label} are generated by rness sync from ${source}. Edit that file, then run rness sync.`\n}\n\n/**\n * Why an `Edit` of a file holding the block is refused: one of the ranges it\n * replaces overlaps the block. Null when it leaves the block alone, or when\n * the file has no block (or a broken one, which `sync` reports).\n */\nexport function editRefusal(\n label: string,\n before: string,\n spans: Replayed['spans']\n): string | null {\n const block = blockOf(before)\n if (block === null) return null\n const hit = spans.find(([s, e]) => s < block.to && e > block.from)\n if (hit === undefined) return null\n return blockRefusal(\n label,\n block,\n sourceOf(block, lineAt(before, Math.max(hit[0], block.from)))\n )\n}\n\n/**\n * Why a `Write` of a file holding the block is refused: the block is not in\n * the new text byte for byte. The source named is that of the first line\n * that differs.\n */\nexport function writeRefusal(\n label: string,\n before: string,\n after: string\n): string | null {\n const block = blockOf(before)\n if (block === null) return null\n const kept = blockOf(after)\n const was = before.slice(block.from, block.to)\n if (kept !== null && after.slice(kept.from, kept.to) === was) return null\n const next = kept === null ? [] : kept.lines.slice(kept.begin, kept.end + 1)\n const old = block.lines.slice(block.begin, block.end + 1)\n const first = old.findIndex((line, i) => line !== next[i])\n return blockRefusal(\n label,\n block,\n kept === null\n ? '.rness/ and rness.json'\n : sourceOf(block, block.begin + Math.max(first, 0))\n )\n}\n","import { checkWorkspace } from './check-workspace.ts'\nimport type { loadManifest } from './manifest.ts'\nimport { pinDrift, workspacePackageManager } from './pinned.ts'\nimport { count } from './style.ts'\nimport type { Workspace } from './types.ts'\n\n/** How many of `validate`'s problems the safety net spells out. */\nexport const SHOWN_PROBLEMS = 3\n\nconst message = (e: unknown): string =>\n e instanceof Error ? e.message : String(e)\n\n/**\n * Why the context may be wrong (spec 0015 §3): the installed copy, then\n * validate's problems, the first few spelled out on indented lines. What the\n * session-start hook says, and what the Claude Code mod shows (spec 0029).\n */\nexport async function safetyNet(\n ws: Workspace,\n manifest: Awaited<ReturnType<typeof loadManifest>>\n): Promise<string[]> {\n const notes: string[] = []\n const drift = await pinDrift(ws.rnessDir)\n if (drift !== null)\n notes.push(\n `.rness pins @rness/cli ${drift.pin} but ${drift.installed ?? 'nothing'} is installed — run ${await workspacePackageManager(ws.rnessDir)} install in .rness`\n )\n try {\n const { problems } = await checkWorkspace(ws, manifest)\n if (problems.length > 0)\n notes.push(\n `${count(problems.length, ['problem', 'problems'])} in the workspace context — run rness validate`,\n ...problems.slice(0, SHOWN_PROBLEMS).map((p) => ` ${p}`)\n )\n } catch (e) {\n notes.push(message(e))\n }\n return notes\n}\n","import { readFile, realpath, stat } from 'node:fs/promises'\nimport { isAbsolute, join, posix, relative, resolve, sep } from 'node:path'\n\nimport { collectMarkdown } from '../core/collect.ts'\nimport { COLLECTIONS, assembleContext, ownerScope } from '../core/context.ts'\nimport { STATUSES } from '../core/contract.ts'\nimport { documentNumber, documentTitle } from '../core/documents.ts'\nimport { loadManifest, workspaceName } from '../core/manifest.ts'\nimport { readBoards } from '../core/preset-board.ts'\nimport { resolveScope } from '../core/scope.ts'\nimport type { CollectionName, Manifest, Workspace } from '../core/types.ts'\nimport { findWorkspace } from '../core/workspace.ts'\nimport type { McpTool } from './protocol.ts'\n\n/**\n * The four read-only tools of `rness mcp` (spec 0014 §2), over the\n * workspace found from `cwd`, and `rness_note` when a board keeps a\n * journal (spec 0030 §5). Everything is read again on each call: an\n * edit in `.rness/` shows at once. Text out, for a model to read.\n */\n\nconst LABELS: Record<CollectionName, string> = {\n standards: 'Standards',\n adr: 'Decisions',\n specs: 'Specifications',\n plans: 'Plans',\n skills: 'Skills',\n}\n/** The scaffold's ADR template is not a decision. */\nconst TEMPLATE = 'adr/0000-template.md'\nconst READ_LIMIT = 256 * 1024\nconst SEARCH_LIMIT = 20\nconst LINES_PER_HIT = 3\nconst LINE_WIDTH = 200\n\ninterface Doc {\n collection: CollectionName\n path: string\n scope: string | null\n id: string | null\n status: string | null\n title: string\n text: string\n}\n\ntype Result = { text: string; isError?: boolean }\nconst refuse = (text: string): Result => ({ text, isError: true })\n\n/** A failure (no workspace, an unreadable rness.json) is an answer too. */\nasync function guard(run: () => Promise<Result>): Promise<Result> {\n try {\n return await run()\n } catch (e) {\n return refuse(e instanceof Error ? e.message : String(e))\n }\n}\n\nasync function workspaceAt(\n cwd: string\n): Promise<{ ws: Workspace; manifest: Manifest }> {\n const ws = await findWorkspace(cwd)\n return { ws, manifest: await loadManifest(ws.rnessDir) }\n}\n\nasync function documents(\n rnessDir: string,\n only?: CollectionName\n): Promise<Doc[]> {\n const docs: Doc[] = []\n for (const collection of COLLECTIONS) {\n if (only !== undefined && collection !== only) continue\n for (const item of await collectMarkdown(join(rnessDir, collection))) {\n const path = `${collection}/${item.rel}`\n if (path === TEMPLATE) continue\n const status = item.fields?.['status']\n const id = documentNumber(item.rel)\n docs.push({\n collection,\n path,\n scope: ownerScope(item.rel),\n id,\n status: typeof status === 'string' ? status : null,\n title: documentTitle(item.title ?? posix.basename(item.rel, '.md'), id),\n text: item.body,\n })\n }\n }\n return docs\n}\n\nfunction line(d: Doc, withScope = false): string {\n const head = [d.id, d.status].filter((x) => x !== null).join(' ')\n return `- ${head === '' ? '' : `${head} — `}${d.title}${withScope ? ` — ${d.scope ?? 'global'}` : ''} — ${d.path}`\n}\n\nfunction isCollection(value: unknown): value is CollectionName {\n return (COLLECTIONS as readonly unknown[]).includes(value)\n}\n\nconst collectionError = (value: unknown): Result =>\n refuse(\n `unknown collection ${JSON.stringify(value)}; one of ${COLLECTIONS.join(', ')}`\n )\n\nasync function context(cwd: string, args: Record<string, unknown>) {\n const { ws, manifest } = await workspaceAt(cwd)\n let scope: string | null\n if (args['scope'] !== undefined) {\n const known = Object.keys(manifest.scopes).sort()\n if (\n typeof args['scope'] !== 'string' ||\n !Object.hasOwn(manifest.scopes, args['scope'])\n )\n return refuse(\n `unknown scope ${JSON.stringify(args['scope'])}; known: ${known.length === 0 ? 'none' : known.join(', ')}`\n )\n scope = args['scope']\n } else\n scope = resolveScope(\n manifest,\n relative(ws.root, cwd).split(sep).join(posix.sep)\n )\n const summary = await scopeSummary(ws, manifest, scope)\n return {\n text: [\n ...summary.lines,\n 'Read one with rness_read; search with rness_search.',\n ].join('\\n'),\n }\n}\n\n/** What applies to one scope, as `rness_context` and the session-start hook say it. */\nexport interface ScopeSummary {\n /** `scope web (org/web, extends platform)`, or `global scope`. */\n where: string\n /** The documents that apply, by collection; empty collections left out. */\n counts: Partial<Record<CollectionName, number>>\n /** The heading line, then each non-empty collection and its documents. */\n lines: string[]\n}\n\n/**\n * The documents that apply to `scope` (null: the global scope) — ids,\n * statuses, titles and paths, no bodies (spec 0014 §2).\n */\nexport async function scopeSummary(\n ws: Workspace,\n manifest: Manifest,\n scope: string | null\n): Promise<ScopeSummary> {\n const entry = scope === null ? undefined : manifest.scopes[scope]\n const where =\n scope === null || entry === undefined\n ? 'global scope'\n : `scope ${scope} (${entry.path}${entry.extends.length > 0 ? `, extends ${entry.extends.join(', ')}` : ''})`\n const ctx = await assembleContext({ rnessDir: ws.rnessDir, manifest, scope })\n const index = new Map(\n (await documents(ws.rnessDir)).map((d) => [d.path, d] as const)\n )\n const lines = [`Workspace ${workspaceName(manifest, ws.root)} · ${where}`]\n const counts: Partial<Record<CollectionName, number>> = {}\n for (const collection of ctx.collections) {\n const docs = collection.files\n .map((f) => index.get(`${collection.name}/${f.rel}`))\n .filter((d): d is Doc => d !== undefined)\n if (docs.length === 0) continue\n counts[collection.name] = docs.length\n lines.push(`${LABELS[collection.name]} (${docs.length}):`)\n for (const d of docs) lines.push(line(d))\n }\n return { where, counts, lines }\n}\n\nasync function list(cwd: string, args: Record<string, unknown>) {\n const { ws } = await workspaceAt(cwd)\n const collection = args['collection']\n if (!isCollection(collection)) return collectionError(collection)\n const status = args['status']\n const allowed = STATUSES[collection]\n if (status !== undefined) {\n if (allowed === undefined)\n return refuse(`${collection} have no status to filter on`)\n if (typeof status !== 'string' || !allowed.includes(status))\n return refuse(\n `unknown status ${JSON.stringify(status)} for ${collection}; one of ${allowed.join(', ')}`\n )\n }\n const docs = (await documents(ws.rnessDir, collection)).filter(\n (d) => status === undefined || d.status === status\n )\n if (docs.length === 0)\n return {\n text: `No document in ${collection}${status === undefined ? '' : ` with status ${String(status)}`}.`,\n }\n return {\n text: [\n `${LABELS[collection]} (${docs.length}):`,\n ...docs.map((d) => line(d, true)),\n ].join('\\n'),\n }\n}\n\nasync function read(cwd: string, args: Record<string, unknown>) {\n const { ws } = await workspaceAt(cwd)\n const path = args['path']\n if (typeof path !== 'string' || path.trim() === '')\n return refuse('path is required, relative to .rness/')\n const segments = path.split(/[\\\\/]/)\n if (\n isAbsolute(path) ||\n segments.includes('..') ||\n segments[0] === '.git' ||\n segments.includes('node_modules')\n )\n return refuse(\n `${path}: not a document of .rness/ (a relative path, no \"..\", nothing under .git/ or node_modules/)`\n )\n const root = await realpath(ws.rnessDir)\n let real: string\n try {\n real = await realpath(resolve(ws.rnessDir, path))\n } catch {\n return refuse(`${path}: no such file in .rness/`)\n }\n if (!real.startsWith(`${root}${sep}`))\n return refuse(`${path}: leads outside .rness/`)\n const info = await stat(real)\n if (!info.isFile()) return refuse(`${path}: not a file`)\n if (info.size > READ_LIMIT)\n return refuse(\n `${path}: ${info.size} bytes, over the 256 KiB rness_read returns`\n )\n return { text: await readFile(real, 'utf8') }\n}\n\nasync function search(cwd: string, args: Record<string, unknown>) {\n const { ws } = await workspaceAt(cwd)\n const query = args['query']\n if (typeof query !== 'string' || query.trim() === '')\n return refuse('query is required')\n const collection = args['collection']\n if (collection !== undefined && !isCollection(collection))\n return collectionError(collection)\n const needle = query.toLowerCase()\n const hits = (await documents(ws.rnessDir, collection))\n .map((d) => ({\n d,\n lines: d.text\n .split(/\\r?\\n/)\n .map((text, i) => ({ n: i + 1, text }))\n .filter((l) => l.text.toLowerCase().includes(needle)),\n }))\n .filter((h) => h.lines.length > 0)\n .sort(\n (a, b) =>\n b.lines.length - a.lines.length || a.d.path.localeCompare(b.d.path)\n )\n if (hits.length === 0)\n return { text: `No document matches ${JSON.stringify(query)}.` }\n const shown = hits.slice(0, SEARCH_LIMIT)\n const out = [\n `${hits.length} document${hits.length === 1 ? '' : 's'} match${hits.length === 1 ? 'es' : ''} ${JSON.stringify(query)}${hits.length > SEARCH_LIMIT ? ` (the ${SEARCH_LIMIT} most matching)` : ''}`,\n ]\n for (const h of shown) {\n out.push(line(h.d, true))\n for (const l of h.lines.slice(0, LINES_PER_HIT))\n out.push(` ${l.n}: ${l.text.trim().slice(0, LINE_WIDTH)}`)\n }\n return { text: out.join('\\n') }\n}\n\nconst collectionProperty = {\n type: 'string',\n enum: [...COLLECTIONS],\n description:\n 'standards (rules), adr (decisions), specs (specifications), plans, skills',\n}\n\nexport function mcpTools(cwd: string): McpTool[] {\n return [\n {\n name: 'rness_context',\n title: 'rness: what applies here',\n description:\n 'The rness scope of the current repository (or the one named) and what applies to it: the standards, decisions (ADRs), specifications and plans of that scope and of the scopes it extends — ids, statuses, titles and paths, no bodies. Start here, then read a document with rness_read.',\n inputSchema: {\n type: 'object',\n properties: {\n scope: {\n type: 'string',\n description:\n 'A scope of rness.json; default: the one owning the working directory',\n },\n },\n additionalProperties: false,\n },\n call: (args) => guard(() => context(cwd, args)),\n },\n {\n name: 'rness_list',\n title: 'rness: a collection',\n description:\n 'Every document of one collection of .rness/, across all scopes, with id, status, title, scope and path; optionally only those with a given status (for example the Accepted decisions).',\n inputSchema: {\n type: 'object',\n properties: {\n collection: collectionProperty,\n status: {\n type: 'string',\n description:\n 'adr: Proposed, Accepted, Rejected, Superseded; specs: Draft, Proposed, Approved, Implemented, Superseded, Rejected; plans: Draft, Ready, In progress, Blocked, Completed, Abandoned',\n },\n },\n required: ['collection'],\n additionalProperties: false,\n },\n call: (args) => guard(() => list(cwd, args)),\n },\n {\n name: 'rness_read',\n title: 'rness: read a document',\n description:\n 'One file of .rness/ as it is, by its path relative to .rness/ (as rness_context, rness_list and rness_search give it). Nothing outside .rness/.',\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'For example adr/0006-workspace.md',\n },\n },\n required: ['path'],\n additionalProperties: false,\n },\n call: (args) => guard(() => read(cwd, args)),\n },\n {\n name: 'rness_search',\n title: 'rness: search the context',\n description:\n 'Where a subject is decided, specified or planned: a case-insensitive search of the documents of .rness/, most matching first, with the matching lines.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Text to find' },\n collection: collectionProperty,\n },\n required: ['query'],\n additionalProperties: false,\n },\n call: (args) => guard(() => search(cwd, args)),\n },\n ]\n}\n\n/** The kinds of a note, as `rness note --kind` takes them. */\nconst NOTE_KINDS = ['approach', 'deviation', 'blocker', 'done']\n\n/** `rness_note`: the agent's journal, the server's one tool that writes. */\nfunction noteTool(cwd: string, githubApi?: string): McpTool {\n return {\n name: 'rness_note',\n title: \"rness: a note on the plan's issue\",\n description:\n \"A note of the agent's journal on the plan in progress, posted to GitHub: when you choose an approach, deviate from the plan, are blocked, and when done. Decisions and their reasons, not steps; a few per session. Returns the issue it went to (owner/repo#N), for the pull request to reference.\",\n inputSchema: {\n type: 'object',\n properties: {\n text: {\n type: 'string',\n description: 'Markdown, 1 to 4,000 characters',\n },\n kind: {\n type: 'string',\n enum: NOTE_KINDS,\n description: 'What the note titles itself; default approach',\n },\n plan: {\n type: 'string',\n description:\n 'The plan, relative to .rness/ (plans/0021-x.md); needed when several are in progress',\n },\n session: {\n type: 'string',\n description:\n 'The session, as the session start spells it: claude · 1a2b3c4d',\n },\n },\n required: ['text', 'session'],\n additionalProperties: false,\n },\n call: (args) =>\n guard(async () => {\n const { postNote } = await import('../commands/note.ts')\n const given = (key: string): string | undefined => {\n const value = args[key]\n return typeof value === 'string' ? value : undefined\n }\n const kind = given('kind')\n const plan = given('plan')\n const posted = await postNote({\n cwd,\n text: given('text') ?? '',\n session: given('session') ?? '',\n // The server's environment names no session: only the argument does.\n env: {},\n ...(kind === undefined ? {} : { kind }),\n ...(plan === undefined ? {} : { plan }),\n ...(githubApi === undefined ? {} : { githubApi }),\n })\n return { text: posted.reference }\n }),\n }\n}\n\n/** What `rness mcp` serves: the four tools, and `rness_note` when a valid board declares `journal`. */\nexport async function serverTools(\n cwd: string,\n /** Internal (tests): GitHub API base. */\n githubApi?: string\n): Promise<McpTool[]> {\n let journal = false\n try {\n const ws = await findWorkspace(cwd)\n journal = (await readBoards(ws.rnessDir)).some((b) =>\n (b.declaration.hooks['session-start'] ?? []).some(\n (a) => a.action === 'journal'\n )\n )\n } catch {\n // No workspace: the four tools say so.\n }\n return [...mcpTools(cwd), ...(journal ? [noteTool(cwd, githubApi)] : [])]\n}\n","import { type OptionColor, optionColor } from '../board/layout.ts'\nimport { boardUrl, itemUrl } from '../board/urls.ts'\nimport type { BoardDeclaration } from '../core/board-declaration.ts'\nimport { COLLECTIONS } from '../core/context.ts'\nimport { PULSE, workspaceName } from '../core/manifest.ts'\nimport { declaredBoard } from '../core/preset-board.ts'\nimport { currentPreset, presetTemplate } from '../core/presets.ts'\nimport { safetyNet } from '../core/safety-net.ts'\nimport {\n type StatusRow,\n type StatusTab,\n plansInProgress,\n} from '../core/status.ts'\nimport { count } from '../core/style.ts'\nimport type { CollectionName, Manifest, Workspace } from '../core/types.ts'\nimport { scopeSummary } from '../mcp/tools.ts'\nimport { VERSION } from '../version.ts'\n\n/**\n * What a Claude Code session shows of the workspace: the session-start\n * hook's banner (spec 0015 §3), and the snapshot `rness status --json`\n * hands the plugin's mod (spec 0029 §3.2). Shared by both commands so the\n * two say the same words.\n */\n\nconst NOUNS: Record<CollectionName, [string, string]> = {\n standards: ['standard', 'standards'],\n adr: ['decision', 'decisions'],\n specs: ['specification', 'specifications'],\n plans: ['plan', 'plans'],\n skills: ['skill', 'skills'],\n}\n\n/** The banner and the scope's summary for the model. */\nexport async function scopeBanner(\n ws: Workspace,\n manifest: Manifest,\n scope: string | null\n): Promise<{ banner: string; lines: string[] }> {\n const summary = await scopeSummary(ws, manifest, scope)\n const counts = COLLECTIONS.flatMap((c) => {\n const n = summary.counts[c]\n return n === undefined ? [] : [count(n, NOUNS[c])]\n })\n const banner = `rness ${VERSION} · ${workspaceName(manifest, ws.root)} · ${scope === null ? 'global scope' : `scope ${scope}`} — ${counts.length === 0 ? 'nothing applies yet' : counts.join(', ')}`\n return { banner, lines: summary.lines }\n}\n\n/** The safety net's notes, each a line of its own, as the hooks print them. */\nexport const noteLines = (notes: readonly string[]): string[] =>\n notes.map((n) => `rness: ${n}`)\n\n/**\n * The workspace's label in the prompt footer (spec 0029 §3.3, plan 0044):\n * `rness`, the scope, the plans in progress, and the notes to act on,\n * counted. A note's indented detail lines do not count. The mod adds it to\n * the session modes (`focus`, `memory paused`), which carry no plugin name,\n * so the word `rness` is part of it.\n */\nexport function statusLine(\n scope: string | null,\n inProgress: readonly string[],\n notes: readonly string[]\n): string {\n const acting = notes.filter((n) => !n.startsWith(' ')).length\n return `rness · ${scope ?? 'global'} · ${inProgress.length} in progress${acting > 0 ? ` · ⚠ ${acting}` : ''}`\n}\n\n/** A row of a tab as the mod draws it: the document, its colour, its item. */\nexport interface SnapshotRow extends StatusRow {\n /**\n * The colour of its status on Agent Pulse (spec 0017 §3: `yellow` for\n * `In progress`, `green` for `Completed`, …), by the board's neutral name;\n * `red` without a status, as the full-screen view marks `?`.\n */\n color: OptionColor\n /**\n * The document's item on Agent Pulse: the board filtered on its `Path`.\n * Null while the workspace declares no board.\n */\n link: string | null\n}\n\nexport interface SnapshotTab {\n name: string\n label: string\n rows: SnapshotRow[]\n}\n\n/** What `rness status --json` prints: everything the mod draws, worded here. */\nexport interface StatusSnapshot {\n version: string\n workspace: string\n scope: string | null\n banner: string\n statusLine: string\n /** The scope's plans In progress, `.rness/`-relative. */\n inProgress: string[]\n /** The safety net's lines, `rness: `-prefixed. */\n notes: string[]\n /** Agent Pulse, the board (spec 0017); null while none is declared. */\n pulse: string | null\n tabs: SnapshotTab[]\n}\n\n/** A board of `boards`, read whole: its name and its declaration. */\nexport interface SnapshotBoard {\n name: string\n declaration: BoardDeclaration\n}\n\n/** The declared boards, read whole; one whose README cannot be read is left out. */\nasync function boardsOf(\n manifest: Manifest,\n rnessDir: string\n): Promise<SnapshotBoard[]> {\n const boards: SnapshotBoard[] = []\n for (const [name, entry] of Object.entries(manifest.boards ?? {}))\n try {\n boards.push({\n name,\n declaration: await declaredBoard(name, entry, rnessDir),\n })\n } catch {\n // `sync` and `validate` say why; the pane shows the rest.\n }\n return boards\n}\n\n/** The board that holds a collection: the one naming it, else one that takes all. */\nconst holderOf = (\n boards: readonly SnapshotBoard[],\n collection: string\n): SnapshotBoard | undefined =>\n boards.find(\n (b) =>\n b.declaration.collections !== 'all' &&\n Object.hasOwn(b.declaration.collections, collection)\n ) ?? boards.find((b) => b.declaration.collections === 'all')\n\n/** The colours of a status nobody declares: Agent Pulse's, as rness ships it. */\nconst SHIPPED_COLORS = presetTemplate(currentPreset('agent-pulse'), {\n collection: PULSE,\n})['colors'] as Record<string, OptionColor>\n\n/**\n * The board of the pane's link: the one that takes all, else the first,\n * among those the provider has; a board not created yet has no link.\n */\nfunction pulseOf(\n org: string | null,\n boards: readonly SnapshotBoard[]\n): string | null {\n const created = boards.filter((b) => b.declaration.number !== null)\n const main =\n created.find((b) => b.declaration.collections === 'all') ?? created[0]\n return org === null || main?.declaration.number == null\n ? null\n : boardUrl(org, main.declaration.number)\n}\n\n/**\n * The tabs with each row's colour and item, from the board that holds its\n * collection (spec 0031): its declared colour for the status, its item.\n */\nexport function snapshotTabs(\n tabs: readonly StatusTab[],\n org: string | null,\n boards: readonly SnapshotBoard[]\n): SnapshotTab[] {\n return tabs.map((tab) => {\n const holder = holderOf(boards, tab.name)\n const colors = holder?.declaration.colors ?? SHIPPED_COLORS\n return {\n name: tab.name,\n label: tab.label,\n rows: tab.rows.map((row) => ({\n ...row,\n color:\n row.status === null\n ? 'red'\n : (optionColor(colors, 'status', row.status) ?? 'gray'),\n link:\n org === null || holder?.declaration.number == null\n ? null\n : itemUrl(org, holder.declaration.number, row.path),\n })),\n }\n })\n}\n\nexport async function statusSnapshot(\n ws: Workspace,\n manifest: Manifest,\n scope: string | null,\n tabs: StatusTab[]\n): Promise<StatusSnapshot> {\n const { banner } = await scopeBanner(ws, manifest, scope)\n const inProgress = await plansInProgress(ws, manifest, scope)\n const notes = await safetyNet(ws, manifest)\n const boards = await boardsOf(manifest, ws.rnessDir)\n return {\n version: VERSION,\n workspace: workspaceName(manifest, ws.root),\n scope,\n banner,\n statusLine: statusLine(scope, inProgress, notes),\n inProgress,\n notes: noteLines(notes),\n pulse: pulseOf(manifest.org, boards),\n tabs: snapshotTabs(tabs, manifest.org, boards),\n }\n}\n","import { createInterface } from 'node:readline'\nimport type { Readable, Writable } from 'node:stream'\n\nimport { createProtocol } from '../mcp/protocol.ts'\nimport { serverTools } from '../mcp/tools.ts'\nimport { VERSION } from '../version.ts'\n\nexport interface McpOptions {\n /** Internal (tests): directory to resolve from; default `process.cwd()`. */\n cwd?: string\n}\n\n/**\n * `rness mcp`: the workspace context for agents, over MCP on stdio\n * (spec 0014). One message per line in, one answer per line out; stdout\n * carries nothing else. Ends when stdin closes.\n */\nexport async function mcpCommand(\n opts: McpOptions,\n io: { input: Readable; output: Writable } = {\n input: process.stdin,\n output: process.stdout,\n }\n): Promise<number> {\n const protocol = createProtocol({\n name: 'rness',\n version: VERSION,\n tools: await serverTools(opts.cwd ?? process.cwd()),\n })\n const lines = createInterface({ input: io.input, crlfDelay: Infinity })\n for await (const line of lines) {\n if (line.trim() === '') continue\n const answer = await protocol.handle(line)\n if (answer !== null) io.output.write(`${answer}\\n`)\n }\n return 0\n}\n","/**\n * The part of MCP `rness mcp` speaks (spec 0014 §1): JSON-RPC 2.0, one\n * message per line, tools only. Both generations of the protocol: the\n * current revision, where every request carries its version and the client's\n * capabilities in `_meta`, and the earlier ones that open with `initialize`.\n * Knows nothing of rness: tools come in, lines go out.\n */\n\nexport interface McpTool {\n name: string\n title: string\n description: string\n inputSchema: Record<string, unknown>\n /** A refusal the model can act on is `isError: true`, not a throw. */\n call(\n args: Record<string, unknown>\n ): Promise<{ text: string; isError?: boolean }>\n}\n\n/** Checked against the MCP specification on 2026-09-29. */\nconst MODERN_VERSIONS: readonly string[] = ['2026-07-28']\nconst LEGACY_VERSIONS: readonly string[] = [\n '2025-11-25',\n '2025-06-18',\n '2025-03-26',\n '2024-11-05',\n]\nconst SUPPORTED = [...MODERN_VERSIONS, ...LEGACY_VERSIONS]\n\nconst VERSION_KEY = 'io.modelcontextprotocol/protocolVersion'\nconst CAPABILITIES_KEY = 'io.modelcontextprotocol/clientCapabilities'\nconst SERVER_INFO_KEY = 'io.modelcontextprotocol/serverInfo'\n\ntype Json = Record<string, unknown>\ntype Id = string | number | null\n\nfunction isObject(value: unknown): value is Json {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction errorLine(\n id: Id,\n code: number,\n message: string,\n data?: unknown\n): string {\n return JSON.stringify({\n jsonrpc: '2.0',\n id,\n error: data === undefined ? { code, message } : { code, message, data },\n })\n}\n\nexport function createProtocol(opts: {\n name: string\n version: string\n tools: readonly McpTool[]\n}): { handle(line: string): Promise<string | null> } {\n const serverInfo = { name: opts.name, version: opts.version }\n\n return {\n async handle(line: string): Promise<string | null> {\n let message: unknown\n try {\n message = JSON.parse(line)\n } catch {\n return errorLine(null, -32700, 'Parse error')\n }\n const rawId = isObject(message) ? message['id'] : undefined\n const id: Id =\n typeof rawId === 'string' || typeof rawId === 'number' ? rawId : null\n if (\n !isObject(message) ||\n message['jsonrpc'] !== '2.0' ||\n typeof message['method'] !== 'string'\n )\n return errorLine(id, -32600, 'Invalid Request')\n // A notification has no id and gets no answer, whatever it says.\n if (!('id' in message)) return null\n if (id === null) return errorLine(null, -32600, 'Invalid Request')\n\n const method = message['method']\n const params = isObject(message['params']) ? message['params'] : {}\n const meta = isObject(params['_meta']) ? params['_meta'] : null\n const modern = meta !== null && typeof meta[VERSION_KEY] === 'string'\n if (modern) {\n const requested = meta[VERSION_KEY] as string\n if (!MODERN_VERSIONS.includes(requested))\n return errorLine(id, -32022, 'Unsupported protocol version', {\n supported: SUPPORTED,\n requested,\n })\n if (!isObject(meta[CAPABILITIES_KEY]))\n return errorLine(\n id,\n -32602,\n `Invalid params: ${CAPABILITIES_KEY} is required`\n )\n }\n const answer = (result: Json): string =>\n JSON.stringify({\n jsonrpc: '2.0',\n id,\n result: modern\n ? {\n resultType: 'complete',\n ...result,\n _meta: { [SERVER_INFO_KEY]: serverInfo },\n }\n : result,\n })\n\n switch (method) {\n case 'server/discover':\n return answer({\n supportedVersions: SUPPORTED,\n capabilities: { tools: {} },\n })\n case 'initialize': {\n const asked = params['protocolVersion']\n const protocolVersion =\n typeof asked === 'string' && LEGACY_VERSIONS.includes(asked)\n ? asked\n : (LEGACY_VERSIONS[0] as string)\n return JSON.stringify({\n jsonrpc: '2.0',\n id,\n result: {\n protocolVersion,\n capabilities: { tools: {} },\n serverInfo,\n },\n })\n }\n case 'ping':\n return answer({})\n case 'tools/list':\n return answer({\n tools: opts.tools.map((t) => ({\n name: t.name,\n title: t.title,\n description: t.description,\n inputSchema: t.inputSchema,\n })),\n })\n case 'tools/call': {\n const name = params['name']\n const tool = opts.tools.find((t) => t.name === name)\n if (tool === undefined)\n return errorLine(id, -32602, `Unknown tool: ${String(name)}`)\n const args = isObject(params['arguments']) ? params['arguments'] : {}\n try {\n const r = await tool.call(args)\n return answer({\n content: [{ type: 'text', text: r.text }],\n isError: r.isError === true,\n })\n } catch (e) {\n return answer({\n content: [\n {\n type: 'text',\n text: `${tool.name} failed: ${e instanceof Error ? e.message : String(e)}`,\n },\n ],\n isError: true,\n })\n }\n }\n default:\n return errorLine(id, -32601, 'Method not found')\n }\n },\n }\n}\n","import { posix, relative, sep } from 'node:path'\nimport { emitKeypressEvents } from 'node:readline'\n\nimport { loadManifest, workspaceName } from '../core/manifest.ts'\nimport { resolveScope } from '../core/scope.ts'\nimport {\n type Key,\n type Look,\n type View,\n clampView,\n pageSize,\n press,\n renderView,\n} from '../core/status-view.ts'\nimport {\n type StatusTab,\n findTab,\n statusMarkdown,\n statusTabs,\n} from '../core/status.ts'\nimport { bold, grey, inverse, paint } from '../core/style.ts'\nimport { findWorkspace } from '../core/workspace.ts'\nimport { reportError } from '../report.ts'\nimport { statusSnapshot } from './snapshot.ts'\n\nexport interface StatusOptions {\n /** Internal (tests, the Claude skill): directory to resolve from; default `process.cwd()`. */\n cwd?: string\n /** One JSON object, what the Claude Code mod draws (spec 0029 §3.2), terminal or not. */\n json?: boolean\n}\n\n/** The terminal the view takes: the process's own, a fake one in tests. */\nexport interface StatusTerminal {\n input: NodeJS.ReadStream\n output: NodeJS.WriteStream\n}\n\nconst ENTER = '\\x1b[?1049h\\x1b[?25l' // alternate screen, cursor hidden\nconst LEAVE = '\\x1b[?25h\\x1b[?1049l' // cursor shown, the screen as it was\n\nfunction lookFor(output: NodeJS.WriteStream): Look {\n return {\n bold: (text) => bold(text, output),\n dim: (text) => grey(text, output),\n inverse: (text) => inverse(text, output),\n tone: (tone, text) =>\n tone === 'done'\n ? paint('done', text, output)\n : tone === 'dropped'\n ? grey(text, output)\n : tone === 'missing'\n ? paint('error', text, output)\n : paint('warn', text, output),\n }\n}\n\ninterface Keypress {\n name?: string\n ctrl?: boolean\n shift?: boolean\n}\n\nconst MOVES: ReadonlySet<string> = new Set([\n 'left',\n 'right',\n 'up',\n 'down',\n 'pageup',\n 'pagedown',\n 'home',\n 'end',\n])\n\n/** A keypress as the view reads it, `close`, or nothing it knows. */\nfunction keyOf(key: Keypress | undefined): Key | 'close' | null {\n const name = key?.name\n if (name === undefined) return null\n if (name === 'q' || name === 'escape' || (key?.ctrl === true && name === 'c'))\n return 'close'\n if (name === 'tab') return key?.shift === true ? 'backtab' : 'tab'\n return MOVES.has(name) ? (name as Key) : null\n}\n\n/**\n * The view (spec 0016 §2.2): the alternate screen, raw keys, a redraw on\n * each key and each resize. Resolves when closed, the terminal restored —\n * also when drawing throws.\n */\nfunction showView(\n tabs: readonly StatusTab[],\n workspace: string,\n start: number,\n { input, output }: StatusTerminal\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const look = lookFor(output)\n let view: View = { tab: start, top: 0 }\n const rows = (): number => output.rows || 24\n const draw = (): void => {\n view = clampView(view, tabs, pageSize(rows()))\n const lines = renderView(\n view,\n tabs,\n workspace,\n output.columns || 80,\n rows(),\n look\n )\n output.write(`\\x1b[H${lines.map((l) => `${l}\\x1b[K`).join('\\r\\n')}\\x1b[J`)\n }\n const restore = (): void => {\n output.write(LEAVE)\n }\n const close = (error?: unknown): void => {\n input.off('keypress', onKey)\n output.off('resize', onResize)\n process.off('exit', restore)\n input.setRawMode(false)\n input.pause()\n restore()\n if (error === undefined) resolve()\n else reject(error)\n }\n const guarded = (step: () => void): void => {\n try {\n step()\n } catch (e) {\n close(e)\n }\n }\n const onKey = (_: string | undefined, key: Keypress | undefined): void => {\n const k = keyOf(key)\n if (k === 'close') close()\n else if (k !== null)\n guarded(() => {\n view = press(view, k, tabs, pageSize(rows()))\n draw()\n })\n }\n const onResize = (): void => {\n guarded(draw)\n }\n emitKeypressEvents(input)\n input.setRawMode(true)\n input.resume()\n output.write(ENTER)\n // Should the process end another way, the shell gets its screen back.\n process.on('exit', restore)\n input.on('keypress', onKey)\n output.on('resize', onResize)\n guarded(draw)\n })\n}\n\n/**\n * `rness status [tab]`: every tracked document of `.rness/` and its status,\n * a tab per directory (spec 0016). In a terminal, a view to move around;\n * off one, Markdown. Read-only.\n */\nexport async function statusCommand(\n tab: string | undefined,\n opts: StatusOptions,\n terminal: StatusTerminal = { input: process.stdin, output: process.stdout }\n): Promise<number> {\n try {\n const cwd = opts.cwd ?? process.cwd()\n const ws = await findWorkspace(cwd)\n const manifest = await loadManifest(ws.rnessDir)\n const workspace = workspaceName(manifest, ws.root)\n const tabs = await statusTabs(ws.rnessDir)\n const wanted = tab === undefined ? undefined : findTab(tabs, tab)\n if (tab !== undefined && wanted === undefined) {\n process.stderr.write(\n `unknown tab \"${tab}\" (tabs: ${tabs.map((t) => t.name).join(', ')})\\n`\n )\n return 2\n }\n const shown = wanted === undefined ? tabs : [wanted]\n if (opts.json === true) {\n const scope = resolveScope(\n manifest,\n relative(ws.root, cwd).split(sep).join(posix.sep)\n )\n terminal.output.write(\n `${JSON.stringify(await statusSnapshot(ws, manifest, scope, shown))}\\n`\n )\n return 0\n }\n if (terminal.input.isTTY === true && terminal.output.isTTY === true) {\n await showView(\n tabs,\n workspace,\n wanted === undefined ? 0 : tabs.indexOf(wanted),\n terminal\n )\n return 0\n }\n terminal.output.write(statusMarkdown(workspace, shown))\n return 0\n } catch (e) {\n return reportError(e)\n }\n}\n","import { type StatusTab, type StatusTone, statusTone } from './status.ts'\n\n/**\n * The view of `rness status` in a terminal (spec 0016 §2.2), as pure\n * functions: a key moves the view, a view at a size is a list of lines. The\n * terminal — alternate screen, raw mode, keypresses — is the command's.\n */\n\nexport interface View {\n /** The active tab. */\n tab: number\n /** The first row shown. */\n top: number\n}\n\nexport type Key =\n | 'left'\n | 'right'\n | 'tab'\n | 'backtab'\n | 'up'\n | 'down'\n | 'pageup'\n | 'pagedown'\n | 'home'\n | 'end'\n\n/** How text is styled: ANSI in a terminal, the identity in tests. */\nexport interface Look {\n bold(text: string): string\n dim(text: string): string\n inverse(text: string): string\n tone(tone: StatusTone, text: string): string\n}\n\n/** Lines around the rows: the name, the tabs, a rule — a rule, the footer. */\nconst FRAME = 5\n\n/** The rows a terminal of `height` lines shows: one at least. */\nexport function pageSize(height: number): number {\n return Math.max(1, height - FRAME)\n}\n\nfunction lastTop(tab: StatusTab | undefined, page: number): number {\n return Math.max(0, (tab?.rows.length ?? 0) - page)\n}\n\n/** `view` moved by `key`: tabs wrap and start at the top; scrolling stops at the ends. */\nexport function press(\n view: View,\n key: Key,\n tabs: readonly StatusTab[],\n page: number\n): View {\n const n = tabs.length\n if (key === 'right' || key === 'tab')\n return { tab: (view.tab + 1) % n, top: 0 }\n if (key === 'left' || key === 'backtab')\n return { tab: (view.tab - 1 + n) % n, top: 0 }\n const moved: Record<string, number> = {\n up: view.top - 1,\n down: view.top + 1,\n pageup: view.top - page,\n pagedown: view.top + page,\n home: 0,\n end: Number.MAX_SAFE_INTEGER,\n }\n const top = moved[key] ?? view.top\n return {\n tab: view.tab,\n top: Math.min(Math.max(0, top), lastTop(tabs[view.tab], page)),\n }\n}\n\n/** The view kept in range after a resize changed the page. */\nexport function clampView(\n view: View,\n tabs: readonly StatusTab[],\n page: number\n): View {\n return {\n tab: view.tab,\n top: Math.min(view.top, lastTop(tabs[view.tab], page)),\n }\n}\n\n// --- rendering ---------------------------------------------------------------\n\n/** A piece of a line and how to style it once cut. */\ntype Segment = readonly [text: string, style?: (text: string) => string]\n\nconst width = (text: string): number => [...text].length\n\n/** `text` in `n` columns: cut with `…` when longer, padded when shorter. */\nfunction fit(text: string, n: number): string {\n if (n <= 0) return ''\n const chars = [...text]\n if (chars.length <= n) return text + ' '.repeat(n - chars.length)\n return `${chars\n .slice(0, n - 1)\n .join('')\n .trimEnd()}…`.padEnd(n)\n}\n\n/** The segments cut to `columns`, then styled: a style never spans a cut. */\nfunction line(segments: readonly Segment[], columns: number): string {\n let left = columns\n let out = ''\n for (const [text, style] of segments) {\n if (left <= 0) break\n const chars = [...text]\n const kept = chars.length <= left ? text : chars.slice(0, left).join('')\n left -= width(kept)\n out += style === undefined ? kept : style(kept)\n }\n return out\n}\n\nfunction tabBar(\n tabs: readonly StatusTab[],\n active: number,\n look: Look\n): Segment[] {\n const segments: Segment[] = [[' ']]\n tabs.forEach((tab, i) => {\n if (i > 0) segments.push([' '])\n const label = ` ${tab.label} (${tab.rows.length}) `\n segments.push(i === active ? [label, look.inverse] : [label])\n })\n return segments\n}\n\nfunction rowLines(\n tab: StatusTab | undefined,\n top: number,\n page: number,\n columns: number,\n look: Look\n): Segment[][] {\n if (tab === undefined || tab.rows.length === 0)\n return [[[' Nothing here yet.', look.dim]]]\n const idWidth = Math.max(...tab.rows.map((r) => width(r.id)))\n const statusWidth = Math.max(...tab.rows.map((r) => width(r.status ?? '?')))\n // Two spaces before each column, one free at the right edge.\n const titleWidth = Math.max(\n 1,\n columns - 1 - (2 + idWidth + 2 + 2 + statusWidth)\n )\n return tab.rows\n .slice(top, top + page)\n .map((row) => [\n [' '],\n [row.id.padEnd(idWidth)],\n [' '],\n [fit(row.title, titleWidth)],\n [' '],\n [\n (row.status ?? '?').padEnd(statusWidth),\n (text) => look.tone(statusTone(row.status), text),\n ],\n ])\n}\n\n/** The footer: what is out of sight, then the keys. */\nfunction footer(above: number, below: number): string {\n const parts = [\n ...(above > 0 ? [`↑ ${above} above`] : []),\n ...(below > 0 ? [`↓ ${below} more`] : []),\n '←/→ tab · ↑/↓ scroll · q close',\n ]\n return ` ${parts.join(' · ')}`\n}\n\n/** The whole screen for `view`, `columns` wide and at most `height` lines. */\nexport function renderView(\n view: View,\n tabs: readonly StatusTab[],\n workspace: string,\n columns: number,\n height: number,\n look: Look\n): string[] {\n const page = pageSize(height)\n const tab = tabs[view.tab]\n const rule: Segment[] = [[` ${'─'.repeat(Math.max(0, columns - 2))}`]]\n const rows = rowLines(tab, view.top, page, columns, look)\n const shown = Math.min(page, rows.length)\n const total = tab?.rows.length ?? 0\n const lines: Segment[][] = [\n [[` rness · ${workspace}`, look.bold]],\n tabBar(tabs, view.tab, look),\n rule,\n ...rows,\n ...Array.from({ length: page - shown }, (): Segment[] => [['']]),\n rule,\n [[footer(view.top, Math.max(0, total - view.top - page)), look.dim]],\n ]\n return lines.slice(0, Math.max(0, height)).map((l) => line(l, columns))\n}\n","import { writtenFiles } from '../core/agent-targets.ts'\nimport { loadManifest } from '../core/manifest.ts'\nimport { findWorkspace } from '../core/workspace.ts'\n\n/**\n * Hidden, for `upgrade` (a fix to spec 0013 §8): the files this copy's sync\n * writes in a clone, as a JSON array. The copy that runs an upgrade asks the\n * one it just installed, whose release may write files it does not know.\n */\nexport async function writtenFilesCommand(opts: {\n cwd?: string\n}): Promise<number> {\n try {\n const ws = await findWorkspace(opts.cwd ?? process.cwd())\n const manifest = await loadManifest(ws.rnessDir)\n process.stdout.write(`${JSON.stringify(writtenFiles(manifest))}\\n`)\n return 0\n } catch (e) {\n process.stderr.write(`${e instanceof Error ? e.message : String(e)}\\n`)\n return 1\n }\n}\n","import { spawnSync } from 'node:child_process'\n\nimport { pinnedBinPath } from './delegate.ts'\nimport {\n type EnsureOptions,\n driftWarning,\n ensureInstalled,\n pinDrift,\n} from './pinned.ts'\nimport { findWorkspace } from './workspace.ts'\n\n/**\n * `create` makes a workspace and `upgrade` replaces the pinned copy: both are\n * served by the copy the user invoked (spec 0006 §3). The login concerns the\n * machine, not a workspace — and git runs `git-credential` from inside a\n * clone, on every fetch: no delegation, no install and no warning there.\n * Claude Code runs `hook` at every session start and after every edit, and\n * it is already the pinned copy: a drift is reported, never installed (spec\n * 0015 §3).\n */\nexport const OWN_COMMANDS: readonly string[] = [\n 'create',\n 'upgrade',\n 'update',\n 'login',\n 'logout',\n 'git-credential',\n 'hook',\n]\n\n/**\n * Set in the environment once an invocation has looked at the drift. Two\n * copies can look in one invocation — the launcher, then the installed copy it\n * delegates to — and they are different modules, in one process or in a child:\n * the environment is the only state they share. Private, not a user setting.\n */\nexport const CATCH_UP_DONE = 'RNESS_CATCH_UP_DONE'\n\nexport interface CatchUpDeps {\n cwd?: string\n env?: NodeJS.ProcessEnv\n stderr?: (text: string) => void\n install?: EnsureOptions['install']\n /** Run the installed bin with the user's arguments; its exit code. */\n spawn?: (bin: string, argv: string[], cwd: string) => number\n}\n\n/**\n * Close the gap between the pin and what is installed, then hand the command\n * to the freshly installed copy (spec 0008 §4). Returns that copy's exit code,\n * or null when the caller should run the command itself: no workspace, no\n * drift, nothing to do for this command, or an install that did not close the\n * drift (reported as a warning).\n *\n * It runs in two places. The launcher calls it before delegating. The\n * package's exported `run` calls it too, because a launcher older than 0.5.1\n * never does: it imports the installed copy's `run` and knows nothing about\n * drift. Everything on this path is imported statically — after the install,\n * the tree this module was loaded from may be gone.\n */\nexport async function catchUp(\n argv: string[],\n deps: CatchUpDeps = {}\n): Promise<number | null> {\n const env = deps.env ?? process.env\n const cwd = deps.cwd ?? process.cwd()\n const command = argv[0]\n if (\n command === undefined ||\n command.startsWith('-') ||\n OWN_COMMANDS.includes(command) ||\n env['RNESS_NO_DELEGATE'] === '1' ||\n env[CATCH_UP_DONE] === '1'\n )\n return null\n const ws = await findWorkspace(cwd).catch(() => null)\n if (ws === null) return null\n env[CATCH_UP_DONE] = '1'\n\n const stderr = deps.stderr ?? ((text) => void process.stderr.write(text))\n // The version was decided by the pull request that moved the pin, so\n // catching up asks nothing.\n const outcome = await ensureInstalled(ws.rnessDir, {\n env,\n announce: (pin) => stderr(`installing @rness/cli ${pin} in .rness…\\n`),\n ...(deps.install === undefined ? {} : { install: deps.install }),\n })\n if (outcome === null) return null\n if (!outcome.installed) {\n const warning = await driftWarning(cwd)\n if (warning !== null) stderr(`${warning}\\n`)\n return null\n }\n // Only hand off when the install actually closed the drift: a child that\n // would install again on every run must never be spawned.\n if ((await pinDrift(ws.rnessDir)) !== null) return null\n const bin = await pinnedBinPath(ws.rnessDir)\n if (bin === null) return null\n // The pinned tree was just rebuilt: importing out of it in this process is\n // fragile, so the freshly installed copy runs as its own process.\n const spawn =\n deps.spawn ??\n ((file, args, dir) =>\n spawnSync(process.execPath, [file, ...args], {\n cwd: dir,\n env,\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AACpD,MAAI,OAAO,KAAM,QAAO;AACxB,MAAI,aAAa,IAAI;AAErB,QAAM,SAAS,KAAK,WAAW,CAAC,SAAS,KAAK,QAAQ,OAAO,MAAM,IAAI;AAGvE,QAAM,UAAU,MAAM,gBAAgB,GAAG,UAAU;AAAA,IACjD;AAAA,IACA,UAAU,CAAC,QAAQ,OAAO,yBAAyB,GAAG;AAAA,CAAe;AAAA,IACrE,GAAI,KAAK,YAAY,SAAY,CAAC,IAAI,EAAE,SAAS,KAAK,QAAQ;AAAA,EAChE,CAAC;AACD,MAAI,YAAY,KAAM,QAAO;AAC7B,MAAI,CAAC,QAAQ,WAAW;AACtB,UAAM,UAAU,MAAM,aAAa,GAAG;AACtC,QAAI,YAAY,KAAM,QAAO,GAAG,OAAO;AAAA,CAAI;AAC3C,WAAO;AAAA,EACT;AAGA,MAAK,MAAM,SAAS,GAAG,QAAQ,MAAO,KAAM,QAAO;AACnD,QAAM,MAAM,MAAM,cAAc,GAAG,QAAQ;AAC3C,MAAI,QAAQ,KAAM,QAAO;AAGzB,QAAMC,SACJ,KAAK,UACJ,CAAC,MAAM,MAAM,QACZ,UAAU,QAAQ,UAAU,CAAC,MAAM,GAAG,IAAI,GAAG;AAAA,IAC3C,KAAK;AAAA,IACL;AAAA,IACA,OAAO;AAAA,EACT,CAAC,EAAE,UAAU;AACjB,SAAOA,OAAM,KAAK,MAAM,GAAG;AAC7B;","names":["resolve","finish","stderr","declared","context","line","header","join","line","join","join","dirname","join","join","join","run","readFile","join","readFile","join","declared","line","join","dirname","join","cancelled","context","basename","join","basename","join","statSync","dirname","join","fileURLToPath","mkdir","readFile","dirname","join","join","readFile","mkdir","dirname","mkdir","mkdtemp","rm","tmpdir","join","relative","resolve","resolve","mkdir","rm","stat","dirname","join","relative","execFile","rm","writeFile","dirname","join","promisify","execFileP","message","status","line","relative","dirname","join","stat","mkdir","rm","line","mkdir","join","relative","resolve","resolve","relative","mkdir","join","line","firstLine","list","join","message","code","resolve","relative","mkdtemp","tmpdir","mkdir","failures","name","rness","next","line","rm","join","status","message","join","context","execFile","mkdtemp","readFile","rm","tmpdir","basename","join","relative","promisify","execFileP","promisify","execFile","inside","join","mkdtemp","tmpdir","rm","readFile","relative","message","line","basename","stat","join","stat","isCollection","join","mkdir","readFile","writeFile","join","join","readFile","writeFile","mkdir","number","status","line","realpath","isAbsolute","posix","relative","resolve","sep","mkdir","readFile","join","join","readFile","mkdir","line","readFile","realpath","stat","join","posix","relative","resolve","sep","run","join","status","posix","relative","sep","realpath","resolve","stat","readFile","banner","message","sep","posix","boardsOf","clone","banner","context","relative","isAbsolute","resolve","realpath","refuse","isObject","message","line","line","posix","relative","sep","line","resolve","relative","sep","posix","run","spawn"]}
|