@toon-protocol/rig 2.1.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +92 -13
- package/dist/{chunk-PLKZAUTG.js → chunk-3HRFDH7H.js} +160 -6
- package/dist/chunk-3HRFDH7H.js.map +1 -0
- package/dist/{chunk-3EKP7PMM.js → chunk-OIJNRACA.js} +5 -144
- package/dist/chunk-OIJNRACA.js.map +1 -0
- package/dist/{chunk-O6TXHKWG.js → chunk-SW7ZHMGS.js} +143 -2
- package/dist/chunk-SW7ZHMGS.js.map +1 -0
- package/dist/{chunk-LFGDLD6J.js → chunk-W2SDL2PE.js} +464 -4
- package/dist/chunk-W2SDL2PE.js.map +1 -0
- package/dist/cli/rig.js +1954 -163
- package/dist/cli/rig.js.map +1 -1
- package/dist/index.d.ts +277 -3
- package/dist/index.js +50 -8
- package/dist/{publisher-Cdr1H1hg.d.ts → publisher-BtVceNeI.d.ts} +39 -3
- package/dist/standalone/index.d.ts +7 -1
- package/dist/standalone/index.js +9 -9
- package/dist/{standalone-mode-FCKTQ33Y.js → standalone-mode-JLGAUMRF.js} +367 -97
- package/dist/standalone-mode-JLGAUMRF.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-3EKP7PMM.js.map +0 -1
- package/dist/chunk-HPSOQP7Q.js +0 -109
- package/dist/chunk-HPSOQP7Q.js.map +0 -1
- package/dist/chunk-LFGDLD6J.js.map +0 -1
- package/dist/chunk-O6TXHKWG.js.map +0 -1
- package/dist/chunk-PLKZAUTG.js.map +0 -1
- package/dist/standalone-mode-FCKTQ33Y.js.map +0 -1
package/dist/cli/rig.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/rig.ts","../../src/cli/dispatch.ts","../../src/cli/balance.ts","../../src/cli/errors.ts","../../src/cli/push.ts","../../src/cli/render.ts","../../src/cli/git-config.ts","../../src/cli/remote.ts","../../src/cli/channel.ts","../../src/cli/events.ts","../../src/cli/fund.ts","../../src/cli/git-passthrough.ts","../../src/cli/init.ts","../../src/cli/output.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `rig` — the git-native TOON CLI shipped by `@toon-protocol/rig` (epic\n * #222; standalone-only since #248; git passthrough since #250).\n *\n * rig-owned subcommands (see ./dispatch.ts):\n * init one-shot repo setup (identity + toon.* git config)\n * remote relays as git remotes (#249): add/remove/list\n * push estimate → confirm → execute (#229)\n * issue | comment | pr single NIP-34 event publishes (#231), incl.\n * `pr status` (moved from `rig status` in #250)\n * channel payment channels (#262/#263): list, open,\n * close, settle\n * fund | balance client money lifecycle (#263): devnet faucet\n * drip; wallet + channel balances\n *\n * Everything else is `git <argv...>` verbatim: `rig status` runs git status.\n *\n * STRICT `--json` STDOUT (#265): when a rig-owned command runs with `--json`,\n * stdout carries exactly one JSON document — the process-level stdout guard\n * reroutes every other write (including dependencies' `console.log`) to\n * stderr, the io layer sends human lines to stderr, and the post-dispatch\n * backstop emits an error envelope for paths that bailed before emitting.\n * The git passthrough is exempt: it inherits stdio verbatim (./output.ts).\n * The enforcement matrix in ./strict-json.test.ts mirrors this composition.\n */\n\nimport { createInterface } from 'node:readline/promises';\nimport { dispatch } from './dispatch.js';\nimport {\n isJsonInvocation,\n makeCliIo,\n redirectStdoutToStderr,\n type RigIo,\n} from './output.js';\n\n/** Real terminal I/O: stdout/stderr sinks + readline y/N confirm. */\nfunction makeIo(jsonMode: boolean): RigIo {\n // In --json mode, patch process.stdout FIRST — before any command (or its\n // dynamically imported dependencies) can write — and keep the only real\n // stdout writer for the machine document.\n const guard = jsonMode ? redirectStdoutToStderr() : undefined;\n return makeCliIo({\n jsonMode,\n writeStdout: guard\n ? guard.write\n : (text) => {\n process.stdout.write(text);\n },\n writeStderr: (text) => {\n process.stderr.write(text);\n },\n isInteractive: Boolean(process.stdin.isTTY && process.stdout.isTTY),\n confirm: async (question) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n try {\n const answer = (await rl.question(question)).trim().toLowerCase();\n return answer === 'y' || answer === 'yes';\n } finally {\n rl.close();\n }\n },\n });\n}\n\nconst argv = process.argv.slice(2);\nconst io = makeIo(isJsonInvocation(argv));\n\ndispatch(argv, {\n io,\n env: process.env,\n cwd: process.cwd(),\n}).then(\n (code) => {\n io.ensureSingleJsonDoc(code);\n process.exitCode = code;\n },\n (err: unknown) => {\n process.stderr.write(\n `rig: unexpected error: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\\n`\n );\n io.ensureSingleJsonDoc(1);\n process.exitCode = 1;\n }\n);\n","/**\n * `rig` subcommand dispatch (#250): rig-owned verbs first, git for the rest.\n *\n * rig owns exactly: init, remote, push, issue, comment, pr, channel, fund,\n * balance, help/-h/--help, and --version. EVERY other subcommand is executed\n * as `git <argv...>` verbatim (./git-passthrough.ts) — `rig status` IS `git\n * status`, `rig add -p`, `rig commit`, `rig rebase -i`, … all land in git\n * with rig's stdio and git's exit code. Owned verbs always win: `rig push`\n * is the paid TOON push and shadows `git push` (plain-git pushes stay\n * available by calling `git push` directly).\n *\n * The NIP-34 status publish that used to be `rig status` lives at\n * `rig pr status` since #250 (BREAKING) — bare `rig status` is git's.\n *\n * `--json` (#265) follows the same ownership boundary: it is a flag OF the\n * owned subcommands, never a global rig flag. `rig --json status` starts\n * with a verb rig does not own (`--json`), so the WHOLE argv passes through\n * to git verbatim — rig neither consumes the flag nor applies the strict\n * stdout contract to git's inherited stdio. The owned-verb list is pinned to\n * ./output.ts's RIG_OWNED_VERBS (strict-json.test.ts keeps them in sync).\n */\n\nimport { createRequire } from 'node:module';\nimport { runBalance } from './balance.js';\nimport { runChannel } from './channel.js';\nimport { runComment, runIssue, runPr, type EventCommandDeps } from './events.js';\nimport { runFund } from './fund.js';\nimport { runGitPassthrough, type GitRunner } from './git-passthrough.js';\nimport { runInit } from './init.js';\nimport { runPush, PUSH_USAGE } from './push.js';\nimport { runRemote } from './remote.js';\n\nexport const USAGE = `rig — git with a TOON remote (pay-to-write Nostr + Arweave)\n\nUsage: rig <command> [options]\n\nCommands rig owns:\n init set up this repo: resolve your identity\n (RIG_MNEMONIC) and write the toon.* git config\n remote add <name> <url> add a relay as a REAL git remote (\"origin\" is\n remote remove <name> the default publish target); remove/list manage\n remote list them — \\`git remote -v\\` shows the same data\n push [remote] [refspecs...] plan, price, confirm, and execute a paid push\n to TOON (defaults to the \"origin\" remote). rig\n push is the TOON transport and shadows git push;\n plain-git pushes remain available by running\n \\`git push\\` directly\n issue create file an issue (kind:1621) against a repo\n comment <root-event-id> comment (kind:1622) on an issue or patch\n pr create publish a patch (kind:1617) with real\n \\`git format-patch\\` content\n pr status <event-id> <state> set an issue/patch status (kind:1630-1633):\n open | applied | closed | draft\n fund drip devnet faucet funds to this identity's\n wallet (free); on other networks prints the\n address(es) to fund externally\n balance wallet balances + payment-channel holdings\n (free — chain reads and local state only)\n channel list show the payment channels paid commands hold\n (free — reads local state)\n channel open explicitly open (or resume) the channel for a\n peer; --deposit adds collateral (on-chain)\n channel close <channelId> start the settlement challenge window (on-chain)\n channel settle <channelId> release collateral after the window (on-chain)\n\nAny other command is passed through to git verbatim: \\`rig status\\` runs\n\\`git status\\`, and \\`rig add -p\\`, \\`rig commit\\`, \\`rig log --oneline\\`,\n\\`rig rebase -i\\`, … behave exactly like git (same output, same exit code).\n\nRun \\`rig <command> --help\\` for a rig command's flags. \\`rig init\\`,\n\\`rig remote\\`, \\`rig fund\\`, \\`rig balance\\`, and \\`rig channel list\\` are\nfree; push/issue/comment/pr are paid writes — permanent and non-refundable —\nand channel open/close/settle are on-chain wallet transactions; each states\nwhat it will spend and asks for confirmation before doing so (--yes skips,\n--json emits machine output).\n\nWith --json, stdout carries exactly ONE JSON document (everything human-facing\ngoes to stderr), so \\`rig <command> --json | jq\\` always parses. --json is a\nper-subcommand flag on the commands rig owns, NOT a global rig flag: it does\nnot apply to the git passthrough (\\`rig status --json\\` runs\n\\`git status --json\\`), and flags placed before the subcommand\n(\\`rig --json status\\`) pass through to git untouched.`;\n\n/** Dispatch deps: the event-command deps plus an injectable git runner. */\nexport interface DispatchDeps extends EventCommandDeps {\n /** Runs the git passthrough (default: real spawned git; tests inject). */\n runGit?: GitRunner;\n}\n\n/**\n * Version of the @toon-protocol/rig package this CLI shipped in. Resolved at\n * runtime relative to this module, which tsup may emit either as the\n * dist/cli/rig.js entry or a dist/ chunk — hence the short upward walk.\n */\nexport function rigVersion(): string {\n const require = createRequire(import.meta.url);\n for (const rel of ['../package.json', '../../package.json', '../../../package.json']) {\n try {\n const pkg = require(rel) as { name?: string; version?: string };\n if (pkg.name === '@toon-protocol/rig' && pkg.version) return pkg.version;\n } catch {\n // keep walking up\n }\n }\n return 'unknown';\n}\n\n/** Route one rig invocation (argv WITHOUT node/script); returns the exit code. */\nexport async function dispatch(\n argv: string[],\n deps: DispatchDeps\n): Promise<number> {\n const [command, ...rest] = argv;\n const { io } = deps;\n\n switch (command) {\n case 'init':\n return runInit(rest, deps);\n case 'remote':\n return runRemote(rest, deps);\n case 'push':\n return runPush(rest, deps);\n case 'issue':\n return runIssue(rest, deps);\n case 'comment':\n return runComment(rest, deps);\n case 'pr':\n return runPr(rest, deps);\n case 'channel':\n return runChannel(rest, deps);\n case 'fund':\n return runFund(rest, deps);\n case 'balance':\n return runBalance(rest, deps);\n case 'help':\n case '--help':\n case '-h':\n io.out(USAGE);\n io.out('');\n io.out(PUSH_USAGE);\n return 0;\n case '--version':\n io.out(`rig ${rigVersion()}`);\n return 0;\n case undefined:\n io.err(USAGE);\n return 2;\n default:\n // Git passthrough (#250): rig does not own this verb, so the EXACT\n // argv tail goes to system git — flags, quoting, and exit code intact.\n return (deps.runGit ?? runGitPassthrough)(argv, {\n cwd: deps.cwd,\n env: deps.env,\n err: (line) => io.err(line),\n });\n }\n}\n","/**\n * `rig balance` — the combined money view for the active identity (#263):\n * on-chain wallet balances plus open payment-channel holdings.\n *\n * FREE: no payment, no nonce guard, no channel, no relay. The wallet section\n * reuses the client's own balance readers (`ToonClient.getBalances()` on the\n * UNSTARTED embedded client) which read the SETTLEMENT chain the channels\n * actually use — the settlement-chain key wins over the network preset's\n * primary chain, so a devnet identity funded on `evm:anvil:31337` shows that\n * balance, not the preset chain's zero (the #260-era getBalances mismatch).\n * The channel section joins the #262 peer→channel map with the claim\n * watermark: deposited / claimed / available per recorded channel of THIS\n * identity. A write uplink is NOT required (`requireUplink: false`) — reads\n * work from a read-only config.\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n channelStatus,\n ChannelMapStore,\n resolveChannelPaths,\n} from '../standalone/channel-map.js';\nimport type { WalletBalanceInfo } from '../standalone/money.js';\nimport { emitCliError } from './errors.js';\nimport {\n defaultLoadStandalone,\n identityReport,\n type IdentityReport,\n type PushDeps,\n} from './push.js';\nimport { renderIdentityLine } from './render.js';\nimport type { StandaloneContext } from './standalone-context.js';\n\nexport const BALANCE_USAGE = `Usage: rig balance [--json]\n\nShow the active identity's money: on-chain wallet balances (per configured\nchain, read from the settlement chain the payment channels actually use) and\nrecorded payment-channel holdings (deposited / claimed / available). Free —\nreads chain RPCs and local state only; nothing is signed or paid.\n\nOptions:\n --json machine-readable envelope (base units as strings)\n -h, --help show this help`;\n\n/** What `rig balance` needs — the shared paid-command deps (loader seam). */\nexport type BalanceDeps = PushDeps;\n\n/** One recorded channel in the balance view. */\ninterface ChannelBalanceJson {\n channelId: string;\n destination: string;\n peerId: string;\n chain: string;\n status: 'open' | 'closing' | 'settleable' | 'settled';\n depositTotal: string | null;\n cumulativeClaimed: string | null;\n nonce: number | null;\n /** depositTotal − cumulativeClaimed, when both are known (floored at 0). */\n available: string | null;\n}\n\n/** `--json` envelope. */\ninterface BalanceJson {\n command: 'balance';\n identity: IdentityReport;\n wallet: WalletBalanceInfo[];\n channels: ChannelBalanceJson[];\n}\n\n/** Run `rig balance`; returns the process exit code. */\nexport async function runBalance(\n args: string[],\n deps: BalanceDeps\n): Promise<number> {\n const { io, env } = deps;\n let json = false;\n try {\n const { values } = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (values.help) {\n io.out(BALANCE_USAGE);\n return 0;\n }\n json = values.json ?? false;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(BALANCE_USAGE);\n return 2;\n }\n\n let ctx: StandaloneContext | undefined;\n try {\n ctx = await (deps.loadStandalone ?? defaultLoadStandalone)({\n env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n // Free read: works without a proxy/BTP write uplink.\n requireUplink: false,\n });\n const identity = identityReport(ctx);\n\n // ── Wallet: the client's own settlement-chain-aware balance readers ─────\n const wallet = ctx.money ? await ctx.money.walletBalances() : [];\n\n // ── Channels: #262 map ⋈ claim watermark, THIS identity only ────────────\n const store = new ChannelMapStore(resolveChannelPaths(env));\n const channels: ChannelBalanceJson[] = store\n .list()\n .filter((record) => record.identity === identity.pubkey)\n .map((record) => {\n const watermark = store.readWatermark(record.channelId);\n const deposited = record.depositTotal;\n const claimed = watermark?.cumulativeAmount;\n let available: string | null = null;\n if (deposited !== undefined && claimed !== undefined) {\n const remaining = BigInt(deposited) - BigInt(claimed);\n available = (remaining > 0n ? remaining : 0n).toString();\n }\n return {\n channelId: record.channelId,\n destination: record.destination,\n peerId: record.peerId,\n chain: record.chain,\n status: channelStatus(watermark),\n depositTotal: deposited ?? null,\n cumulativeClaimed: claimed ?? null,\n nonce: watermark?.nonce ?? null,\n available,\n };\n });\n\n if (json) {\n io.emitJson({\n command: 'balance',\n identity,\n wallet,\n channels,\n } satisfies BalanceJson);\n return 0;\n }\n\n io.out(renderIdentityLine(identity));\n io.out('');\n io.out('Wallet (on-chain):');\n if (wallet.length === 0) {\n io.out(\n ' (no balance readable — no chain configured, the RPC is unreachable, ' +\n \"or the chain's keys derive only during a client start)\"\n );\n }\n for (const balance of wallet) {\n io.out(\n ` ${balance.chain.padEnd(7)} ${balance.address} ${balance.amount}` +\n (balance.asset ? ` ${balance.asset}` : ' base units') +\n (balance.assetScale !== undefined ? ` (scale ${balance.assetScale})` : '')\n );\n }\n io.out('');\n io.out('Channels (recorded):');\n if (channels.length === 0) {\n io.out(\n ' none — paid commands record their channel on first use; ' +\n '`rig channel open` records one explicitly.'\n );\n }\n for (const c of channels) {\n io.out(\n ` ${c.channelId} [${c.status}] deposited ${c.depositTotal ?? '?'} ` +\n `claimed ${c.cumulativeClaimed ?? '?'} available ${c.available ?? '?'}` +\n ` (${c.chain} → ${c.destination})`\n );\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'balance', err);\n } finally {\n if (ctx) {\n try {\n await ctx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n","/**\n * Error UX for the `rig` commands: map structured planner/publisher errors\n * to actionable terminal output (and a machine-readable envelope for\n * `--json`). The CLI is standalone-only (#248), so everything here is either\n * a local planner error, an identity/config-chain error, or a tagged error\n * surfaced from the embedded publisher (matched by name — those classes live\n * behind the lazy `@toon-protocol/client` dynamic import).\n */\n\nimport { MAX_OBJECT_SIZE } from '../objects.js';\nimport {\n NonFastForwardError,\n OversizeObjectsError,\n type OversizeObject,\n type RejectedRefUpdate,\n} from '../push.js';\nimport { GitError } from '../repo-reader.js';\nimport { MissingIdentityError } from './identity.js';\nimport type { CliIo } from './output.js';\n\n/** Normalized error description: terminal lines + `--json` envelope. */\nexport interface DescribedError {\n /** Stable machine code. */\n code: string;\n /** Human-facing lines (message first, remediation after). */\n lines: string[];\n /** Machine envelope for `--json` output (structured payload included). */\n json: Record<string, unknown>;\n}\n\n/**\n * A command could not resolve the NIP-34 repo address\n * (`30617:<ownerPubkey>:<repoId>`) from flags or the `toon.*` git config\n * keys `rig init` writes.\n */\nexport class UnconfiguredRepoAddressError extends Error {\n constructor(\n /** Which half of the address is missing. */\n public readonly missing: 'repository id' | 'repository owner'\n ) {\n super(\n `no ${missing} configured — this command addresses the repo as ` +\n '30617:<ownerPubkey>:<repoId>. Run `rig init` once inside the repo ' +\n '(it writes toon.repoid/toon.owner to the local git config), or ' +\n `pass ${missing === 'repository id' ? '--repo-id <id>' : '--owner <pubkey>'} ` +\n \"explicitly (use --owner for repos you don't own).\"\n );\n this.name = 'UnconfiguredRepoAddressError';\n }\n}\n\n/** A relay URL (flag, `rig remote add`, or a remote's stored URL) is junk. */\nexport class InvalidRelayUrlError extends Error {\n constructor(\n public readonly url: string,\n /** What was being resolved, e.g. `remote \"origin\"`. */\n context: string\n ) {\n super(\n `${context}: ${JSON.stringify(url)} is not a relay URL — relays are ` +\n 'ws://, wss://, http://, or https://'\n );\n this.name = 'InvalidRelayUrlError';\n }\n}\n\n/** A paid command addressed a git remote that is not configured. */\nexport class UnknownRemoteError extends Error {\n constructor(public readonly remote: string) {\n super(\n `no remote named ${JSON.stringify(remote)} is configured — ` +\n '`rig remote list` shows configured remotes; add it with ' +\n `\\`rig remote add ${remote} <relay-url>\\``\n );\n this.name = 'UnknownRemoteError';\n }\n}\n\n/**\n * The addressed git remote carries multiple URLs (`git remote set-url --add`\n * done by hand). rig publishes to exactly one relay per paid command, so this\n * is refused BEFORE anything is fetched, uploaded, or paid (the #243\n * single-relay guard, extended to remotes).\n */\nexport class MultiUrlRemoteError extends Error {\n constructor(\n public readonly remote: string,\n public readonly urls: string[]\n ) {\n super(\n `remote ${JSON.stringify(remote)} has ${urls.length} URLs ` +\n `(${urls.join(', ')}) — rig supports one relay URL per remote. ` +\n `Fix it with \\`git remote set-url ${remote} <relay-url>\\`. ` +\n 'Nothing was uploaded, published, or paid.'\n );\n this.name = 'MultiUrlRemoteError';\n }\n}\n\n/** No relay resolved: no --relay, no usable remote, no legacy toon.relay. */\nexport class NoOriginConfiguredError extends Error {\n constructor(\n /** URL of an existing `origin` remote that is NOT a relay, if any. */\n nonRelayOriginUrl?: string\n ) {\n super(\n 'no origin configured — run `rig remote add origin <relay-url>` ' +\n '(or pass --relay <url> for a one-off publish).' +\n (nonRelayOriginUrl !== undefined\n ? `\\nThe existing \"origin\" remote (${nonRelayOriginUrl}) is not a ` +\n 'relay URL, so rig ignores it — add the relay under another ' +\n 'name (`rig remote add toon <relay-url>`) and target it ' +\n 'explicitly (`rig push toon` / `--remote toon`).'\n : '')\n );\n this.name = 'NoOriginConfiguredError';\n }\n}\n\n/** A rig command ran outside any git repository. */\nexport class NotAGitRepositoryError extends Error {\n constructor(cwd: string) {\n super(\n `not a git repository: ${cwd}\\n` +\n 'rig works inside an existing repo — create one first with `git init` ' +\n '(rig never runs it for you), then re-run.'\n );\n this.name = 'NotAGitRepositoryError';\n }\n}\n\nfunction nonFastForwardLines(refs: RejectedRefUpdate[]): string[] {\n return [\n 'Push rejected: non-fast-forward update for:',\n ...refs.map(\n (r) =>\n ` ${r.refname} remote ${r.remoteSha.slice(0, 7)} is not an ancestor of local ${r.localSha.slice(0, 7)}`\n ),\n 'The remote moved since your last push. Re-run with --force to overwrite it',\n 'WARNING: --force rewrites the published ref history for every reader of this repo.',\n ];\n}\n\nfunction oversizeLines(objects: OversizeObject[]): string[] {\n return [\n `Push rejected: ${objects.length} object(s) exceed the ${MAX_OBJECT_SIZE}-byte (95KB) upload limit:`,\n ...objects.map(\n (o) => ` ${o.path ?? o.sha} ${o.type}, ${o.size} bytes`\n ),\n 'Objects over 95KB are a hard error in v1 — split or remove the file(s) from history to push.',\n 'Large-object support is tracked in toon-client#235.',\n ];\n}\n\n/**\n * Normalize any command-path error for rendering. `command` names the rig\n * subcommand for the generic \"rig <command> failed\" lines.\n */\nexport function describeError(err: unknown, command = 'push'): DescribedError {\n if (err instanceof UnconfiguredRepoAddressError) {\n return {\n code: 'unconfigured_repo_address',\n lines: err.message.split('\\n'),\n json: { error: 'unconfigured_repo_address', detail: err.message },\n };\n }\n if (err instanceof NotAGitRepositoryError) {\n return {\n code: 'not_a_git_repository',\n lines: err.message.split('\\n'),\n json: { error: 'not_a_git_repository', detail: err.message },\n };\n }\n if (err instanceof InvalidRelayUrlError) {\n return {\n code: 'invalid_relay_url',\n lines: err.message.split('\\n'),\n json: { error: 'invalid_relay_url', detail: err.message, url: err.url },\n };\n }\n if (err instanceof UnknownRemoteError) {\n return {\n code: 'unknown_remote',\n lines: err.message.split('\\n'),\n json: { error: 'unknown_remote', detail: err.message, remote: err.remote },\n };\n }\n if (err instanceof MultiUrlRemoteError) {\n return {\n code: 'multi_url_remote',\n lines: err.message.split('\\n'),\n json: {\n error: 'multi_url_remote',\n detail: err.message,\n remote: err.remote,\n urls: err.urls,\n },\n };\n }\n if (err instanceof NoOriginConfiguredError) {\n return {\n code: 'no_origin_configured',\n lines: err.message.split('\\n'),\n json: { error: 'no_origin_configured', detail: err.message },\n };\n }\n if (err instanceof MissingIdentityError) {\n return {\n code: 'missing_identity',\n lines: err.message.split('\\n'),\n json: { error: 'missing_identity', detail: err.message },\n };\n }\n if (err instanceof NonFastForwardError) {\n return {\n code: 'non_fast_forward',\n lines: nonFastForwardLines(err.refs),\n json: { error: 'non_fast_forward', detail: err.message, refs: err.refs },\n };\n }\n if (err instanceof OversizeObjectsError) {\n return {\n code: 'oversize_objects',\n lines: oversizeLines(err.objects),\n json: {\n error: 'oversize_objects',\n detail: err.message,\n objects: err.objects,\n },\n };\n }\n if (err instanceof GitError) {\n return {\n code: 'git_error',\n lines: [`git failed: ${err.message}`],\n json: { error: 'git_error', detail: err.message },\n };\n }\n\n // Standalone-path tagged errors (matched by name — the classes live behind\n // the optional dynamic import).\n const name = err instanceof Error ? err.name : '';\n const message = err instanceof Error ? err.message : String(err);\n if (name === 'DaemonIdentityConflictError') {\n return {\n code: 'daemon_identity_conflict',\n lines: [\n message,\n 'Stop the toon-clientd daemon (or publish through its toon_git_* MCP tools) and re-run.',\n ],\n json: { error: 'daemon_identity_conflict', detail: message },\n };\n }\n if (name === 'MissingUplinkError') {\n return {\n code: 'missing_uplink',\n lines: [message],\n json: { error: 'missing_uplink', detail: message },\n };\n }\n // Peer→channel map corruption (#262) — matched by name so tsup chunk\n // duplication between the cli and standalone entries can't break instanceof.\n if (name === 'ChannelMapCorruptError') {\n return {\n code: 'channel_map_corrupt',\n lines: [message],\n json: { error: 'channel_map_corrupt', detail: message },\n };\n }\n // Settle attempted before the challenge window elapsed (#263) — the client\n // throws this retryable error BEFORE spending gas; surface when to retry.\n if (name === 'SettleTooEarlyError') {\n const settleableAt = (err as { settleableAt?: unknown }).settleableAt;\n return {\n code: 'settle_too_early',\n lines: [\n message,\n 'The settlement challenge window is still open — nothing was spent. ' +\n 'Re-run `rig channel settle` after the settleable time.',\n ],\n json: {\n error: 'settle_too_early',\n detail: message,\n ...(typeof settleableAt === 'string' ? { settleableAt } : {}),\n },\n };\n }\n\n return {\n code: 'error',\n lines: [`rig ${command} failed: ${message}`],\n json: { error: 'error', detail: message },\n };\n}\n\n/**\n * The one command-error emitter (#265): the machine envelope (tagged with\n * the command name) goes to stdout via `emitJson` when `--json` is active,\n * and the human-facing lines ALWAYS go to stderr — so JSON consumers get the\n * parseable envelope while a human tailing stderr still sees the detail.\n * Returns the exit code (always 1) so callers can `return emitCliError(…)`.\n */\nexport function emitCliError(\n io: CliIo,\n json: boolean,\n command: string,\n err: unknown\n): 1 {\n const described = describeError(err, command);\n if (json) io.emitJson({ command, ...described.json });\n for (const line of described.lines) io.err(line);\n return 1;\n}\n","/**\n * `rig push [remote] [refspecs...]` — estimate → confirm → execute (#229,\n * standalone since #248, git-like remote resolution since #249).\n *\n * The CLI is STANDALONE-ONLY: it plans locally (`planPush`) and executes\n * through the embedded, nonce-guarded StandalonePublisher (loaded via dynamic\n * import so runs that fail earlier never need `@toon-protocol/client`). The\n * identity comes from the RIG_MNEMONIC precedence chain (./identity.ts); the\n * nonce guard still refuses when a running toon-clientd holds the same\n * identity (cumulative-claim watermark protection) — drive the daemon through\n * its toon_git_* MCP tools instead.\n *\n * Repo addressing comes from the `toon.*` git config keys `rig init` writes\n * (`--repo-id` overrides); an unconfigured repo is a hard \"run `rig init`\n * first\" error — nothing is written as a side effect of pushing.\n *\n * The relay comes from the repo's git remotes (#249): when the first\n * positional matches a configured remote name it is the push target,\n * otherwise it is a refspec and the remote defaults to `origin`. `--relay`\n * is an ad-hoc override that bypasses remotes (all positionals are then\n * refspecs); the deprecated v0.1 `git config toon.relay` still works with a\n * migration nudge. See ./remote.ts for the full resolution order.\n *\n * Money is only spent after the confirm gate: `--yes`, or an interactive\n * y/N prompt (a non-TTY session without `--yes` refuses). `--json` emits the\n * wire-shaped plan/receipts for agent consumers; without `--yes` it becomes\n * a pure estimate (plan JSON, nothing executed, exit 0).\n */\n\nimport { parseArgs } from 'node:util';\nimport { planPush, executePush } from '../push.js';\nimport { GitRepoReader } from '../repo-reader.js';\nimport { renderIdentityLine, renderPlan, renderResult } from './render.js';\nimport {\n serializePushPlan,\n serializePushResult,\n type GitEstimateResponse,\n type GitPushResponse,\n} from '../routes.js';\nimport { emitCliError, UnconfiguredRepoAddressError } from './errors.js';\nimport { listGitRemotes, readToonConfig, resolveRepoRoot } from './git-config.js';\nimport type { IdentitySourceKind } from './identity.js';\nimport { resolveRelays, singleRelayRefusal } from './remote.js';\nimport type { LoadStandalone, StandaloneContext } from './standalone-context.js';\n\n// ---------------------------------------------------------------------------\n// Dependency seam (real wiring in rig.ts; tests inject fakes)\n// ---------------------------------------------------------------------------\n\n/**\n * Terminal I/O seam — lives in ./output.ts since #265 (the strict `--json`\n * stdout layer); re-exported here because every command module historically\n * imports it from push.ts.\n */\nexport type { CliIo } from './output.js';\nimport type { CliIo } from './output.js';\n\nexport interface PushDeps {\n io: CliIo;\n env: NodeJS.ProcessEnv;\n cwd: string;\n /** Standalone factory; defaults to the real dynamic-import loader. */\n loadStandalone?: LoadStandalone;\n}\n\n/**\n * Default standalone factory (shared by every paid command). Dynamic import:\n * `standalone-mode` (and its `@toon-protocol/client` dependency) only loads\n * once a command actually needs to sign or pay.\n */\nexport const defaultLoadStandalone: LoadStandalone = async (options) => {\n const mod = await import('./standalone-mode.js');\n return mod.createStandaloneContext(options);\n};\n\n/** Identity report shared by every paid command's `--json` envelope. */\nexport interface IdentityReport {\n /** Derived Nostr pubkey (hex) of the active identity. */\n pubkey: string;\n /** Which tier of the RIG_MNEMONIC precedence chain supplied it. */\n source: IdentitySourceKind;\n /** Human-facing source label, e.g. `RIG_MNEMONIC env` or a file path. */\n sourceLabel: string;\n}\n\n/** Build the identity report of a loaded standalone context. */\nexport function identityReport(ctx: StandaloneContext): IdentityReport {\n return {\n pubkey: ctx.ownerPubkey,\n source: ctx.identitySource,\n sourceLabel: ctx.identitySourceLabel,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Usage\n// ---------------------------------------------------------------------------\n\nexport const PUSH_USAGE = `Usage: rig push [remote] [refspecs...] [options]\n\nPush local git refs to TOON: uploads the object delta to Arweave (paid) and\npublishes the NIP-34 refs event (kind:30618; kind:30617 announce on first\npush). Writes are permanent and non-refundable.\n\nThe repo must be set up once with \\`rig init\\` (writes toon.repoid/toon.owner\nto the local git config); the identity comes from RIG_MNEMONIC (env or a\nproject .env), or the ~/.toon-client keystore/config.\n\nThe relay is a git remote: \\`rig push\\` publishes via \"origin\" (set up with\n\\`rig remote add origin <relay-url>\\`); \\`rig push <remote> [refspecs...]\\`\npublishes via a named remote. When the first positional matches a configured\nremote name it is the remote; otherwise it is a refspec and the remote\ndefaults to origin. Refspecs are branch/tag names or full refnames; default\nis the current branch.\n\nOptions:\n --force allow non-fast-forward ref updates (overwrites remote history)\n --all push all local branches\n --tags push all local tags\n --yes skip the fee confirmation (required when not a TTY)\n --json machine-readable plan/receipts; without --yes it is a pure\n estimate (nothing executed)\n --relay <url> ad-hoc relay override (exactly one) — bypasses the\n configured remotes; every positional is then a refspec.\n The deprecated v0.1 \\`git config toon.relay\\` still works\n as a fallback, with a migration nudge\n --repo-id <id> repository id / NIP-34 d-tag (default: git config\n toon.repoid — run \\`rig init\\` to set it)\n -h, --help show this help`;\n\n// ---------------------------------------------------------------------------\n// Refspec selection\n// ---------------------------------------------------------------------------\n\n/**\n * Expand positional refspecs / `--all` / `--tags` into full refnames using\n * the local ref list; default (no selection) is the current branch.\n */\nexport async function selectRefspecs(\n reader: GitRepoReader,\n positionals: string[],\n all: boolean,\n tags: boolean\n): Promise<string[]> {\n const { head, refs } = await reader.listRefs();\n const byName = new Set(refs.map((r) => r.refname));\n\n const selected: string[] = [];\n const add = (refname: string): void => {\n if (!selected.includes(refname)) selected.push(refname);\n };\n\n for (const spec of positionals) {\n if (byName.has(spec)) {\n add(spec);\n } else if (byName.has(`refs/heads/${spec}`)) {\n add(`refs/heads/${spec}`);\n } else if (byName.has(`refs/tags/${spec}`)) {\n add(`refs/tags/${spec}`);\n } else {\n throw new Error(\n `refspec ${JSON.stringify(spec)} matches no local branch or tag ` +\n '(ref deletion is out of scope in v1)'\n );\n }\n }\n if (all) {\n for (const ref of refs) {\n if (ref.refname.startsWith('refs/heads/')) add(ref.refname);\n }\n }\n if (tags) {\n for (const ref of refs) {\n if (ref.refname.startsWith('refs/tags/')) add(ref.refname);\n }\n }\n if (selected.length === 0) {\n if (!head) {\n throw new Error(\n 'HEAD is detached and no refspec was given — pass a branch/tag name, --all, or --tags'\n );\n }\n add(head);\n }\n return selected;\n}\n\n// ---------------------------------------------------------------------------\n// Command\n// ---------------------------------------------------------------------------\n\ninterface PushFlags {\n force: boolean;\n all: boolean;\n tags: boolean;\n yes: boolean;\n json: boolean;\n relay: string[];\n repoId?: string;\n help: boolean;\n positionals: string[];\n}\n\nfunction parsePushArgs(args: string[]): PushFlags {\n const { values, positionals } = parseArgs({\n args,\n options: {\n force: { type: 'boolean', default: false },\n all: { type: 'boolean', default: false },\n tags: { type: 'boolean', default: false },\n yes: { type: 'boolean', default: false },\n json: { type: 'boolean', default: false },\n relay: { type: 'string', multiple: true },\n 'repo-id': { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: true,\n });\n const flags: PushFlags = {\n force: values.force ?? false,\n all: values.all ?? false,\n tags: values.tags ?? false,\n yes: values.yes ?? false,\n json: values.json ?? false,\n relay: values.relay ?? [],\n help: values.help ?? false,\n positionals,\n };\n const repoId = values['repo-id'];\n if (repoId !== undefined) flags.repoId = repoId;\n return flags;\n}\n\n/** JSON envelope emitted by `--json` runs (agents consume this). */\ninterface PushJsonOutput {\n command: 'push';\n repoId: string;\n /** Active identity: source tier + derived pubkey (never the phrase). */\n identity: IdentityReport;\n /** True when the paid execute step ran. */\n executed: boolean;\n /** True when every selected ref already matched the remote (no-op). */\n upToDate: boolean;\n plan: GitEstimateResponse;\n result?: GitPushResponse;\n hint?: string;\n}\n\n/** Run `rig push`; returns the process exit code. */\nexport async function runPush(args: string[], deps: PushDeps): Promise<number> {\n const { io, env } = deps;\n\n let flags: PushFlags;\n try {\n flags = parsePushArgs(args);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(PUSH_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(PUSH_USAGE);\n return 0;\n }\n\n let standaloneCtx: StandaloneContext | undefined;\n try {\n // ── Repo + config resolution (rig init writes these) ────────────────────\n const repoRoot = await resolveRepoRoot(deps.cwd);\n const toonConfig = await readToonConfig(repoRoot);\n const repoId = flags.repoId ?? toonConfig.repoId;\n if (!repoId) throw new UnconfiguredRepoAddressError('repository id');\n const reader = new GitRepoReader(repoRoot);\n\n // ── Remote-vs-refspec resolution (git-like: `rig push [remote] [refspecs…]`)\n // The first positional is the remote when it names a configured git\n // remote; with --relay the remotes are bypassed and every positional is\n // a refspec.\n let remoteName: string | undefined;\n let refspecArgs = flags.positionals;\n if (flags.relay.length === 0 && refspecArgs.length > 0) {\n const first = refspecArgs[0] as string;\n const remoteNames = new Set(\n (await listGitRemotes(repoRoot)).map((r) => r.name)\n );\n if (remoteNames.has(first)) {\n remoteName = first;\n refspecArgs = refspecArgs.slice(1);\n } else {\n // Not a remote, so it must be a refspec — distinguish a typo'd /\n // unconfigured remote from a bad refspec with one combined error.\n const { refs } = await reader.listRefs();\n const known = new Set(refs.map((r) => r.refname));\n if (\n !known.has(first) &&\n !known.has(`refs/heads/${first}`) &&\n !known.has(`refs/tags/${first}`)\n ) {\n throw new Error(\n `${JSON.stringify(first)} is neither a configured remote nor a ` +\n 'local branch/tag — add the relay remote ' +\n `(\\`rig remote add ${first} <relay-url>\\`; \\`rig remote list\\` ` +\n 'shows configured remotes) or fix the refspec'\n );\n }\n }\n }\n const refspecs = await selectRefspecs(\n reader,\n refspecArgs,\n flags.all,\n flags.tags\n );\n\n // ── Relay resolution (#249: --relay > named remote > origin > toon.relay)\n const resolved = await resolveRelays({\n relayFlags: flags.relay,\n remoteName,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n if (resolved.nudge !== undefined) io.err(resolved.nudge);\n const relaysUsed = resolved.relays;\n // StandalonePublisher publishes to exactly one relay (its publishEvent\n // throws on >1). Multiple relays can arrive here without explicit intent\n // (repeated --relay flags, an old multi-valued git config `toon.relay`).\n // Refuse up front, before anything is fetched, uploaded, or paid.\n if (relaysUsed.length > 1) {\n io.err(singleRelayRefusal(resolved, 'Nothing was uploaded or paid.'));\n return 1;\n }\n\n // ── Standalone context (identity chain + nonce guard) ───────────────────\n standaloneCtx = await (deps.loadStandalone ?? defaultLoadStandalone)({\n env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n // Relay-origin for #264 network bootstrap (announce discovery).\n ...(relaysUsed[0] !== undefined ? { relayUrl: relaysUsed[0] } : {}),\n });\n const identity = identityReport(standaloneCtx);\n\n if (toonConfig.owner && toonConfig.owner !== identity.pubkey) {\n io.err(\n `warning: git config toon.owner (${toonConfig.owner.slice(0, 8)}…) differs from ` +\n `the active identity (${identity.pubkey.slice(0, 8)}…) — this push publishes ` +\n \"under the ACTIVE identity's repo namespace, not the configured owner's. \" +\n 'Re-run `rig init` to adopt the active identity.'\n );\n }\n\n // ── Estimate (local plan) ───────────────────────────────────────────────\n const remoteState = await standaloneCtx.fetchRemote({\n ownerPubkey: standaloneCtx.ownerPubkey,\n repoId,\n relayUrls: relaysUsed,\n });\n const feeRates = await standaloneCtx.publisher.getFeeRates();\n const pushPlan = await planPush({\n repoReader: reader,\n remoteState,\n feeRates,\n repoId,\n refs: refspecs,\n force: flags.force,\n });\n const plan = serializePushPlan(pushPlan);\n\n // ── Up-to-date short-circuit (never publish a no-op refs event) ─────────\n const upToDate = plan.refUpdates.every((u) => u.kind === 'up-to-date');\n if (upToDate) {\n if (flags.json) {\n io.emitJson({\n command: 'push',\n repoId,\n identity,\n executed: false,\n upToDate: true,\n plan,\n } satisfies PushJsonOutput);\n } else {\n io.out('Everything up-to-date — nothing to push (and nothing paid).');\n }\n return 0;\n }\n\n // ── Confirm gate ────────────────────────────────────────────────────────\n if (!flags.json) {\n for (const line of renderPlan(plan)) io.out(line);\n io.out(renderIdentityLine(identity));\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n command: 'push',\n repoId,\n identity,\n executed: false,\n upToDate: false,\n plan,\n hint: 'estimate only — re-run with --yes to upload and publish (permanent, non-refundable)',\n } satisfies PushJsonOutput);\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n 'refusing to spend channel funds without confirmation in a non-interactive ' +\n 'session — re-run with --yes (or use --json for an estimate)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Proceed with paid push (total ${plan.estimate.totalFee} base units)? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was uploaded or published.');\n return 1;\n }\n }\n\n // ── Execute ─────────────────────────────────────────────────────────────\n const pushResult = await executePush({\n plan: pushPlan,\n publisher: standaloneCtx.publisher,\n remoteState,\n repoReader: reader,\n relayUrls: relaysUsed,\n });\n const result = serializePushResult(pushPlan, pushResult);\n\n // ── Receipts ────────────────────────────────────────────────────────────\n if (flags.json) {\n io.emitJson({\n command: 'push',\n repoId,\n identity,\n executed: true,\n upToDate: false,\n plan,\n result,\n } satisfies PushJsonOutput);\n } else {\n for (const line of renderResult(result)) io.out(line);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, 'push', err);\n } finally {\n if (standaloneCtx) {\n try {\n await standaloneCtx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n","/**\n * Human-facing rendering for `rig push`: the pre-push confirm table and the\n * post-push receipts. Machine consumers use `--json` instead (the raw wire\n * shapes from ../routes.ts) — nothing here is meant to be parsed.\n */\n\nimport type {\n GitEstimateResponse,\n GitEventResponse,\n GitPushResponse,\n GitRefUpdate,\n GitRepoAddr,\n} from '../routes.js';\n\n/** Group thousands for readability: 1234567 → '1,234,567'. */\nexport function formatNumber(value: number | string | bigint): string {\n return String(value).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n}\n\nfunction shortSha(sha: string | null): string {\n return sha ? sha.slice(0, 7) : '(none)';\n}\n\nfunction refLine(update: GitRefUpdate): string {\n const arrow = `${shortSha(update.remoteSha)} → ${shortSha(update.localSha)}`;\n return ` ${update.refname} ${arrow} (${update.kind})`;\n}\n\n/**\n * One-line identity report: derived pubkey + which chain tier supplied the\n * mnemonic (never the phrase itself).\n */\nexport function renderIdentityLine(identity: {\n pubkey: string;\n sourceLabel: string;\n}): string {\n return `Identity: ${identity.pubkey} (from ${identity.sourceLabel})`;\n}\n\n/** The pre-push confirm table (refs, objects, itemized fees, warning). */\nexport function renderPlan(plan: GitEstimateResponse): string[] {\n const lines: string[] = [];\n lines.push(\n `Push plan for repo \"${plan.repoId}\"` +\n (plan.announceNeeded ? ' — first push, will announce (kind:30617)' : '')\n );\n lines.push('Refs:');\n for (const update of plan.refUpdates) lines.push(refLine(update));\n\n const est = plan.estimate;\n const skipped = Object.keys(plan.knownShaToTxId).length;\n lines.push(\n `Objects: ${est.objectCount} to upload` +\n ` (${formatNumber(est.totalObjectBytes)} bytes)` +\n (skipped > 0 ? `; ${skipped} already on Arweave (free)` : '')\n );\n lines.push('Fees (base units):');\n lines.push(\n ` upload ${est.objectCount} object(s), ${formatNumber(est.totalObjectBytes)} bytes` +\n ` ${formatNumber(est.uploadFee)}`\n );\n lines.push(` events ${est.eventCount} event(s) ${formatNumber(est.eventFees)}`);\n lines.push(` total ${formatNumber(est.totalFee)}`);\n lines.push('Writes are permanent and non-refundable.');\n return lines;\n}\n\n/** Human label for a per-event fee that may be unknown (older daemons). */\nexport function feeLabel(fee: string | undefined): string {\n return fee !== undefined\n ? `${formatNumber(fee)} base units`\n : \"the publisher's configured per-event fee\";\n}\n\n/**\n * Pre-publish summary for the single-event subcommands\n * (issue/comment/pr/status): what is published, against which repo address,\n * at what fee — the confirm gate follows these lines.\n */\nexport function renderEventPlan(opts: {\n /** e.g. `issue \"Fix the flux\" (kind:1621)`. */\n action: string;\n addr: GitRepoAddr;\n /** Active identity (source + derived pubkey). */\n identity: { pubkey: string; sourceLabel: string };\n /** Per-event fee (base units, decimal string), when known. */\n fee?: string;\n}): string[] {\n return [\n `Publish ${opts.action}`,\n `Repo: 30617:${opts.addr.ownerPubkey}:${opts.addr.repoId}`,\n renderIdentityLine(opts.identity),\n `Fee: ${feeLabel(opts.fee)}. Writes are permanent and non-refundable.`,\n ];\n}\n\n/** Receipt line for one published single-event git write. */\nexport function renderEventReceipt(\n action: string,\n result: GitEventResponse\n): string[] {\n const lines = [\n `Published ${action}: ${result.eventId} paid ${formatNumber(result.feePaid)} base units`,\n ];\n if (result.channelBalanceAfter !== undefined) {\n lines.push(\n `Channel balance after: ${formatNumber(result.channelBalanceAfter)} base units`\n );\n }\n return lines;\n}\n\n/** Post-push receipts: per-object skipped/paid, event ids, paid-vs-estimate. */\nexport function renderResult(result: GitPushResponse): string[] {\n const lines: string[] = [];\n lines.push(`Pushed \"${result.repoId}\":`);\n const paid = result.uploads.filter((u) => !u.skipped);\n const skipped = result.uploads.filter((u) => u.skipped);\n for (const upload of result.uploads) {\n lines.push(\n ` object ${upload.sha.slice(0, 12)} ${upload.skipped ? 'skipped (already stored)' : `paid ${formatNumber(upload.feePaid)}`}` +\n ` ar:${upload.txId}`\n );\n }\n lines.push(\n `Uploads: ${paid.length} paid, ${skipped.length} skipped (content-addressed).`\n );\n if (result.announceReceipt) {\n lines.push(\n `Announcement (kind:30617): ${result.announceReceipt.eventId}` +\n ` paid ${formatNumber(result.announceReceipt.feePaid)}`\n );\n }\n lines.push(\n `Refs event (kind:30618): ${result.refsReceipt.eventId}` +\n ` paid ${formatNumber(result.refsReceipt.feePaid)}`\n );\n lines.push(\n `Total paid: ${formatNumber(result.totalFeePaid)} base units` +\n ` (estimate was ${formatNumber(result.estimate.totalFee)})`\n );\n return lines;\n}\n","/**\n * Repo-local `rig` configuration, persisted in git's own storage:\n *\n * toon.repoid NIP-34 repository identifier (`d` tag)\n * toon.owner repository owner's Nostr pubkey (hex) — the identity that\n * signs kind:30617/30618 (`a`-tag `30617:<owner>:<repoId>`)\n * toon.relay relay URL(s), multi-valued — DEPRECATED since #249 (relays\n * live in real git remotes now; the key stays readable as a\n * fallback and is removed in v0.3)\n *\n * plus the REAL git remotes (`remote.<name>.url`) that #249 maps relays onto:\n * `rig remote add origin <relay-url>` is `git remote add`, so `git remote -v`\n * shows rig's relays and plain git tooling round-trips them.\n *\n * All access goes through `execFile git` with argument arrays (same\n * injection posture as GitRepoReader — never a shell).\n */\n\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\n\nconst execFileAsync = promisify(execFile);\n\n/** The rig-relevant git config keys of one repository. */\nexport interface ToonRepoConfig {\n repoId?: string;\n owner?: string;\n relays: string[];\n}\n\nasync function git(\n repoPath: string,\n args: string[],\n allowExitCodes: number[] = []\n): Promise<{ stdout: string; exitCode: number }> {\n try {\n const { stdout } = await execFileAsync('git', args, {\n cwd: repoPath,\n encoding: 'utf-8',\n });\n return { stdout, exitCode: 0 };\n } catch (err) {\n const e = err as NodeJS.ErrnoException & {\n code?: number | string;\n stdout?: string;\n stderr?: string;\n };\n const exitCode = typeof e.code === 'number' ? e.code : undefined;\n if (exitCode !== undefined && allowExitCodes.includes(exitCode)) {\n return { stdout: e.stdout ?? '', exitCode };\n }\n throw new Error(\n `git ${args.join(' ')} failed${exitCode !== undefined ? ` (exit ${exitCode})` : ''}: ` +\n `${(e.stderr ?? e.message ?? '').trim()}`\n );\n }\n}\n\n/**\n * Resolve the repository worktree root for `cwd` via\n * `git rev-parse --show-toplevel`. Throws a clear error when `cwd` is not\n * inside a git repository.\n */\nexport async function resolveRepoRoot(cwd: string): Promise<string> {\n try {\n const { stdout } = await execFileAsync(\n 'git',\n ['rev-parse', '--show-toplevel'],\n { cwd, encoding: 'utf-8' }\n );\n const root = stdout.trim();\n if (!root) throw new Error('empty rev-parse output');\n return root;\n } catch (err) {\n const e = err as { stderr?: string; message?: string };\n throw new Error(\n `not a git repository (run rig inside a repo): ${(e.stderr ?? e.message ?? '').trim()}`\n );\n }\n}\n\n/** Read the `toon.*` git config keys of the repository at `repoPath`. */\nexport async function readToonConfig(repoPath: string): Promise<ToonRepoConfig> {\n // exit 1 = key unset (git config --get convention) — tolerated everywhere.\n const [repoId, owner, relays] = await Promise.all([\n git(repoPath, ['config', '--get', 'toon.repoid'], [1]),\n git(repoPath, ['config', '--get', 'toon.owner'], [1]),\n git(repoPath, ['config', '--get-all', 'toon.relay'], [1]),\n ]);\n const config: ToonRepoConfig = {\n relays: relays.stdout\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean),\n };\n const id = repoId.stdout.trim();\n if (repoId.exitCode === 0 && id) config.repoId = id;\n const own = owner.stdout.trim();\n if (owner.exitCode === 0 && own) config.owner = own;\n return config;\n}\n\n/** One configured git remote: its name + (possibly multiple) fetch URLs. */\nexport interface GitRemoteInfo {\n name: string;\n urls: string[];\n}\n\n/**\n * URLs of the git remote `name` (`remote.<name>.url`, multi-valued when\n * `git remote set-url --add` was used). `[]` when the remote does not exist.\n */\nexport async function getGitRemoteUrls(\n repoPath: string,\n name: string\n): Promise<string[]> {\n // exit 1 = key unset / invalid key — either way, no such remote.\n const { stdout } = await git(\n repoPath,\n ['config', '--get-all', `remote.${name}.url`],\n [1]\n );\n return stdout\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean);\n}\n\n/** All configured git remotes with their URLs (`git remote -v` data). */\nexport async function listGitRemotes(\n repoPath: string\n): Promise<GitRemoteInfo[]> {\n const { stdout } = await git(repoPath, ['remote']);\n const names = stdout\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean);\n const remotes: GitRemoteInfo[] = [];\n for (const name of names) {\n remotes.push({ name, urls: await getGitRemoteUrls(repoPath, name) });\n }\n return remotes;\n}\n\n/** `git remote add <name> <url>` — real git remote storage, never a shell. */\nexport async function addGitRemote(\n repoPath: string,\n name: string,\n url: string\n): Promise<void> {\n await git(repoPath, ['remote', 'add', name, url]);\n}\n\n/** `git remote remove <name>`. */\nexport async function removeGitRemote(\n repoPath: string,\n name: string\n): Promise<void> {\n await git(repoPath, ['remote', 'remove', name]);\n}\n\n/**\n * Persist the `toon.*` keys (repo-local config). Only supplied fields are\n * written; `relays` replaces the whole multi-valued list.\n */\nexport async function writeToonConfig(\n repoPath: string,\n config: { repoId?: string; owner?: string; relays?: string[] }\n): Promise<void> {\n if (config.repoId !== undefined) {\n await git(repoPath, ['config', 'toon.repoid', config.repoId]);\n }\n if (config.owner !== undefined) {\n await git(repoPath, ['config', 'toon.owner', config.owner]);\n }\n if (config.relays !== undefined && config.relays.length > 0) {\n // Replace the whole list: unset-all (exit 5 = key did not exist) + re-add.\n await git(repoPath, ['config', '--unset-all', 'toon.relay'], [5]);\n for (const relay of config.relays) {\n await git(repoPath, ['config', '--add', 'toon.relay', relay]);\n }\n }\n}\n","/**\n * Relays as origins (#249): the `rig remote` subcommand and the relay\n * resolution every paid command shares.\n *\n * Remotes are stored as REAL git remotes (`git remote add/remove` under the\n * hood), so `git remote -v` shows them and plain git tooling round-trips the\n * config — no parallel store. Paid commands resolve their relay as:\n *\n * 1. `--relay <url>` ad-hoc override, bypasses remotes\n * 2. a named remote `rig push <remote>` / `--remote <name>`\n * 3. the `origin` remote the default target\n * 4. git config `toon.relay` DEPRECATED v0.1 fallback (one-line nudge;\n * the key is removed in v0.3)\n * 5. error \"no origin configured — run `rig remote\n * add origin <relay-url>`\"\n *\n * A remote with multiple URLs (`git remote set-url --add` done by hand) is\n * refused BEFORE anything is fetched, uploaded, or paid: rig publishes to\n * exactly one relay per paid command (the #243 single-relay guard). One\n * carve-out: a default `origin` whose URLs are ALL non-relay is a plain git\n * remote — it is skipped like any single non-relay origin, never refused.\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n emitCliError,\n InvalidRelayUrlError,\n MultiUrlRemoteError,\n NoOriginConfiguredError,\n NotAGitRepositoryError,\n UnknownRemoteError,\n} from './errors.js';\nimport {\n addGitRemote,\n getGitRemoteUrls,\n listGitRemotes,\n readToonConfig,\n removeGitRemote,\n resolveRepoRoot,\n} from './git-config.js';\nimport type { CliIo } from './push.js';\n\n// ---------------------------------------------------------------------------\n// Relay URL validation\n// ---------------------------------------------------------------------------\n\nconst RELAY_PROTOCOLS = new Set(['ws:', 'wss:', 'http:', 'https:']);\n\n/** True when `url` parses and uses a relay scheme (ws/wss/http/https). */\nexport function isRelayUrl(url: string): boolean {\n try {\n return RELAY_PROTOCOLS.has(new URL(url).protocol);\n } catch {\n return false;\n }\n}\n\n/** Throw {@link InvalidRelayUrlError} unless `url` is a relay URL. */\nexport function assertRelayUrl(url: string, context: string): void {\n if (!isRelayUrl(url)) throw new InvalidRelayUrlError(url, context);\n}\n\n// ---------------------------------------------------------------------------\n// Relay resolution (shared by push + the event commands)\n// ---------------------------------------------------------------------------\n\n/** Where the resolved relay came from. */\nexport type RelaySource = 'relay-flag' | 'remote' | 'toon.relay';\n\nexport interface ResolvedRelays {\n /** Relay URLs to publish to (paid commands still enforce exactly one). */\n relays: string[];\n source: RelaySource;\n /** The git remote that supplied the URL (source === 'remote'). */\n remoteName?: string;\n /** One-line stderr note (toon.relay deprecation), when applicable. */\n nudge?: string;\n}\n\nexport interface ResolveRelaysOptions {\n /** `--relay` flag values (may be >1 — the command-level guard refuses). */\n relayFlags: string[];\n /** Explicitly requested remote (`rig push <remote>` / `--remote <name>`). */\n remoteName?: string | undefined;\n /** Repo worktree root; undefined when not inside a git repository. */\n repoRoot?: string | undefined;\n /** Deprecated `git config toon.relay` values (v0.1 fallback). */\n toonRelays: string[];\n}\n\n/**\n * Resolve the relay(s) for a paid command. Throws (before any payment):\n * {@link UnknownRemoteError}, {@link MultiUrlRemoteError},\n * {@link InvalidRelayUrlError}, {@link NoOriginConfiguredError}.\n */\nexport async function resolveRelays(\n opts: ResolveRelaysOptions\n): Promise<ResolvedRelays> {\n // 1. Ad-hoc --relay override: bypasses the configured remotes entirely.\n if (opts.relayFlags.length > 0) {\n return { relays: opts.relayFlags, source: 'relay-flag' };\n }\n\n // 2. Explicitly named remote: must exist, carry ONE URL, and be a relay.\n if (opts.remoteName !== undefined) {\n const urls =\n opts.repoRoot !== undefined\n ? await getGitRemoteUrls(opts.repoRoot, opts.remoteName)\n : [];\n if (urls.length === 0) throw new UnknownRemoteError(opts.remoteName);\n if (urls.length > 1) throw new MultiUrlRemoteError(opts.remoteName, urls);\n const url = urls[0] as string;\n assertRelayUrl(url, `remote ${JSON.stringify(opts.remoteName)}`);\n return { relays: urls, source: 'remote', remoteName: opts.remoteName };\n }\n\n // 3. Default remote: origin — when it looks like a relay. A PURELY\n // non-relay origin (e.g. a GitHub clone URL, even one with several\n // mirror push URLs) is skipped, not an error: rig shares git's remote\n // namespace, so pre-existing git origins must not break paid commands\n // that can still resolve via toon.relay. But the moment ANY of a\n // multi-URL origin's URLs is relay-shaped, the publish target is\n // ambiguous — refuse before anything is fetched, uploaded, or paid\n // (the #243 single-relay guard).\n let nonRelayOriginUrl: string | undefined;\n if (opts.repoRoot !== undefined) {\n const urls = await getGitRemoteUrls(opts.repoRoot, 'origin');\n if (urls.length === 1 && isRelayUrl(urls[0] as string)) {\n return { relays: urls, source: 'remote', remoteName: 'origin' };\n }\n if (urls.length > 1 && urls.some(isRelayUrl)) {\n throw new MultiUrlRemoteError('origin', urls);\n }\n // Reachable only when every remaining URL is non-relay (single relay URL\n // returned above; multi-URL with any relay URL threw above), so urls[0]\n // is guaranteed non-relay — NoOriginConfiguredError's message relies on\n // that (\"the existing origin is not a relay URL\").\n if (urls.length > 0) nonRelayOriginUrl = urls[0] as string;\n }\n\n // 4. Deprecated v0.1 fallback: git config toon.relay (nudges to migrate).\n if (opts.toonRelays.length > 0) {\n return {\n relays: opts.toonRelays,\n source: 'toon.relay',\n nudge:\n 'note: git config toon.relay is deprecated (removed in v0.3) — ' +\n `migrate: rig remote add origin ${opts.toonRelays[0]}`,\n };\n }\n\n // 5. Nothing resolved.\n throw new NoOriginConfiguredError(nonRelayOriginUrl);\n}\n\n/**\n * Refusal line for >1 resolved relays: the StandalonePublisher publishes to\n * exactly one relay per paid command, and multiple can arrive without\n * explicit intent (repeated --relay flags, a multi-valued toon.relay).\n * `nothingHappened` names what was NOT done, e.g. 'Nothing was uploaded or\n * paid.'\n */\nexport function singleRelayRefusal(\n resolved: ResolvedRelays,\n nothingHappened: string\n): string {\n const fix =\n resolved.source === 'relay-flag'\n ? 'pass exactly one --relay <url>'\n : 'trim git config toon.relay to one URL (better: migrate — ' +\n '`rig remote add origin <relay-url>`)';\n return (\n `rig publishes to a single relay, but ${resolved.relays.length} are ` +\n `configured (${resolved.relays.join(', ')}) — ${fix}. ${nothingHappened}`\n );\n}\n\n// ---------------------------------------------------------------------------\n// rig remote <add|remove|list>\n// ---------------------------------------------------------------------------\n\nexport const REMOTE_USAGE = `Usage: rig remote <add|remove|list> [args] [options]\n\nManage the relays this repo publishes to. Remotes are stored as REAL git\nremotes (\\`git remote -v\\` shows them; plain git tooling round-trips). Paid\ncommands publish via the \"origin\" remote by default; \\`rig push <remote>\\`\nand \\`--remote <name>\\` target another one. Free — nothing is published or\npaid.\n\nCommands:\n add <name> <relay-url> add a remote pointing at a relay (the URL must be\n ws://, wss://, http://, or https://)\n remove <name> remove a remote\n list list remote names + URLs (the default subcommand)\n\nOptions:\n --json machine-readable envelope (all subcommands)\n -h, --help show this help`;\n\n/** Deps subset `rig remote` needs (free — no publisher, no identity). */\nexport interface RemoteDeps {\n io: CliIo;\n cwd: string;\n}\n\n/** Run `rig remote …`; returns the process exit code. */\nexport async function runRemote(\n args: string[],\n deps: RemoteDeps\n): Promise<number> {\n const { io } = deps;\n\n let sub: string | undefined;\n let rest: string[];\n let json: boolean;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: true,\n });\n if (values.help) {\n io.out(REMOTE_USAGE);\n return 0;\n }\n json = values.json ?? false;\n [sub, ...rest] = positionals;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(REMOTE_USAGE);\n return 2;\n }\n\n // Argument-shape validation (exit 2) before touching the repository.\n switch (sub) {\n case undefined:\n case 'list':\n if (rest.length > 0) {\n io.err(`rig remote list takes no arguments (got ${rest.join(' ')})`);\n io.err(REMOTE_USAGE);\n return 2;\n }\n break;\n case 'add': {\n if (rest.length !== 2) {\n io.err('usage: rig remote add <name> <relay-url>');\n io.err(REMOTE_USAGE);\n return 2;\n }\n const url = rest[1] as string;\n if (!isRelayUrl(url)) {\n io.err(\n `cannot add remote: ${JSON.stringify(url)} is not a relay URL — ` +\n 'relays are ws://, wss://, http://, or https://'\n );\n return 2;\n }\n break;\n }\n case 'remove':\n if (rest.length !== 1) {\n io.err('usage: rig remote remove <name>');\n io.err(REMOTE_USAGE);\n return 2;\n }\n break;\n default:\n io.err(`unknown rig remote subcommand: ${sub}`);\n io.err(REMOTE_USAGE);\n return 2;\n }\n\n try {\n let repoRoot: string;\n try {\n repoRoot = await resolveRepoRoot(deps.cwd);\n } catch {\n throw new NotAGitRepositoryError(deps.cwd);\n }\n\n switch (sub) {\n case undefined:\n case 'list': {\n const remotes = await listGitRemotes(repoRoot);\n if (json) {\n io.emitJson({ command: 'remote', remotes });\n return 0;\n }\n if (remotes.length === 0) {\n io.out(\n 'no remotes configured — add one: rig remote add origin <relay-url>'\n );\n return 0;\n }\n for (const remote of remotes) {\n for (const url of remote.urls) {\n io.out(\n `${remote.name}\\t${url}` +\n (isRelayUrl(url) ? '' : '\\t(not a relay URL — ignored by rig)')\n );\n }\n if (remote.urls.length > 1) {\n io.err(\n `warning: remote \"${remote.name}\" has ${remote.urls.length} ` +\n 'URLs — rig supports one relay URL per remote (fix with ' +\n `\\`git remote set-url ${remote.name} <relay-url>\\`)`\n );\n }\n }\n return 0;\n }\n\n case 'add': {\n const [name, url] = rest as [string, string];\n const existing = await getGitRemoteUrls(repoRoot, name);\n if (existing.length > 0) {\n const detail =\n `remote ${JSON.stringify(name)} already exists ` +\n `(${existing.join(', ')}) — nothing changed. Point it ` +\n `somewhere else with \\`git remote set-url ${name} <relay-url>\\`, ` +\n `or \\`rig remote remove ${name}\\` first.`;\n if (json) {\n io.emitJson({\n command: 'remote',\n error: 'remote_exists',\n detail,\n remote: name,\n urls: existing,\n });\n }\n io.err(detail);\n return 1;\n }\n await addGitRemote(repoRoot, name, url);\n if (!json) io.out(`Added remote ${name} → ${url}`);\n if (name === 'origin') {\n if (!json) {\n io.out(\n '`rig push` and the event commands now publish here by default.'\n );\n }\n const toonConfig = await readToonConfig(repoRoot);\n if (toonConfig.relays.length > 0) {\n io.err(\n `note: git config toon.relay (${toonConfig.relays.join(', ')}) ` +\n 'is deprecated and now shadowed by the origin remote — drop ' +\n 'it with `git config --unset-all toon.relay` (the key is ' +\n 'removed in v0.3).'\n );\n }\n }\n if (json) {\n io.emitJson({ command: 'remote', action: 'add', name, url });\n }\n return 0;\n }\n\n case 'remove': {\n const name = rest[0] as string;\n const existing = await getGitRemoteUrls(repoRoot, name);\n if (existing.length === 0) {\n const detail =\n `no remote named ${JSON.stringify(name)} — ` +\n '`rig remote list` shows configured remotes.';\n if (json) {\n io.emitJson({\n command: 'remote',\n error: 'unknown_remote',\n detail,\n remote: name,\n });\n }\n io.err(detail);\n return 1;\n }\n await removeGitRemote(repoRoot, name);\n if (json) {\n io.emitJson({ command: 'remote', action: 'remove', name });\n } else {\n io.out(`Removed remote ${name}`);\n }\n return 0;\n }\n\n /* v8 ignore next 2 -- unreachable: validated above */\n default:\n return 2;\n }\n } catch (err) {\n return emitCliError(io, json, 'remote', err);\n }\n}\n","/**\n * `rig channel` — the payment channels paid rig commands hold (#262), plus\n * the explicit money lifecycle (#263): open / close / settle.\n *\n * Paid commands open a channel lazily on first use and RECORD it in the\n * peer→channel map under `TOON_CLIENT_HOME` (default `~/.toon-client`,\n * `rig-channels.json`), so later invocations resume the same channel instead\n * of opening (and funding) a new one per run. `rig channel list` reads that\n * map plus the client's nonce-watermark store (`channels.json`) and shows\n * current holdings — a FREE command: local files only, no client start, no\n * network, no payment (and therefore no `@toon-protocol/client` import).\n *\n * The lifecycle subcommands are ON-CHAIN wallet operations (gas + collateral\n * movement, not relay claims), so they follow the push confirm idiom: print\n * what will happen, then require `--yes` (mandatory in a non-TTY session) or\n * an interactive y/N confirm; `--json` without `--yes` is a pure plan.\n *\n * open the SAME resume-or-open path lazy paid writes use (factored, not\n * forked): resumes the recorded channel when one is live, else\n * opens + records a fresh one; `--deposit` adds collateral on top.\n * close starts the settlement challenge window for a recorded channel —\n * the channel stops paying immediately; collateral is released by\n * `settle` once the window elapses.\n * settle releases the remaining collateral after the challenge window\n * (the client refuses a too-early settle BEFORE spending gas).\n *\n * close/settle recover deposits stranded by pre-#262 one-channel-per-run\n * behaviour: any channel present in the map can be driven to settled.\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n channelStatus,\n ChannelMapStore,\n resolveChannelPaths,\n type ChannelMapRecord,\n type WatermarkEntry,\n} from '../standalone/channel-map.js';\nimport { emitCliError } from './errors.js';\nimport {\n defaultLoadStandalone,\n identityReport,\n type CliIo,\n type IdentityReport,\n type PushDeps,\n} from './push.js';\nimport { renderIdentityLine } from './render.js';\nimport type { StandaloneContext } from './standalone-context.js';\nimport type { StandaloneMoneyOps } from '../standalone/money.js';\n\nexport const CHANNEL_USAGE = `Usage: rig channel <subcommand>\n\nManage the payment channels paid rig commands hold with relay/store peers.\nPaid commands open a channel lazily on first use and record it under\nTOON_CLIENT_HOME (default ~/.toon-client, rig-channels.json), so later\ninvocations resume the same channel instead of opening a new one per run.\n\nSubcommands:\n list [--json] show recorded channels — peer, chain, channel id, deposit,\n cumulative claimed, status. Free: reads local state only.\n\n open [--peer <ilp-destination>] [--deposit <base-units>]\n explicitly open the payment channel for a peer — the SAME\n path paid commands use lazily: resumes the recorded live\n channel if one exists (no on-chain spend), else opens and\n records a fresh one (locks the peer-negotiated initial\n deposit on-chain). --peer is the ILP destination to anchor\n to (default: the configured destination, e.g. the devnet\n apex); --deposit adds that much extra collateral after the\n open/resume. On-chain: asks for confirmation (--yes skips).\n\n close <channelId>\n close a recorded channel — an on-chain tx that starts the\n settlement challenge window (the peer's settlementTimeout).\n The channel stops paying immediately; the remaining\n collateral stays locked until \\`rig channel settle\\` after\n the window elapses. Asks for confirmation (--yes skips).\n\n settle <channelId>\n settle a closed channel once its challenge window elapsed —\n an on-chain tx that releases the remaining collateral back\n to your wallet. Refused (without spending gas) while the\n window is still open. Asks for confirmation (--yes skips).\n\nCommon options: --json (machine-readable envelopes; without --yes lifecycle\ncommands emit a pure plan and execute nothing), --yes, -h/--help.`;\n\n/**\n * What `rig channel` needs from the command environment — the shared paid\n * command deps (io/env/cwd + injectable standalone loader): `list` uses only\n * io/env, the lifecycle subcommands load the standalone context.\n */\nexport type ChannelDeps = PushDeps;\n\n/** One channel in the `--json` envelope (unknowns are null, bigints strings). */\ninterface ChannelJson {\n channelId: string;\n peerId: string;\n identity: string;\n destination: string;\n chain: string;\n tokenNetwork: string;\n depositTotal: string | null;\n cumulativeClaimed: string | null;\n nonce: number | null;\n status: 'open' | 'closing' | 'settleable' | 'settled';\n openedAt: string;\n lastUsedAt: string;\n}\n\n/** Route one `rig channel …` invocation; returns the exit code. */\nexport async function runChannel(\n args: string[],\n deps: ChannelDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n switch (sub) {\n case 'list':\n return runChannelList(rest, deps);\n case 'open':\n return runChannelOpen(rest, deps);\n case 'close':\n return runChannelWithdrawStep(rest, deps, 'close');\n case 'settle':\n return runChannelWithdrawStep(rest, deps, 'settle');\n case 'help':\n case '--help':\n case '-h':\n io.out(CHANNEL_USAGE);\n return 0;\n case undefined:\n io.err(CHANNEL_USAGE);\n return 2;\n default:\n io.err(`rig channel: unknown subcommand ${JSON.stringify(sub)}`);\n io.err(CHANNEL_USAGE);\n return 2;\n }\n}\n\n// ---------------------------------------------------------------------------\n// list (#262)\n// ---------------------------------------------------------------------------\n\nfunction runChannelList(args: string[], deps: ChannelDeps): number {\n const { io, env } = deps;\n let json = false;\n try {\n const { values } = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (values.help) {\n io.out(CHANNEL_USAGE);\n return 0;\n }\n json = values.json ?? false;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CHANNEL_USAGE);\n return 2;\n }\n\n try {\n const paths = resolveChannelPaths(env);\n const store = new ChannelMapStore(paths);\n const records = store.list();\n const rows = records.map((record) => describeChannel(record, store));\n\n if (json) {\n io.emitJson({ command: 'channel list', channels: rows });\n return 0;\n }\n if (rows.length === 0) {\n io.out(\n 'No payment channels recorded — paid rig commands (push, issue, ' +\n 'comment, pr) record the channel they open on first use, and ' +\n '`rig channel open` records an explicit one.'\n );\n return 0;\n }\n io.out(\n `${rows.length} payment channel${rows.length === 1 ? '' : 's'} ` +\n `recorded in ${paths.mapPath}:`\n );\n for (const row of rows) {\n io.out('');\n for (const line of renderChannel(row)) io.out(line);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'channel list', err);\n }\n}\n\n/** Join one map record with its watermark state. */\nfunction describeChannel(\n record: ChannelMapRecord,\n store: ChannelMapStore\n): ChannelJson {\n const watermark: WatermarkEntry | undefined = store.readWatermark(\n record.channelId\n );\n return {\n channelId: record.channelId,\n peerId: record.peerId,\n identity: record.identity,\n destination: record.destination,\n chain: record.chain,\n tokenNetwork: record.tokenNetwork,\n depositTotal: record.depositTotal ?? null,\n cumulativeClaimed: watermark?.cumulativeAmount ?? null,\n nonce: watermark?.nonce ?? null,\n status: channelStatus(watermark),\n openedAt: record.openedAt,\n lastUsedAt: record.lastUsedAt,\n };\n}\n\nfunction renderChannel(row: ChannelJson): string[] {\n const claimed =\n row.cumulativeClaimed === null\n ? 'unknown (no local claim state)'\n : `${row.cumulativeClaimed} base units (nonce ${row.nonce})`;\n return [\n `channel ${row.channelId} [${row.status}]`,\n ` peer ${row.destination} (${row.peerId})`,\n ` identity ${row.identity.slice(0, 8)}…`,\n ` chain ${row.chain}` +\n (row.tokenNetwork ? ` token-network ${row.tokenNetwork}` : ''),\n ` deposited ${row.depositTotal ?? 'unrecorded'}` +\n (row.depositTotal ? ' base units' : ''),\n ` claimed ${claimed}`,\n ` opened ${row.openedAt} (last used ${row.lastUsedAt})`,\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Shared money-command plumbing (#263)\n// ---------------------------------------------------------------------------\n\n/** Load the standalone context and require its money-ops surface. */\nasync function loadMoneyContext(\n deps: ChannelDeps,\n options?: { channelDestination?: string }\n): Promise<{ ctx: StandaloneContext; money: StandaloneMoneyOps }> {\n const ctx = await (deps.loadStandalone ?? defaultLoadStandalone)({\n env: deps.env,\n cwd: deps.cwd,\n warn: (line) => deps.io.err(line),\n ...(options?.channelDestination\n ? { channelDestination: options.channelDestination }\n : {}),\n });\n const money = ctx.money;\n if (!money) {\n await ctx.stop().catch(() => undefined);\n throw new Error(\n 'this standalone loader does not expose money operations — ' +\n 'channel open/close/settle need the #263 loader'\n );\n }\n return { ctx, money };\n}\n\n/**\n * The push-idiom confirm gate for an ON-CHAIN money operation. Returns the\n * exit code to bail out with, or undefined to proceed. In `--json` mode\n * without `--yes` the caller emits its plan envelope (exit 0) — this gate\n * signals that with `'json-plan'`.\n */\nasync function confirmOnChain(\n io: CliIo,\n flags: { yes: boolean; json: boolean },\n question: string\n): Promise<'proceed' | 'json-plan' | number> {\n if (flags.yes) return 'proceed';\n if (flags.json) return 'json-plan';\n if (!io.isInteractive) {\n io.err(\n 'refusing to move on-chain funds without confirmation in a ' +\n 'non-interactive session — re-run with --yes (or use --json for a plan)'\n );\n return 1;\n }\n const proceed = await io.confirm(question);\n if (proceed) return 'proceed';\n io.err('aborted — no on-chain transaction was sent.');\n return 1;\n}\n\n/** Format a string-encoded unix-seconds timestamp for humans. */\nfunction formatUnixSeconds(value: string): string {\n const ms = Number(value) * 1000;\n return Number.isFinite(ms) ? new Date(ms).toISOString() : `t=${value}s`;\n}\n\n/** Whole seconds from now until a string-encoded unix-seconds timestamp. */\nfunction secondsUntil(value: string, nowSec: number): number {\n return Number(value) - nowSec;\n}\n\n// ---------------------------------------------------------------------------\n// open\n// ---------------------------------------------------------------------------\n\ninterface ChannelOpenJson {\n command: 'channel open';\n identity: IdentityReport;\n executed: boolean;\n plan: { destination: string | null; deposit: string | null };\n result?: {\n channelId: string;\n resumed: boolean;\n destination: string;\n chain: string | null;\n peerId: string | null;\n depositTotal: string | null;\n depositAdded: string | null;\n depositTxHash: string | null;\n };\n hint?: string;\n}\n\nasync function runChannelOpen(\n args: string[],\n deps: ChannelDeps\n): Promise<number> {\n const { io } = deps;\n let peer: string | undefined;\n let deposit: bigint | undefined;\n let yes = false;\n let json = false;\n try {\n const { values } = parseArgs({\n args,\n options: {\n peer: { type: 'string' },\n deposit: { type: 'string' },\n yes: { type: 'boolean', default: false },\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (values.help) {\n io.out(CHANNEL_USAGE);\n return 0;\n }\n peer = values.peer;\n yes = values.yes ?? false;\n json = values.json ?? false;\n if (values.deposit !== undefined) {\n if (!/^\\d+$/.test(values.deposit) || BigInt(values.deposit) <= 0n) {\n throw new Error(\n `--deposit must be a positive base-unit integer, got ${JSON.stringify(values.deposit)}`\n );\n }\n deposit = BigInt(values.deposit);\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CHANNEL_USAGE);\n return 2;\n }\n\n let ctx: StandaloneContext | undefined;\n try {\n const loaded = await loadMoneyContext(deps, {\n ...(peer ? { channelDestination: peer } : {}),\n });\n ctx = loaded.ctx;\n const identity = identityReport(ctx);\n const plan = {\n destination: peer ?? null,\n deposit: deposit?.toString() ?? null,\n };\n\n if (!json) {\n io.out('Channel open plan:');\n io.out(` peer (ILP) ${peer ?? '(configured default destination)'}`);\n io.out(\n ` deposit ${deposit !== undefined ? `+${deposit} base units of extra collateral after the open/resume` : 'none beyond the peer-negotiated initial deposit'}`\n );\n io.out(renderIdentityLine(identity));\n io.out(\n 'If a live channel is already recorded for this peer it is RESUMED ' +\n '(no on-chain spend); otherwise an on-chain channel open locks the ' +\n 'peer-negotiated initial deposit from your wallet (plus gas).'\n );\n }\n\n const gate = await confirmOnChain(\n io,\n { yes, json },\n 'Proceed with on-chain channel open? [y/N] '\n );\n if (gate === 'json-plan') {\n io.emitJson({\n command: 'channel open',\n identity,\n executed: false,\n plan,\n hint: 'plan only — re-run with --yes to open (on-chain: locks collateral and spends gas)',\n } satisfies ChannelOpenJson);\n return 0;\n }\n if (gate !== 'proceed') return gate;\n\n const outcome = await loaded.money.openChannel(\n deposit !== undefined ? { deposit } : undefined\n );\n\n if (json) {\n io.emitJson({\n command: 'channel open',\n identity,\n executed: true,\n plan,\n result: {\n channelId: outcome.channelId,\n resumed: outcome.resumed,\n destination: outcome.destination,\n chain: outcome.chain ?? null,\n peerId: outcome.peerId ?? null,\n depositTotal: outcome.depositTotal ?? null,\n depositAdded: outcome.depositAdded ?? null,\n depositTxHash: outcome.depositTxHash ?? null,\n },\n } satisfies ChannelOpenJson);\n return 0;\n }\n io.out(\n outcome.resumed\n ? `Resumed recorded channel ${outcome.channelId} — no on-chain open was needed.`\n : `Opened channel ${outcome.channelId}${outcome.chain ? ` on ${outcome.chain}` : ''} and recorded it for reuse.`\n );\n io.out(` peer ${outcome.destination}${outcome.peerId ? ` (${outcome.peerId})` : ''}`);\n if (outcome.depositAdded) {\n io.out(\n ` deposited +${outcome.depositAdded} base units` +\n (outcome.depositTxHash ? ` (tx ${outcome.depositTxHash})` : '')\n );\n }\n if (outcome.depositTotal) {\n io.out(` collateral ${outcome.depositTotal} base units total on-chain`);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'channel open', err);\n } finally {\n await stopQuietly(ctx);\n }\n}\n\n// ---------------------------------------------------------------------------\n// close / settle (the two halves of withdraw)\n// ---------------------------------------------------------------------------\n\ninterface WithdrawJson {\n command: 'channel close' | 'channel settle';\n identity: IdentityReport;\n executed: boolean;\n channelId: string;\n result?: {\n txHash: string | null;\n closedAt?: string;\n settleableAt?: string;\n };\n hint?: string;\n}\n\n/**\n * Fail-fast local pre-checks from the recorded watermark timers — before any\n * identity resolution or client start (chain state stays authoritative: the\n * client re-checks before spending gas).\n */\nfunction withdrawPrecheck(\n step: 'close' | 'settle',\n channelId: string,\n watermark: WatermarkEntry | undefined,\n nowSec: number\n): string | undefined {\n const status = channelStatus(watermark, nowSec);\n if (status === 'settled') {\n return `channel ${channelId} is already settled — nothing left to ${step}.`;\n }\n if (step === 'close') {\n if (status === 'closing' || status === 'settleable') {\n const at = watermark?.settleableAt;\n return (\n `channel ${channelId} is already closing — ` +\n (status === 'settleable'\n ? 'its challenge window has elapsed; run `rig channel settle` to release the collateral.'\n : `settleable at ${at ? formatUnixSeconds(at) : 'the end of its challenge window'} (run \\`rig channel settle\\` then).`)\n );\n }\n return undefined;\n }\n // settle\n if (status === 'open') {\n return (\n `channel ${channelId} is not closed — run \\`rig channel close ${channelId}\\` ` +\n 'first (settle only releases collateral after the challenge window of a closed channel).'\n );\n }\n if (status === 'closing' && watermark?.settleableAt !== undefined) {\n const remain = secondsUntil(watermark.settleableAt, nowSec);\n return (\n `channel ${channelId} is not settleable yet — the challenge window is ` +\n `still open (${remain}s remain, settleable at ${formatUnixSeconds(watermark.settleableAt)}). ` +\n 'Nothing was spent; re-run after that time.'\n );\n }\n return undefined;\n}\n\nasync function runChannelWithdrawStep(\n args: string[],\n deps: ChannelDeps,\n step: 'close' | 'settle'\n): Promise<number> {\n const { io, env } = deps;\n const command = `channel ${step}` as WithdrawJson['command'];\n let channelId: string | undefined;\n let yes = false;\n let json = false;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: {\n yes: { type: 'boolean', default: false },\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: true,\n });\n if (values.help) {\n io.out(CHANNEL_USAGE);\n return 0;\n }\n yes = values.yes ?? false;\n json = values.json ?? false;\n if (positionals.length !== 1) {\n throw new Error(\n `rig channel ${step} takes exactly one <channelId> (got ${positionals.length}) — \\`rig channel list\\` shows recorded channels`\n );\n }\n channelId = positionals[0] as string;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CHANNEL_USAGE);\n return 2;\n }\n\n let ctx: StandaloneContext | undefined;\n try {\n // ── Local state: the recorded channel + its watermark (free, fail-fast) ──\n const store = new ChannelMapStore(resolveChannelPaths(env));\n const record = store.list().find((r) => r.channelId === channelId);\n if (!record) {\n throw new Error(\n `no recorded channel ${JSON.stringify(channelId)} — \\`rig channel list\\` shows the channels this identity holds`\n );\n }\n const watermark = store.readWatermark(channelId);\n const nowSec = Math.floor(Date.now() / 1000);\n const refusal = withdrawPrecheck(step, channelId, watermark, nowSec);\n if (refusal) throw new Error(refusal);\n\n // ── Identity (must match the channel's opener — its claims/keys) ────────\n const loaded = await loadMoneyContext(deps);\n ctx = loaded.ctx;\n const identity = identityReport(ctx);\n if (record.identity !== identity.pubkey) {\n throw new Error(\n `channel ${channelId} was opened by identity ${record.identity.slice(0, 8)}… ` +\n `but the active identity is ${identity.pubkey.slice(0, 8)}… ` +\n `(from ${identity.sourceLabel}) — on-chain ${step} must be signed by ` +\n \"the opener's wallet key. Switch RIG_MNEMONIC (or the keystore) to that identity.\"\n );\n }\n\n // ── Plan + confirm gate ──────────────────────────────────────────────────\n if (!json) {\n const claimed = watermark?.cumulativeAmount;\n io.out(`Channel ${step} plan:`);\n io.out(` channel ${channelId} [${channelStatus(watermark, nowSec)}]`);\n io.out(` peer ${record.destination} (${record.peerId})`);\n io.out(` chain ${record.chain}`);\n io.out(\n ` deposited ${record.depositTotal ?? 'unrecorded'}` +\n (claimed !== undefined ? ` claimed ${claimed} base units` : '')\n );\n io.out(renderIdentityLine(identity));\n if (step === 'close') {\n io.out(\n 'Closing is an ON-CHAIN transaction (gas) that starts the settlement ' +\n 'challenge window: the channel stops paying immediately, and the ' +\n 'remaining collateral stays locked until `rig channel settle` ' +\n 'succeeds after the window elapses.'\n );\n } else {\n io.out(\n 'Settling is an ON-CHAIN transaction (gas) that releases the ' +\n \"remaining collateral back to your wallet. The chain's challenge \" +\n 'window is authoritative — a too-early settle is refused before ' +\n 'any gas is spent.'\n );\n }\n }\n const gate = await confirmOnChain(\n io,\n { yes, json },\n `Proceed with on-chain channel ${step}? [y/N] `\n );\n if (gate === 'json-plan') {\n io.emitJson({\n command,\n identity,\n executed: false,\n channelId,\n hint: `plan only — re-run with --yes to ${step} (on-chain transaction)`,\n } satisfies WithdrawJson);\n return 0;\n }\n if (gate !== 'proceed') return gate;\n\n // ── Execute ──────────────────────────────────────────────────────────────\n if (step === 'close') {\n const result = await loaded.money.closeChannel(record);\n if (json) {\n io.emitJson({\n command,\n identity,\n executed: true,\n channelId,\n result: {\n txHash: result.txHash ?? null,\n closedAt: result.closedAt,\n settleableAt: result.settleableAt,\n },\n } satisfies WithdrawJson);\n return 0;\n }\n io.out(\n `Channel ${channelId} is closing` +\n (result.txHash ? ` (tx ${result.txHash})` : '') +\n '.'\n );\n io.out(\n ` challenge window: settleable at ${formatUnixSeconds(result.settleableAt)} ` +\n `(~${Math.max(0, secondsUntil(result.settleableAt, nowSec))}s from now)`\n );\n io.out(\n ` run \\`rig channel settle ${channelId}\\` after that time to release the collateral.`\n );\n return 0;\n }\n\n const result = await loaded.money.settleChannel(record);\n if (json) {\n io.emitJson({\n command,\n identity,\n executed: true,\n channelId,\n result: { txHash: result.txHash ?? null },\n } satisfies WithdrawJson);\n return 0;\n }\n io.out(\n `Channel ${channelId} settled` +\n (result.txHash ? ` (tx ${result.txHash})` : '') +\n ' — the remaining collateral was released to your wallet.'\n );\n return 0;\n } catch (err) {\n return emitCliError(io, json, command, err);\n } finally {\n await stopQuietly(ctx);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Small shared helpers\n// ---------------------------------------------------------------------------\n\nasync function stopQuietly(ctx: StandaloneContext | undefined): Promise<void> {\n if (!ctx) return;\n try {\n await ctx.stop();\n } catch {\n // best-effort teardown\n }\n}\n","/**\n * The single-event `rig` subcommands (#231): issue / comment / pr, where\n * `pr` nests `create` and `status` (#250 moved the NIP-34 status publish\n * from top-level `rig status` to `rig pr status` — bare `rig status` now\n * passes through to `git status`).\n *\n * One shared pipeline behind four thin arg-parsers, mirroring `rig push`\n * (./push.ts) exactly: repo addressing from the `toon.*` git config keys\n * `rig init` writes (`--repo-id`/`--owner` override; actionable \"run\n * `rig init`\" error when unconfigured), a fee-quoting confirm gate (`--yes`\n * skips; a non-TTY session without it refuses; `--json` without `--yes` is a\n * pure estimate), and ONE transport: build the NIP-34 event locally\n * (../nip34-events.ts — the same builders the toon-clientd daemon uses) and\n * pay-to-publish through the embedded, nonce-guarded StandalonePublisher\n * (#248: the CLI is standalone-only; the daemon keeps its own toon_git_* MCP\n * surface). The relay resolves like `rig push` (#249): `--remote <name>`\n * (default: the `origin` git remote), `--relay <url>` as an ad-hoc override\n * that bypasses remotes, deprecated `git config toon.relay` as a nudged\n * fallback. Publishes go to a SINGLE relay; multiple configured relays and\n * multi-URL remotes are refused before anything is paid (same guard as push).\n *\n * `rig pr create --range` runs REAL `git format-patch --stdout <range>` in\n * the local repository and publishes its output as the kind:1617 content —\n * one event for the whole series (cover-letter threading is out of scope in\n * v1; see the usage text).\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { parseArgs } from 'node:util';\nimport {\n REPOSITORY_ANNOUNCEMENT_KIND,\n STATUS_APPLIED_KIND,\n STATUS_CLOSED_KIND,\n STATUS_DRAFT_KIND,\n STATUS_OPEN_KIND,\n} from '@toon-protocol/core/nip34';\nimport {\n buildComment,\n buildIssue,\n buildPatch,\n buildStatus,\n type StatusKind,\n type UnsignedEvent,\n} from '../nip34-events.js';\nimport { GitRepoReader } from '../repo-reader.js';\nimport {\n serializeEventReceipt,\n type GitEventResponse,\n type GitRepoAddr,\n type GitStatusValue,\n} from '../routes.js';\nimport { emitCliError, UnconfiguredRepoAddressError } from './errors.js';\nimport { readToonConfig, resolveRepoRoot, type ToonRepoConfig } from './git-config.js';\nimport {\n defaultLoadStandalone,\n identityReport,\n type IdentityReport,\n type PushDeps,\n} from './push.js';\nimport { resolveRelays, singleRelayRefusal } from './remote.js';\nimport { feeLabel, renderEventPlan, renderEventReceipt } from './render.js';\nimport type { StandaloneContext } from './standalone-context.js';\n\n// ---------------------------------------------------------------------------\n// Deps\n// ---------------------------------------------------------------------------\n\n/** Push deps plus a stdin reader (issue-body fallback); tests inject both. */\nexport interface EventCommandDeps extends PushDeps {\n /** Read all of stdin as UTF-8 (default: the real process stdin). */\n readStdin?: () => Promise<string>;\n}\n\nconst defaultReadStdin = async (): Promise<string> => {\n // Never block waiting for keyboard input (e.g. stdout piped but stdin a\n // TTY): an interactive stdin yields no body, which surfaces as the clear\n // \"body is empty\" error instead of a hang.\n if (process.stdin.isTTY) return '';\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString('utf-8');\n};\n\n// ---------------------------------------------------------------------------\n// Usage\n// ---------------------------------------------------------------------------\n\n/** Flags every single-event subcommand shares (mirrors `rig push`). */\nconst COMMON_FLAGS_USAGE = ` --repo-id <id> repository id / NIP-34 d-tag (default: git config\n toon.repoid — run \\`rig init\\` to set it)\n --owner <pubkey> repository owner pubkey, 64-char hex (default: git config\n toon.owner, then the active identity)\n --remote <name> publish via this configured git remote (default: the\n \"origin\" remote — \\`rig remote add origin <relay-url>\\`)\n --relay <url> ad-hoc relay override (exactly one) — bypasses the\n configured remotes. The deprecated v0.1 \\`git config\n toon.relay\\` still works as a fallback, with a nudge\n --yes skip the fee confirmation (required when not a TTY)\n --json machine-readable receipt; without --yes it is a pure\n estimate (nothing published, exit 0)\n -h, --help show this help`;\n\nexport const ISSUE_USAGE = `Usage: rig issue create --title <title> [options]\n\nFile an issue (kind:1621) against a TOON repo — a paid publish; writes are\npermanent and non-refundable. The repo address (30617:<owner>:<repoId>) comes\nfrom the toon.* git config keys \\`rig init\\` writes.\n\nBody source (exactly one): --body, --body-file, or piped stdin.\n\nOptions:\n --title <title> issue title (subject tag) [required]\n --body <text> issue body (Markdown)\n --body-file <path> read the issue body from a file\n --label <label> label (t tag); repeatable\n${COMMON_FLAGS_USAGE}`;\n\nexport const COMMENT_USAGE = `Usage: rig comment <root-event-id> --body <text> [options]\n\nComment (kind:1622) on an issue or patch — a paid publish; writes are\npermanent and non-refundable. <root-event-id> is the 64-char hex id of the\nkind:1621 issue / kind:1617 patch being commented on.\n\nOptions:\n --body <text> comment body (Markdown) [required]\n --parent-author <pubkey> pubkey of the TARGET event's author (p threading\n tag; default: the repo owner)\n --marker <root|reply> e-tag marker (default: root — commenting directly\n on the issue/patch)\n${COMMON_FLAGS_USAGE}`;\n\nexport const PR_CREATE_USAGE = `Usage: rig pr create --title <title> (--range <range> | --patch-file <path>) [options]\n\nPublish a patch (kind:1617) whose content is REAL \\`git format-patch\\` output —\na paid publish; writes are permanent and non-refundable. --range runs\n\\`git format-patch --stdout <range>\\` in the local repository and derives the\ncommit/parent-commit tags; --patch-file publishes a pre-generated patch\nverbatim. A multi-commit range publishes ONE kind:1617 event carrying the\nfull series text — cover-letter threading (one event per commit) is out of\nscope in v1.\n\nOptions:\n --title <title> patch/PR title (subject tag) [required]\n --range <range> revision range for format-patch: <rev>, <rev>..<rev>,\n or <rev>...<rev> (mutually exclusive with --patch-file)\n --patch-file <path> literal patch text to publish\n --branch <name> branch name (t tag)\n${COMMON_FLAGS_USAGE}`;\n\nexport const PR_STATUS_USAGE = `Usage: rig pr status <target-event-id> <open|applied|closed|draft> [options]\n\nSet the status of an issue or patch — a paid publish; writes are permanent\nand non-refundable. Publishes kind:1630 (open), 1631 (applied), 1632\n(closed), or 1633 (draft) against the 64-char hex id of the target event,\nwith the repo a-tag attached so readers can scope a status stream to the\nrepository. (This command was \\`rig status\\` before v2 — bare \\`rig status\\`\nnow passes through to \\`git status\\`.)\n\nOptions:\n${COMMON_FLAGS_USAGE}`;\n\nexport const PR_USAGE = `${PR_CREATE_USAGE}\n\n${PR_STATUS_USAGE}`;\n\n// ---------------------------------------------------------------------------\n// Shared flag parsing\n// ---------------------------------------------------------------------------\n\nconst HEX64_RE = /^[0-9a-f]{64}$/;\n\nfunction assertHex64(value: string, what: string): void {\n if (!HEX64_RE.test(value)) {\n throw new Error(\n `${what} must be a 64-char lowercase hex id (got ${JSON.stringify(value)})`\n );\n }\n}\n\n/** parseArgs options every subcommand accepts (mirrors `rig push`). */\nconst COMMON_OPTIONS = {\n yes: { type: 'boolean', default: false },\n json: { type: 'boolean', default: false },\n relay: { type: 'string', multiple: true },\n remote: { type: 'string' },\n 'repo-id': { type: 'string' },\n owner: { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n} as const;\n\ninterface CommonFlags {\n yes: boolean;\n json: boolean;\n relay: string[];\n remote?: string;\n repoId?: string;\n owner?: string;\n help: boolean;\n}\n\nfunction pickCommon(values: Record<string, unknown>): CommonFlags {\n const flags: CommonFlags = {\n yes: values['yes'] === true,\n json: values['json'] === true,\n relay: Array.isArray(values['relay']) ? (values['relay'] as string[]) : [],\n help: values['help'] === true,\n };\n const remote = values['remote'];\n if (typeof remote === 'string') flags.remote = remote;\n const repoId = values['repo-id'];\n if (typeof repoId === 'string') flags.repoId = repoId;\n const owner = values['owner'];\n if (typeof owner === 'string') {\n assertHex64(owner, '--owner');\n flags.owner = owner;\n }\n return flags;\n}\n\n// ---------------------------------------------------------------------------\n// Shared publish pipeline\n// ---------------------------------------------------------------------------\n\ntype EventCommand = 'issue' | 'comment' | 'pr' | 'pr status';\n\ninterface RunEventOptions {\n command: EventCommand;\n flags: CommonFlags;\n deps: EventCommandDeps;\n /** Human action label WITHOUT the kind, e.g. `issue \"Fix the flux\"`. */\n actionLabel: string;\n /**\n * Build the unsigned NIP-34 event for the resolved repo address — the\n * publish payload, and the source of truth for the kind. May do real work\n * (pr runs format-patch here), so failures land in the normal error path.\n */\n buildEvent: (addr: GitRepoAddr) => Promise<UnsignedEvent>;\n}\n\n/** JSON envelope emitted by `--json` runs (agents consume this). */\ninterface EventJsonOutput {\n command: EventCommand;\n repoAddr: GitRepoAddr;\n /** Active identity: source tier + derived pubkey (never the phrase). */\n identity: IdentityReport;\n /** NIP-34 kind this command publishes. */\n kind: number;\n /** True when the paid publish ran. */\n executed: boolean;\n /** Per-event fee (base units, decimal string). */\n feeEstimate: string | null;\n result?: GitEventResponse;\n hint?: string;\n}\n\n/**\n * The estimate → confirm → execute flow shared by all four subcommands.\n * Money moves only after the confirm gate and the single-relay guard.\n */\nasync function runEvent(opts: RunEventOptions): Promise<number> {\n const { command, flags, deps, actionLabel } = opts;\n const { io, env } = deps;\n\n let standaloneCtx: StandaloneContext | undefined;\n try {\n // ── Repo addressing (best-effort git config; flags can stand alone) ─────\n let repoRoot: string | undefined;\n let toonConfig: ToonRepoConfig = { relays: [] };\n try {\n repoRoot = await resolveRepoRoot(deps.cwd);\n toonConfig = await readToonConfig(repoRoot);\n } catch {\n // Not inside a git repository — --repo-id/--owner must carry the address.\n }\n const repoId = flags.repoId ?? toonConfig.repoId;\n if (!repoId) throw new UnconfiguredRepoAddressError('repository id');\n\n // ── Relay resolution (#249: --relay > --remote > origin > toon.relay) ───\n const resolved = await resolveRelays({\n relayFlags: flags.relay,\n remoteName: flags.remote,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n if (resolved.nudge !== undefined) io.err(resolved.nudge);\n const relaysUsed = resolved.relays;\n // Same pre-pay guard as push: StandalonePublisher publishes to exactly\n // one relay, and multiple can arrive without explicit intent (repeated\n // --relay flags, an old multi-valued git config `toon.relay`). Refuse\n // before anything is paid.\n if (relaysUsed.length > 1) {\n io.err(singleRelayRefusal(resolved, 'Nothing was published or paid.'));\n return 1;\n }\n\n // ── Standalone context (identity chain + nonce guard) + per-event fee ───\n standaloneCtx = await (deps.loadStandalone ?? defaultLoadStandalone)({\n env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n // Relay-origin for #264 network bootstrap (announce discovery).\n ...(relaysUsed[0] !== undefined ? { relayUrl: relaysUsed[0] } : {}),\n });\n const identity = identityReport(standaloneCtx);\n const fee = (await standaloneCtx.publisher.getFeeRates()).eventFee.toString();\n\n const owner = flags.owner ?? toonConfig.owner ?? identity.pubkey;\n const addr: GitRepoAddr = { ownerPubkey: owner, repoId };\n\n // Built once: the publish payload AND the kind for rendering.\n const event = await opts.buildEvent(addr);\n const action = `kind:${event.kind} ${actionLabel}`;\n\n // ── Confirm gate (identical semantics to `rig push`) ────────────────────\n if (!flags.json) {\n for (const line of renderEventPlan({ action, addr, identity, fee })) {\n io.out(line);\n }\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: addr,\n identity,\n kind: event.kind,\n executed: false,\n feeEstimate: fee,\n hint: 'estimate only — re-run with --yes to publish (permanent, non-refundable)',\n } satisfies EventJsonOutput);\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n 'refusing to spend channel funds without confirmation in a non-interactive ' +\n 'session — re-run with --yes (or use --json for an estimate)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Proceed with paid publish (${feeLabel(fee)})? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was published.');\n return 1;\n }\n }\n\n // ── Execute ─────────────────────────────────────────────────────────────\n const receipt = await standaloneCtx.publisher.publishEvent(event, relaysUsed);\n const result = serializeEventReceipt(event.kind, receipt);\n\n // ── Receipts ────────────────────────────────────────────────────────────\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: addr,\n identity,\n kind: result.kind,\n executed: true,\n feeEstimate: fee,\n result,\n } satisfies EventJsonOutput);\n } else {\n for (const line of renderEventReceipt(action, result)) io.out(line);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, command, err);\n } finally {\n if (standaloneCtx) {\n try {\n await standaloneCtx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// rig issue create\n// ---------------------------------------------------------------------------\n\n/** Run `rig issue …`; returns the process exit code. */\nexport async function runIssue(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n if (sub === '--help' || sub === '-h' || sub === 'help') {\n io.out(ISSUE_USAGE);\n return 0;\n }\n if (sub !== 'create') {\n io.err(\n sub === undefined\n ? 'missing subcommand: rig issue create'\n : `unknown rig issue subcommand: ${sub}`\n );\n io.err(ISSUE_USAGE);\n return 2;\n }\n\n let flags: CommonFlags;\n let title: string;\n let bodyFlag: string | undefined;\n let bodyFile: string | undefined;\n let labels: string[];\n try {\n const { values } = parseArgs({\n args: rest,\n options: {\n ...COMMON_OPTIONS,\n title: { type: 'string' },\n body: { type: 'string' },\n 'body-file': { type: 'string' },\n label: { type: 'string', multiple: true },\n },\n allowPositionals: false,\n });\n flags = pickCommon(values);\n if (!flags.help && (values.title === undefined || values.title === '')) {\n throw new Error('--title is required');\n }\n if (values.body !== undefined && values['body-file'] !== undefined) {\n throw new Error('--body and --body-file are mutually exclusive');\n }\n title = values.title ?? '';\n bodyFlag = values.body;\n bodyFile = values['body-file'];\n labels = values.label ?? [];\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(ISSUE_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(ISSUE_USAGE);\n return 0;\n }\n\n // Body source: --body → --body-file → piped stdin.\n let body: string;\n if (bodyFlag !== undefined) {\n body = bodyFlag;\n } else if (bodyFile !== undefined) {\n try {\n body = await readFile(bodyFile, 'utf-8');\n } catch (err) {\n io.err(\n `cannot read --body-file ${bodyFile}: ${err instanceof Error ? err.message : String(err)}`\n );\n return 2;\n }\n } else if (!io.isInteractive) {\n body = await (deps.readStdin ?? defaultReadStdin)();\n } else {\n io.err('an issue body is required: pass --body/--body-file or pipe stdin');\n io.err(ISSUE_USAGE);\n return 2;\n }\n if (body.trim() === '') {\n io.err('the issue body is empty — nothing to publish');\n return 2;\n }\n\n return runEvent({\n command: 'issue',\n flags,\n deps,\n actionLabel: `issue ${JSON.stringify(title)}`,\n buildEvent: async (addr) =>\n buildIssue(addr.ownerPubkey, addr.repoId, title, body, labels),\n });\n}\n\n// ---------------------------------------------------------------------------\n// rig comment\n// ---------------------------------------------------------------------------\n\n/** Run `rig comment …`; returns the process exit code. */\nexport async function runComment(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let flags: CommonFlags;\n let rootEventId: string;\n let body: string;\n let parentAuthor: string | undefined;\n let marker: 'root' | 'reply';\n try {\n const { values, positionals } = parseArgs({\n args,\n options: {\n ...COMMON_OPTIONS,\n body: { type: 'string' },\n 'parent-author': { type: 'string' },\n marker: { type: 'string' },\n },\n allowPositionals: true,\n });\n flags = pickCommon(values);\n if (flags.help) {\n io.out(COMMENT_USAGE);\n return 0;\n }\n if (positionals.length !== 1) {\n throw new Error(\n positionals.length === 0\n ? '<root-event-id> is required'\n : `expected exactly one <root-event-id>, got ${positionals.length} positionals`\n );\n }\n rootEventId = positionals[0] as string;\n assertHex64(rootEventId, '<root-event-id>');\n if (values.body === undefined || values.body === '') {\n throw new Error('--body is required');\n }\n body = values.body;\n parentAuthor = values['parent-author'];\n if (parentAuthor !== undefined) assertHex64(parentAuthor, '--parent-author');\n const rawMarker = values.marker ?? 'root';\n if (rawMarker !== 'root' && rawMarker !== 'reply') {\n throw new Error(`--marker must be root or reply (got ${JSON.stringify(rawMarker)})`);\n }\n marker = rawMarker;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(COMMENT_USAGE);\n return 2;\n }\n\n return runEvent({\n command: 'comment',\n flags,\n deps,\n actionLabel: `comment on ${rootEventId.slice(0, 8)}…`,\n buildEvent: async (addr) =>\n buildComment(\n addr.ownerPubkey,\n addr.repoId,\n rootEventId,\n parentAuthor ?? addr.ownerPubkey,\n body,\n marker\n ),\n });\n}\n\n// ---------------------------------------------------------------------------\n// rig pr create\n// ---------------------------------------------------------------------------\n\n/** `From <sha> <date>` separator lines of `git format-patch --stdout` output. */\nconst PATCH_FROM_RE = /^From ([0-9a-f]{40}) /gm;\n\n/** Commit SHAs of a format-patch series, in patch (oldest-first) order. */\nexport function extractPatchShas(patchText: string): string[] {\n return [...patchText.matchAll(PATCH_FROM_RE)].map((m) => m[1] as string);\n}\n\n/** Run `rig pr …` (nested dispatch: create | status); returns the exit code. */\nexport async function runPr(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n switch (sub) {\n case 'create':\n return runPrCreate(rest, deps);\n case 'status':\n return runPrStatus(rest, deps);\n case '--help':\n case '-h':\n case 'help':\n io.out(PR_USAGE);\n return 0;\n default:\n io.err(\n sub === undefined\n ? 'missing subcommand: rig pr <create|status>'\n : `unknown rig pr subcommand: ${sub}`\n );\n io.err(PR_USAGE);\n return 2;\n }\n}\n\n/** `rig pr create` — kind:1617 patch publish. */\nasync function runPrCreate(\n rest: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let flags: CommonFlags;\n let title: string;\n let range: string | undefined;\n let patchFile: string | undefined;\n let branch: string | undefined;\n try {\n const { values } = parseArgs({\n args: rest,\n options: {\n ...COMMON_OPTIONS,\n title: { type: 'string' },\n range: { type: 'string' },\n 'patch-file': { type: 'string' },\n branch: { type: 'string' },\n },\n allowPositionals: false,\n });\n flags = pickCommon(values);\n if (flags.help) {\n io.out(PR_CREATE_USAGE);\n return 0;\n }\n if (values.title === undefined || values.title === '') {\n throw new Error('--title is required');\n }\n if ((values.range === undefined) === (values['patch-file'] === undefined)) {\n throw new Error('exactly one of --range or --patch-file is required');\n }\n title = values.title;\n range = values.range;\n patchFile = values['patch-file'];\n branch = values.branch;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(PR_CREATE_USAGE);\n return 2;\n }\n\n return runEvent({\n command: 'pr',\n flags,\n deps,\n actionLabel: `patch ${JSON.stringify(title)}`,\n buildEvent: async (addr) => {\n let patchText: string;\n let commits: { sha: string; parentSha: string }[];\n if (range !== undefined) {\n // REAL format-patch output from the local repository (v1 publishes\n // the whole series as ONE event; see PR_USAGE).\n const reader = new GitRepoReader(await resolveRepoRoot(deps.cwd));\n patchText = await reader.formatPatch(range);\n if (patchText === '') {\n throw new Error(\n `range ${JSON.stringify(range)} selects no commits — nothing to publish`\n );\n }\n // commit/parent-commit tags for exactly the commits the series\n // carries (parsed from the patch itself, so the tags can never drift\n // from the content). Root commits have no parent and contribute no\n // tag pair.\n const shas = extractPatchShas(patchText);\n const parents = await reader.commitParents(shas);\n commits = shas.flatMap((sha) => {\n const parentSha = parents.get(sha)?.[0];\n return parentSha ? [{ sha, parentSha }] : [];\n });\n } else {\n patchText = await readFile(patchFile as string, 'utf-8');\n if (patchText.trim() === '') {\n throw new Error(`--patch-file ${patchFile} is empty — nothing to publish`);\n }\n commits = [];\n }\n return buildPatch(\n addr.ownerPubkey,\n addr.repoId,\n title,\n commits,\n branch,\n patchText\n );\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// rig pr status (top-level `rig status` before #250 — now git's)\n// ---------------------------------------------------------------------------\n\n/** NIP-34 status kinds by wire value (mirrors the daemon's mapping). */\nconst STATUS_KIND_BY_VALUE: Record<GitStatusValue, StatusKind> = {\n open: STATUS_OPEN_KIND,\n applied: STATUS_APPLIED_KIND,\n closed: STATUS_CLOSED_KIND,\n draft: STATUS_DRAFT_KIND,\n};\n\nfunction isStatusValue(value: string): value is GitStatusValue {\n return Object.hasOwn(STATUS_KIND_BY_VALUE, value);\n}\n\n/** `rig pr status` — kind:1630-1633 status publish. */\nasync function runPrStatus(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let flags: CommonFlags;\n let targetEventId: string;\n let status: GitStatusValue;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: COMMON_OPTIONS,\n allowPositionals: true,\n });\n flags = pickCommon(values);\n if (flags.help) {\n io.out(PR_STATUS_USAGE);\n return 0;\n }\n if (positionals.length !== 2) {\n throw new Error(\n 'expected exactly two arguments: <target-event-id> <open|applied|closed|draft>'\n );\n }\n targetEventId = positionals[0] as string;\n assertHex64(targetEventId, '<target-event-id>');\n const rawStatus = positionals[1] as string;\n if (!isStatusValue(rawStatus)) {\n throw new Error(\n `status must be one of open | applied | closed | draft (got ${JSON.stringify(rawStatus)})`\n );\n }\n status = rawStatus;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(PR_STATUS_USAGE);\n return 2;\n }\n\n return runEvent({\n command: 'pr status',\n flags,\n deps,\n actionLabel: `status ${status} on ${targetEventId.slice(0, 8)}…`,\n buildEvent: async (addr) => {\n const event = buildStatus(targetEventId, STATUS_KIND_BY_VALUE[status]);\n // NIP-34 status events also carry the repo `a` tag so readers can scope\n // a status stream to the repository without resolving the target first\n // (mirrors the daemon's gitStatus).\n event.tags.push([\n 'a',\n `${REPOSITORY_ANNOUNCEMENT_KIND}:${addr.ownerPubkey}:${addr.repoId}`,\n ]);\n return event;\n },\n });\n}\n","/**\n * `rig fund` — drip devnet test funds to the active identity's wallet (#263).\n *\n * A FREE command: no relay, no client start, no nonce guard, no payment\n * channel — just the identity chain (RIG_MNEMONIC precedence, ./identity.ts)\n * to derive the chain address, and one HTTP POST to the devnet faucet\n * (`@toon-protocol/client`'s `fundWallet`: `POST {faucet}/api/request` for\n * EVM, `/api/solana/request`, `/api/mina/request` — body `{ address }`; the\n * faucet drips FIXED amounts, so there is no --amount).\n *\n * Faucet resolution mirrors the toon-clientd conventions\n * (client-mcp/src/daemon/config.ts — no import, keep in sync):\n * `TOON_CLIENT_FAUCET_URL` env → `faucetUrl` in the shared client config →\n * the deployed devnet faucet when the configured network IS devnet. On any\n * other network there is no faucet: the command prints the derived wallet\n * address(es) to fund externally instead of failing silently.\n *\n * The drip is awaited synchronously (a CLI has no background): the Mina\n * faucet legitimately takes ~75s, so the per-chain timeout is generous\n * (daemon convention: 90s, mina 130s; `TOON_CLIENT_FAUCET_TIMEOUT_MS` /\n * config `faucetTimeoutMs` override).\n */\n\nimport { readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { emitCliError } from './errors.js';\nimport { resolveIdentity } from './identity.js';\nimport type { CliIo, IdentityReport } from './push.js';\nimport { renderIdentityLine } from './render.js';\n\n/**\n * The deployed devnet faucet — the same edge the e2e suite drips from\n * (`client-mcp/src/e2e/devnet.ts`). Used only when the configured network is\n * `devnet` and no explicit faucet URL is set.\n */\nexport const DEVNET_FAUCET_URL = 'https://faucet.devnet.toonprotocol.dev';\n\n/** Supported faucet chains (client `FaucetChain`). */\nconst CHAINS = ['evm', 'solana', 'mina'] as const;\ntype FundChain = (typeof CHAINS)[number];\n\nexport const FUND_USAGE = `Usage: rig fund [options]\n\nDrip devnet test funds to the active identity's wallet — free (the faucet\npays). The identity comes from RIG_MNEMONIC (env or a project .env) or the\n~/.toon-client keystore/config; the faucet from TOON_CLIENT_FAUCET_URL, the\nfaucetUrl config field, or the deployed devnet faucet when the configured\nnetwork is devnet. The faucet drips a FIXED amount per chain (there is no\n--amount). On a network without a faucet, prints the wallet address(es) to\nfund externally instead.\n\nOptions:\n --chain <chain> evm | solana | mina (default: TOON_CLIENT_CHAIN, the\n \\`chain\\` config field, else evm)\n --address <address> fund this address instead of the identity's own\n --json machine-readable envelope\n -h, --help show this help`;\n\n/** What `rig fund` needs from the command environment. */\nexport interface FundDeps {\n io: CliIo;\n env: NodeJS.ProcessEnv;\n /** Working directory (starts the project-local `.env` walk). */\n cwd: string;\n /** fetch used for the faucet call (tests inject; default global fetch). */\n fetchImpl?: typeof fetch;\n}\n\n/** The slice of the shared client config file `rig fund` consumes. */\ninterface FundConfigFile {\n network?: string;\n faucetUrl?: string;\n faucetTimeoutMs?: number;\n chain?: string;\n}\n\n/** `--json` envelope. */\ninterface FundJson {\n command: 'fund';\n identity: IdentityReport;\n /** True when a faucet drip was performed (and succeeded). */\n funded: boolean;\n network: string | null;\n chain: FundChain;\n address?: string;\n faucetUrl?: string;\n /** Raw faucet response body (shape is faucet-defined). */\n response?: unknown;\n /** Non-devnet path: the derived wallet addresses to fund externally. */\n addresses?: { evm: string | null; solana: string | null; mina: string | null };\n guidance?: string;\n}\n\nfunction readFundConfig(env: NodeJS.ProcessEnv): {\n file: FundConfigFile;\n configPath: string;\n} {\n const dir = env['TOON_CLIENT_HOME'] ?? join(homedir(), '.toon-client');\n const configPath = join(dir, 'config.json');\n try {\n return {\n file: JSON.parse(readFileSync(configPath, 'utf8')) as FundConfigFile,\n configPath,\n };\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { file: {}, configPath };\n }\n throw new Error(\n `failed to read client config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n}\n\n/** Run `rig fund`; returns the process exit code. */\nexport async function runFund(args: string[], deps: FundDeps): Promise<number> {\n const { io, env } = deps;\n\n let chainFlag: string | undefined;\n let addressFlag: string | undefined;\n let json = false;\n try {\n const { values } = parseArgs({\n args,\n options: {\n chain: { type: 'string' },\n address: { type: 'string' },\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (values.help) {\n io.out(FUND_USAGE);\n return 0;\n }\n chainFlag = values.chain;\n addressFlag = values.address;\n json = values.json ?? false;\n if (chainFlag !== undefined && !CHAINS.includes(chainFlag as FundChain)) {\n throw new Error(\n `--chain must be one of ${CHAINS.join(' | ')}, got ${JSON.stringify(chainFlag)}`\n );\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(FUND_USAGE);\n return 2;\n }\n\n try {\n const { file } = readFundConfig(env);\n const chain = (chainFlag ??\n env['TOON_CLIENT_CHAIN'] ??\n file.chain ??\n 'evm') as FundChain;\n if (!CHAINS.includes(chain)) {\n throw new Error(\n `configured settlement chain ${JSON.stringify(chain)} has no faucet — pass --chain ${CHAINS.join(' | ')}`\n );\n }\n const network = env['TOON_CLIENT_NETWORK'] ?? file.network;\n const faucetUrl =\n env['TOON_CLIENT_FAUCET_URL'] ??\n file.faucetUrl ??\n (network === 'devnet' ? DEVNET_FAUCET_URL : undefined);\n\n // ── Identity chain → wallet addresses (never the phrase) ────────────────\n const resolved = await resolveIdentity({\n env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n });\n const identity: IdentityReport = {\n pubkey: resolved.pubkey,\n source: resolved.source,\n sourceLabel: resolved.sourceLabel,\n };\n // Dynamic import: `@toon-protocol/client` is heavy; runs that fail\n // earlier (usage errors) never pay its startup cost.\n const client = await import('@toon-protocol/client');\n const derived = await client.deriveFullIdentity(\n resolved.mnemonic,\n resolved.accountIndex\n );\n const addresses = {\n evm: derived.evm.address || null,\n solana: derived.solana.publicKey || null,\n mina: derived.mina.publicKey || null,\n };\n\n // ── No faucet on this network: clear external-funding guidance ──────────\n if (!faucetUrl) {\n const guidance =\n `no faucet on network ${JSON.stringify(network ?? 'custom')} — fund the wallet ` +\n 'externally (send the settlement token + native gas to the address for ' +\n 'the chain your channels settle on), or set TOON_CLIENT_FAUCET_URL / ' +\n 'the faucetUrl config field if this network has one.';\n if (json) {\n io.emitJson({\n command: 'fund',\n identity,\n funded: false,\n network: network ?? null,\n chain,\n addresses,\n guidance,\n } satisfies FundJson);\n return 0;\n }\n io.out(renderIdentityLine(identity));\n io.out(guidance);\n io.out('Wallet addresses:');\n io.out(` evm ${addresses.evm ?? '(no key derived)'}`);\n io.out(` solana ${addresses.solana ?? '(no key derived)'}`);\n io.out(` mina ${addresses.mina ?? '(no key derived — optional mina-signer dependency missing)'}`);\n return 0;\n }\n\n // ── Devnet faucet drip ───────────────────────────────────────────────────\n const address = addressFlag ?? addresses[chain];\n if (!address) {\n throw new Error(\n `no ${chain} address could be derived for this identity — pass an ` +\n 'explicit --address (for mina, install the optional mina-signer dependency)'\n );\n }\n // Generous, chain-aware timeout (daemon convention): the drip is awaited\n // here, and a Mina drip routinely takes >75s server-side.\n const timeoutEnv = env['TOON_CLIENT_FAUCET_TIMEOUT_MS'];\n const timeout =\n timeoutEnv && Number.isFinite(Number(timeoutEnv))\n ? Number(timeoutEnv)\n : (file.faucetTimeoutMs ?? (chain === 'mina' ? 130_000 : 90_000));\n\n if (!json) {\n io.out(\n `Requesting ${chain} drip from ${faucetUrl} for ${address} …` +\n (chain === 'mina' ? ' (mina settles slowly; this can take ~2 minutes)' : '')\n );\n }\n const { response } = await client.fundWallet(faucetUrl, address, chain, {\n timeout,\n ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n if (json) {\n io.emitJson({\n command: 'fund',\n identity,\n funded: true,\n network: network ?? null,\n chain,\n address,\n faucetUrl,\n response,\n } satisfies FundJson);\n return 0;\n }\n io.out(`Faucet drip succeeded: ${chain} → ${address}`);\n io.out(renderIdentityLine(identity));\n io.out('Re-check with `rig balance` (a drip can take a few blocks to land).');\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'fund', err);\n }\n}\n","/**\n * Git passthrough (#250): any subcommand `rig` does not own is executed as\n * `git <argv...>` verbatim — `rig status`, `rig add -p`, `rig commit`,\n * `rig log --oneline`, `rig rebase -i`, everything.\n *\n * The child git runs with `stdio: 'inherit'` so interactive commands, pagers,\n * colors, and prompts behave exactly as if the user had typed `git` (no\n * capture, no buffering). The child's exit code is propagated verbatim; a\n * child killed by a signal maps to the shell convention 128+N. While the\n * child runs, rig ignores-and-forwards SIGINT/SIGTERM/SIGHUP so git (not\n * rig) decides the outcome of a Ctrl-C — e.g. `rebase -i` gets to clean up —\n * and rig then reports git's exit.\n */\n\nimport { spawn } from 'node:child_process';\nimport { constants as osConstants } from 'node:os';\n\nexport interface GitPassthroughOptions {\n /** Working directory for the git child (default: the rig process cwd). */\n cwd?: string;\n /** Environment for the git child (default: the rig process env). */\n env?: NodeJS.ProcessEnv;\n /** Write one line to stderr (missing-git error); default: process.stderr. */\n err?: (line: string) => void;\n}\n\n/** The passthrough seam `dispatch` uses; tests inject a fake. */\nexport type GitRunner = (\n argv: string[],\n options?: GitPassthroughOptions\n) => Promise<number>;\n\n/** Exit code when the system git binary cannot be found (shell convention). */\nexport const GIT_NOT_FOUND_EXIT = 127;\n\n/** Signals relayed to the git child while it runs. */\nconst RELAYED_SIGNALS: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP'];\n\n/** Shell-convention exit code for a child terminated by `signal`. */\nfunction signalExitCode(signal: NodeJS.Signals): number {\n const num = osConstants.signals[signal];\n return num === undefined ? 1 : 128 + num;\n}\n\n/**\n * Run system `git` with the exact argv tail, inheriting rig's stdio.\n * Resolves to the exit code rig should exit with; never rejects.\n */\nexport const runGitPassthrough: GitRunner = (argv, options = {}) => {\n const err =\n options.err ?? ((line: string) => process.stderr.write(`${line}\\n`));\n\n return new Promise<number>((resolve) => {\n const child = spawn('git', argv, {\n stdio: 'inherit',\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\n env: options.env ?? process.env,\n });\n\n // Terminal-generated signals (Ctrl-C) already reach the child through the\n // shared foreground process group; the handlers stop rig's default\n // die-on-signal so the child controls the outcome, and forward the signal\n // for the cases where only rig was targeted (`kill <rig-pid>`).\n const relay = new Map<NodeJS.Signals, () => void>();\n for (const signal of RELAYED_SIGNALS) {\n const handler = (): void => {\n child.kill(signal);\n };\n relay.set(signal, handler);\n process.on(signal, handler);\n }\n const restoreSignals = (): void => {\n for (const [signal, handler] of relay) process.removeListener(signal, handler);\n };\n\n child.on('error', (spawnErr: NodeJS.ErrnoException) => {\n restoreSignals();\n if (spawnErr.code === 'ENOENT') {\n err(\n `rig: git not found — \\`rig ${argv[0] ?? ''}\\` is not a rig command, so it is ` +\n 'passed through to the system `git`, which is not on your PATH. ' +\n 'Install git (https://git-scm.com) or fix your PATH.'\n );\n resolve(GIT_NOT_FOUND_EXIT);\n return;\n }\n err(`rig: failed to run git: ${spawnErr.message}`);\n resolve(1);\n });\n\n child.on('close', (code, signal) => {\n restoreSignals();\n resolve(signal !== null ? signalExitCode(signal) : (code ?? 1));\n });\n });\n};\n","/**\n * `rig init` — one-shot, idempotent repo setup (#248).\n *\n * Replaces the old \"config written as a side effect of the first push\":\n *\n * 1. verifies the working directory is inside a git repository (hints at\n * `git init` when not — never runs it);\n * 2. resolves the signing identity via the RIG_MNEMONIC precedence chain\n * (./identity.ts) and reports the SOURCE + derived pubkey (never the\n * phrase); a chain miss errors with all three remediation options;\n * 3. writes `toon.repoid` (default: repo directory basename; existing\n * value kept on re-runs; `--repo-id` overrides) and `toon.owner` (the\n * derived pubkey) to the repository's LOCAL git config — the mnemonic\n * itself is never written to git config or any repo file;\n * 4. reports the relay setup (#249): when the deprecated v0.1\n * `git config toon.relay` is set and no `origin` remote exists, it\n * MIGRATES the value to a real `origin` git remote (the old key stays\n * readable as a fallback and is removed in v0.3); when nothing is\n * configured it suggests `rig remote add origin <relay-url>` as the\n * follow-up step.\n *\n * Re-running updates and reports instead of erroring. `--json` emits a\n * machine-readable report. Free — nothing is published or paid.\n */\n\nimport { basename } from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { emitCliError, NotAGitRepositoryError } from './errors.js';\nimport {\n addGitRemote,\n listGitRemotes,\n readToonConfig,\n resolveRepoRoot,\n writeToonConfig,\n type GitRemoteInfo,\n} from './git-config.js';\nimport { resolveIdentity, type ResolvedIdentity } from './identity.js';\nimport type { CliIo } from './push.js';\nimport { isRelayUrl } from './remote.js';\nimport { renderIdentityLine } from './render.js';\n\nexport const INIT_USAGE = `Usage: rig init [options]\n\nSet up the current git repository for rig (one-shot, idempotent, free):\nresolves your identity (RIG_MNEMONIC env → project .env → ~/.toon-client\nkeystore/config), then writes toon.repoid and toon.owner to the repo's\nLOCAL git config. Re-running updates and reports; it never errors on an\nalready-initialized repo. The seed phrase is never written anywhere.\n\nThe follow-up step is adding a relay: \\`rig remote add origin <relay-url>\\`\n(a real git remote — \\`git remote -v\\` shows it). A deprecated v0.1\n\\`git config toon.relay\\` is migrated to the origin remote automatically\nwhen no origin exists (the old key stays readable and is removed in v0.3).\n\nOptions:\n --repo-id <id> repository id / NIP-34 d-tag (default: the existing\n toon.repoid, then the repo directory basename)\n --json machine-readable report\n -h, --help show this help`;\n\n/** Deps subset `rig init` needs (no publisher — init is free). */\nexport interface InitDeps {\n io: CliIo;\n env: NodeJS.ProcessEnv;\n cwd: string;\n /** Identity resolver seam (tests); defaults to the real chain. */\n resolveIdentityImpl?: typeof resolveIdentity;\n}\n\ninterface InitFlags {\n repoId?: string;\n json: boolean;\n help: boolean;\n}\n\nfunction parseInitArgs(args: string[]): InitFlags {\n const { values, positionals } = parseArgs({\n args,\n options: {\n 'repo-id': { type: 'string' },\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: false,\n });\n if (positionals.length > 0) {\n throw new Error(`rig init takes no positional arguments`);\n }\n const flags: InitFlags = {\n json: values.json ?? false,\n help: values.help ?? false,\n };\n const repoId = values['repo-id'];\n if (repoId !== undefined) {\n if (repoId.trim() === '') throw new Error('--repo-id must not be empty');\n flags.repoId = repoId;\n }\n return flags;\n}\n\n/** JSON envelope emitted by `rig init --json`. */\ninterface InitJsonOutput {\n command: 'init';\n repoRoot: string;\n repoId: string;\n /** `toon.owner` — the derived pubkey of the active identity. */\n owner: string;\n identity: {\n source: ResolvedIdentity['source'];\n sourceLabel: string;\n pubkey: string;\n };\n /** Deprecated `git config toon.relay` values (kept readable until v0.3). */\n relays: string[];\n /** True when any relay source is configured (origin remote or toon.relay). */\n relayConfigured: boolean;\n /** Configured git remotes (post-migration). */\n remotes: GitRemoteInfo[];\n /** The single relay URL of the `origin` remote, when it is one. */\n origin: string | null;\n /** True when this run migrated toon.relay to a new `origin` remote. */\n migratedToonRelay: boolean;\n /** What this run changed in git config (false = already up to date). */\n changed: { repoId: boolean; owner: boolean };\n}\n\n/** Run `rig init`; returns the process exit code. */\nexport async function runInit(args: string[], deps: InitDeps): Promise<number> {\n const { io, env } = deps;\n\n let flags: InitFlags;\n try {\n flags = parseInitArgs(args);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(INIT_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(INIT_USAGE);\n return 0;\n }\n\n try {\n // ── (a) Must be a git repository — hint, never auto-run git init ────────\n let repoRoot: string;\n try {\n repoRoot = await resolveRepoRoot(deps.cwd);\n } catch {\n throw new NotAGitRepositoryError(deps.cwd);\n }\n\n // ── (b) Identity chain: source + derived pubkey (never the phrase) ──────\n const identity = await (deps.resolveIdentityImpl ?? resolveIdentity)({\n env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n });\n\n // ── (c) Write toon.repoid / toon.owner to LOCAL git config ──────────────\n const existing = await readToonConfig(repoRoot);\n const repoId = flags.repoId ?? existing.repoId ?? basename(repoRoot);\n const changed = {\n repoId: existing.repoId !== repoId,\n owner: existing.owner !== identity.pubkey,\n };\n await writeToonConfig(repoRoot, { repoId, owner: identity.pubkey });\n\n // ── (d) Relay setup (#249): migrate toon.relay → origin remote ──────────\n // toon.relay is the deprecated v0.1 key. When it is set, single-valued,\n // relay-shaped, and no `origin` remote exists, adopt it as a real git\n // remote. The old key stays readable (paid commands still fall back to\n // it, with a nudge) and is removed in v0.3.\n let remotes = await listGitRemotes(repoRoot);\n let migratedToonRelay = false;\n const legacyRelay = existing.relays[0];\n if (\n !remotes.some((r) => r.name === 'origin') &&\n existing.relays.length === 1 &&\n legacyRelay !== undefined &&\n isRelayUrl(legacyRelay)\n ) {\n await addGitRemote(repoRoot, 'origin', legacyRelay);\n migratedToonRelay = true;\n remotes = await listGitRemotes(repoRoot);\n }\n const origin = remotes.find((r) => r.name === 'origin');\n const originRelay =\n origin !== undefined &&\n origin.urls.length === 1 &&\n isRelayUrl(origin.urls[0] as string)\n ? (origin.urls[0] as string)\n : undefined;\n\n // ── (e) Report ───────────────────────────────────────────────────────────\n if (flags.json) {\n const output: InitJsonOutput = {\n command: 'init',\n repoRoot,\n repoId,\n owner: identity.pubkey,\n identity: {\n source: identity.source,\n sourceLabel: identity.sourceLabel,\n pubkey: identity.pubkey,\n },\n relays: existing.relays,\n relayConfigured: originRelay !== undefined || existing.relays.length > 0,\n remotes,\n origin: originRelay ?? null,\n migratedToonRelay,\n changed,\n };\n io.emitJson(output);\n return 0;\n }\n\n io.out(`Initialized rig for ${repoRoot}`);\n io.out(renderIdentityLine(identity));\n io.out(\n ` toon.repoid = ${repoId}` +\n (changed.repoId ? '' : ' (unchanged)') +\n (existing.repoId && changed.repoId ? ` (was ${existing.repoId})` : '')\n );\n io.out(\n ` toon.owner = ${identity.pubkey}` +\n (changed.owner ? '' : ' (unchanged)') +\n (existing.owner && changed.owner ? ` (was ${existing.owner})` : '')\n );\n if (originRelay !== undefined) {\n io.out(\n ` origin = ${originRelay}` +\n (migratedToonRelay ? ' (migrated from git config toon.relay)' : '')\n );\n if (migratedToonRelay) {\n io.out(\n 'note: toon.relay is deprecated — it stays readable as a fallback ' +\n 'and is removed in v0.3; drop it now with ' +\n '`git config --unset-all toon.relay`.'\n );\n }\n io.out('Ready: `rig push` publishes this repo via remote \"origin\".');\n } else if (existing.relays.length > 0) {\n // toon.relay is set but could not be migrated (multi-valued, junk URL,\n // or a non-relay `origin` remote already occupies the name).\n io.out(` toon.relay = ${existing.relays.join(', ')} (deprecated)`);\n io.out(\n origin !== undefined\n ? `The \"origin\" remote (${origin.urls.join(', ')}) is not a single ` +\n 'relay URL, so toon.relay stays the fallback — add the relay ' +\n 'under another name (`rig remote add toon <relay-url>`) and ' +\n 'push with `rig push toon`.'\n : existing.relays.length > 1\n ? `toon.relay has ${existing.relays.length} values and rig ` +\n 'publishes to one relay — migrate the right one: ' +\n '`rig remote add origin <relay-url>`.'\n : 'This value is not a relay URL (ws://, wss://, http://, or ' +\n 'https://) — set a real one: `rig remote add origin <relay-url>`.'\n );\n } else if (origin !== undefined) {\n // The origin name is occupied by a non-relay remote (e.g. a GitHub\n // clone) and no legacy toon.relay exists.\n io.out(\n `No relay configured yet — \"origin\" (${origin.urls.join(', ')}) is ` +\n 'not a relay URL, so add the relay under another name: ' +\n '`rig remote add toon <relay-url>`, then `rig push toon`.'\n );\n } else {\n io.out(\n 'No relay configured yet — add one as the follow-up step: ' +\n '`rig remote add origin <relay-url>` (a real git remote; ' +\n '`git remote -v` shows it). One-off pushes can pass --relay <url>.'\n );\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, 'init', err);\n }\n}\n","/**\n * The rig CLI output layer (#265): the strict `--json` stdout guarantee.\n *\n * CONTRACT — when `--json` is set on a rig-owned command, stdout carries\n * EXACTLY ONE parseable JSON document and nothing else. Agents consume this\n * stream (`rig … --json | jq`), so any stray banner, progress line, warning,\n * deprecation nudge, or third-party `console.log` on stdout breaks pipelines\n * (the #260 addendum: `[Bootstrap] …` logs from the embedded client's core\n * polluted `rig push --json`). Everything human-facing goes to stderr.\n *\n * Three layers enforce the contract (composed in ./rig.ts; the enforcement\n * matrix in ./strict-json.test.ts mirrors that composition):\n *\n * 1. {@link makeCliIo} — the ONLY output surface commands use. In JSON mode\n * `out()` (human lines) reroutes to stderr and `emitJson()` is the sole\n * writer that reaches the real stdout.\n * 2. {@link redirectStdoutToStderr} — a process-level guard for code the io\n * seam cannot reach: dependencies that `console.log` directly (the\n * embedded `@toon-protocol/client`'s core bootstrap does). Installed\n * before any command code runs, it reroutes EVERY `process.stdout.write`\n * to stderr; only the writer it returns (wired into `emitJson`) still\n * reaches the real stdout.\n * 3. {@link RigIo.ensureSingleJsonDoc} — the backstop for paths that bail\n * out before emitting an envelope (usage errors, pre-payment refusals):\n * after dispatch it emits one error envelope built from the collected\n * stderr lines, so stdout is never empty in JSON mode.\n *\n * GIT PASSTHROUGH IS EXEMPT: `--json` is a per-subcommand flag on rig-owned\n * verbs, not a global rig flag. Any verb rig does not own goes to system git\n * with the EXACT argv tail and inherited stdio — `rig status --json` runs\n * `git status --json` (git rejects it), and flags BEFORE the subcommand\n * (`rig --json status`) are not rig's either: the whole argv passes through\n * to git verbatim. {@link isJsonInvocation} implements exactly that boundary.\n */\n\n// ---------------------------------------------------------------------------\n// The io seam\n// ---------------------------------------------------------------------------\n\n/** Terminal I/O seam — every rig-owned command writes ONLY through this. */\nexport interface CliIo {\n /**\n * One HUMAN-facing line: stdout normally, stderr when `--json` is active\n * (chatter must never pollute the machine stream).\n */\n out(line: string): void;\n /** One human-facing line to stderr (warnings, nudges, errors). */\n err(line: string): void;\n /**\n * THE machine-readable JSON document of a `--json` run — serialized here\n * (2-space indent) and written to the REAL stdout. Must be a command's\n * single stdout emission; call it at most once per invocation.\n */\n emitJson(payload: unknown): void;\n /** True when stdin+stdout are TTYs (interactive confirm possible). */\n isInteractive: boolean;\n /** Ask a y/N question; resolves true on explicit yes. */\n confirm(question: string): Promise<boolean>;\n}\n\n/** {@link CliIo} plus the JSON-mode bookkeeping the entrypoint needs. */\nexport interface RigIo extends CliIo {\n /** True when this invocation runs in `--json` mode. */\n readonly jsonMode: boolean;\n /** True once `emitJson` has written the machine document. */\n readonly emittedJson: boolean;\n /**\n * The #265 backstop: called once after dispatch (see ./rig.ts). In JSON\n * mode, when NO machine document was emitted (usage error, pre-payment\n * refusal, unexpected crash), emits one error envelope carrying the\n * human-facing lines the run wrote to stderr — so `--json` stdout always\n * parses. No-op outside JSON mode or after a real emission.\n */\n ensureSingleJsonDoc(exitCode: number): void;\n}\n\n/** Sinks + terminal facts {@link makeCliIo} builds a {@link RigIo} from. */\nexport interface CliIoOptions {\n /** Whether this invocation is a rig-owned command with `--json`. */\n jsonMode: boolean;\n /**\n * Write to the REAL stdout (in JSON mode: the pre-guard writer returned by\n * {@link redirectStdoutToStderr}). Receives full text including newlines.\n */\n writeStdout(text: string): void;\n /** Write to stderr. Receives full text including newlines. */\n writeStderr(text: string): void;\n isInteractive: boolean;\n confirm(question: string): Promise<boolean>;\n}\n\n/**\n * Build the {@link RigIo} for one invocation. Centralizes the #265 routing:\n * human lines → stderr in JSON mode, and `emitJson` as the only stdout path.\n */\nexport function makeCliIo(options: CliIoOptions): RigIo {\n const { jsonMode, writeStdout, writeStderr } = options;\n let emittedJson = false;\n /** Human lines collected in JSON mode — the backstop envelope's detail. */\n const humanLines: string[] = [];\n\n const toStderr = (line: string): void => {\n if (jsonMode) humanLines.push(line);\n writeStderr(`${line}\\n`);\n };\n\n return {\n jsonMode,\n get emittedJson() {\n return emittedJson;\n },\n out: (line) => {\n if (jsonMode) {\n toStderr(line);\n } else {\n writeStdout(`${line}\\n`);\n }\n },\n err: toStderr,\n emitJson: (payload) => {\n emittedJson = true;\n writeStdout(`${JSON.stringify(payload, null, 2)}\\n`);\n },\n isInteractive: options.isInteractive,\n confirm: options.confirm,\n ensureSingleJsonDoc(exitCode: number): void {\n if (!jsonMode || emittedJson) return;\n const detail =\n humanLines.join('\\n') ||\n (exitCode === 0\n ? 'the command produced no machine output'\n : 'the command failed before emitting machine output — see stderr');\n this.emitJson(\n exitCode === 0\n ? { error: null, exitCode, detail }\n : { error: 'error', exitCode, detail }\n );\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// JSON-mode detection (and the git-passthrough exemption)\n// ---------------------------------------------------------------------------\n\n/**\n * The verbs rig owns — everything else is `git <argv…>` verbatim. Must match\n * the ./dispatch.ts switch (dispatch.test.ts pins both directions).\n */\nexport const RIG_OWNED_VERBS: ReadonlySet<string> = new Set([\n 'init',\n 'remote',\n 'push',\n 'issue',\n 'comment',\n 'pr',\n 'channel',\n 'fund',\n 'balance',\n]);\n\n/**\n * True when this argv is a rig-owned command run with `--json` — the strict\n * stdout contract applies. Deliberately NOT true for:\n *\n * - non-owned verbs (`rig status --json` IS `git status --json`: inherited\n * stdio, git's own semantics, rig adds nothing);\n * - flags before the subcommand (`rig --json status`): rig has no global\n * flags besides help/--version, so the argv passes to git verbatim;\n * - `--json` after a bare `--` (parseArgs treats those tokens as\n * positionals, so rig's flag parsers never see it as a flag either).\n *\n * Mirrors a plain token scan rather than each command's full parseArgs\n * config: the one divergence is `--json` consumed as a STRING option's value\n * (e.g. `rig push --relay --json`) — a pathological invocation that ends up\n * with chatter on stderr and a backstop envelope on stdout, which still\n * honors the parse guarantee.\n */\nexport function isJsonInvocation(argv: string[]): boolean {\n const [verb, ...rest] = argv;\n if (verb === undefined || !RIG_OWNED_VERBS.has(verb)) return false;\n for (const arg of rest) {\n if (arg === '--') return false;\n if (arg === '--json') return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Process-level stdout guard (third-party console.log defense)\n// ---------------------------------------------------------------------------\n\n/** Handle on an installed stdout guard. */\nexport interface StdoutGuard {\n /** Write to the REAL stdout (bypasses the redirection). */\n write(text: string): void;\n /** Undo the patch (tests; the one-shot CLI process never needs it). */\n restore(): void;\n}\n\n/**\n * Reroute every `process.stdout.write` — including `console.log` from\n * dependencies rig cannot re-route at the io seam, like the embedded\n * client's `[Bootstrap] …` logs (#260) — to stderr. Returns the ONLY writer\n * that still reaches the real stdout; ./rig.ts wires it into\n * {@link makeCliIo}'s `writeStdout` so `emitJson` output is the single\n * survivor on the machine stream.\n *\n * @param realWrite Override the saved real-stdout writer (tests capture it);\n * defaults to the unpatched `process.stdout.write`.\n */\nexport function redirectStdoutToStderr(\n realWrite?: (text: string) => void\n): StdoutGuard {\n const original = process.stdout.write;\n const real = realWrite ?? original.bind(process.stdout);\n const patched = ((\n chunk: Uint8Array | string,\n encodingOrCb?: BufferEncoding | ((err?: Error | null) => void),\n cb?: (err?: Error | null) => void\n ): boolean =>\n typeof encodingOrCb === 'function'\n ? process.stderr.write(chunk, encodingOrCb)\n : process.stderr.write(\n chunk,\n encodingOrCb,\n cb\n )) as typeof process.stdout.write;\n process.stdout.write = patched;\n return {\n write: (text) => {\n real(text);\n },\n restore: () => {\n if (process.stdout.write === patched) process.stdout.write = original;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAS,uBAAuB;;;ACLhC,SAAS,qBAAqB;;;ACN9B,SAAS,aAAAA,kBAAiB;;;ACmBnB,IAAM,+BAAN,cAA2C,MAAM;AAAA,EACtD,YAEkB,SAChB;AACA;AAAA,MACE,MAAM,OAAO,iMAGH,YAAY,kBAAkB,mBAAmB,kBAAkB;AAAA,IAE/E;AARgB;AAShB,SAAK,OAAO;AAAA,EACd;AAAA,EAVkB;AAWpB;AAGO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YACkB,KAEhB,SACA;AACA;AAAA,MACE,GAAG,OAAO,KAAK,KAAK,UAAU,GAAG,CAAC;AAAA,IAEpC;AAPgB;AAQhB,SAAK,OAAO;AAAA,EACd;AAAA,EATkB;AAUpB;AAGO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,YAA4B,QAAgB;AAC1C;AAAA,MACE,mBAAmB,KAAK,UAAU,MAAM,CAAC,oGAEnB,MAAM;AAAA,IAC9B;AAL0B;AAM1B,SAAK,OAAO;AAAA,EACd;AAAA,EAP4B;AAQ9B;AAQO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YACkB,QACA,MAChB;AACA;AAAA,MACE,UAAU,KAAK,UAAU,MAAM,CAAC,QAAQ,KAAK,MAAM,UAC7C,KAAK,KAAK,IAAI,CAAC,oFACiB,MAAM;AAAA,IAE9C;AARgB;AACA;AAQhB,SAAK,OAAO;AAAA,EACd;AAAA,EAVkB;AAAA,EACA;AAUpB;AAGO,IAAM,0BAAN,cAAsC,MAAM;AAAA,EACjD,YAEE,mBACA;AACA;AAAA,MACE,wHAEG,sBAAsB,SACnB;AAAA,gCAAmC,iBAAiB,4LAIpD;AAAA,IACR;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAGO,IAAM,yBAAN,cAAqC,MAAM;A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AU,MAAM,GAAG,SAAS,QAAQ,GAAG,KAAK,EAAE,YAAY;AAChE,eAAO,WAAW,OAAO,WAAW;AAAA,MACtC,UAAE;AACA,WAAG,MAAM;AAAA,MACX;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAEA,IAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,IAAM,KAAK,OAAO,iBAAiB,IAAI,CAAC;AAExC,SAAS,MAAM;AAAA,EACb;AAAA,EACA,KAAK,QAAQ;AAAA,EACb,KAAK,QAAQ,IAAI;AACnB,CAAC,EAAE;AAAA,EACD,CAAC,SAAS;AACR,OAAG,oBAAoB,IAAI;AAC3B,YAAQ,WAAW;AAAA,EACrB;AAAA,EACA,CAAC,QAAiB;AAChB,YAAQ,OAAO;AAAA,MACb,0BAA0B,eAAe,QAAS,IAAI,SAAS,IAAI,UAAW,OAAO,GAAG,CAAC;AAAA;AAAA,IAC3F;AACA,OAAG,oBAAoB,CAAC;AACxB,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["parseArgs","io","parseArgs","io","parseArgs","io","io","parseArgs","parseArgs","io","parseArgs","result","parseArgs","io","parseArgs","parseArgs","io","parseArgs","argv","parseArgs","parseArgs","io","require","argv","io","argv"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/rig.ts","../../src/cli/dispatch.ts","../../src/cli/balance.ts","../../src/cli/daemon-session.ts","../../src/cli/errors.ts","../../src/cli/push.ts","../../src/cli/render.ts","../../src/cli/git-config.ts","../../src/cli/remote.ts","../../src/cli/channel.ts","../../src/cli/clone.ts","../../src/cli/events.ts","../../src/cli/tracker.ts","../../src/cli/fetch.ts","../../src/cli/fund.ts","../../src/cli/git-passthrough.ts","../../src/cli/init.ts","../../src/cli/maintainers.ts","../../src/cli/output.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `rig` — the git-native TOON CLI shipped by `@toon-protocol/rig` (epic\n * #222; standalone-only since #248; git passthrough since #250).\n *\n * rig-owned subcommands (see ./dispatch.ts):\n * init one-shot repo setup (identity + toon.* git config)\n * remote relays as git remotes (#249): add/remove/list\n * push estimate → confirm → execute (#229)\n * issue | comment | pr single NIP-34 event publishes (#231), incl.\n * `pr status` (moved from `rig status` in #250)\n * channel payment channels (#262/#263): list, open,\n * close, settle\n * fund | balance client money lifecycle (#263): devnet faucet\n * drip; wallet + channel balances\n *\n * Everything else is `git <argv...>` verbatim: `rig status` runs git status.\n *\n * STRICT `--json` STDOUT (#265): when a rig-owned command runs with `--json`,\n * stdout carries exactly one JSON document — the process-level stdout guard\n * reroutes every other write (including dependencies' `console.log`) to\n * stderr, the io layer sends human lines to stderr, and the post-dispatch\n * backstop emits an error envelope for paths that bailed before emitting.\n * The git passthrough is exempt: it inherits stdio verbatim (./output.ts).\n * The enforcement matrix in ./strict-json.test.ts mirrors this composition.\n */\n\nimport { createInterface } from 'node:readline/promises';\nimport { dispatch } from './dispatch.js';\nimport {\n calmBootstrapNoise,\n isJsonInvocation,\n makeCliIo,\n redirectStdoutToStderr,\n type RigIo,\n} from './output.js';\n\n/** Real terminal I/O: stdout/stderr sinks + readline y/N confirm. */\nfunction makeIo(jsonMode: boolean): RigIo {\n // Reframe the embedded client's expected announce-402 stderr noise (#280)\n // — installed for every mode, before any command code can run.\n calmBootstrapNoise();\n // In --json mode, patch process.stdout FIRST — before any command (or its\n // dynamically imported dependencies) can write — and keep the only real\n // stdout writer for the machine document.\n const guard = jsonMode ? redirectStdoutToStderr() : undefined;\n return makeCliIo({\n jsonMode,\n writeStdout: guard\n ? guard.write\n : (text) => {\n process.stdout.write(text);\n },\n writeStderr: (text) => {\n process.stderr.write(text);\n },\n isInteractive: Boolean(process.stdin.isTTY && process.stdout.isTTY),\n confirm: async (question) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n try {\n const answer = (await rl.question(question)).trim().toLowerCase();\n return answer === 'y' || answer === 'yes';\n } finally {\n rl.close();\n }\n },\n });\n}\n\n/**\n * Exit as soon as stdio is flushed (#279). By the time dispatch resolves,\n * every command has finished its work and awaited its teardown — but the\n * embedded `@toon-protocol/client` can leave a keep-alive socket behind\n * that holds the Node event loop open for ~30 more seconds. That lingering\n * handle — not discovery or negotiation — was the bulk of the uniform\n * \"~32s per paid command\" tax the #279 study measured. Nothing rig can\n * reach unrefs it, so the one-shot CLI does what one-shot CLIs do: flush\n * and exit.\n */\nfunction exitWhenFlushed(code: number): void {\n process.exitCode = code;\n let pending = 2;\n const done = (): void => {\n pending -= 1;\n if (pending === 0) process.exit(code);\n };\n process.stdout.write('', done);\n process.stderr.write('', done);\n}\n\nconst argv = process.argv.slice(2);\nconst io = makeIo(isJsonInvocation(argv));\n\ndispatch(argv, {\n io,\n env: process.env,\n cwd: process.cwd(),\n}).then(\n (code) => {\n io.ensureSingleJsonDoc(code);\n exitWhenFlushed(code);\n },\n (err: unknown) => {\n process.stderr.write(\n `rig: unexpected error: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\\n`\n );\n io.ensureSingleJsonDoc(1);\n exitWhenFlushed(1);\n }\n);\n","/**\n * `rig` subcommand dispatch (#250): rig-owned verbs first, git for the rest.\n *\n * rig owns exactly: init, remote, clone, fetch, push, issue, comment, pr,\n * channel, fund, balance, help/-h/--help, and --version. EVERY other\n * subcommand is executed as `git <argv...>` verbatim (./git-passthrough.ts)\n * — `rig status` IS `git status`, `rig add -p`, `rig commit`, `rig rebase\n * -i`, … all land in git with rig's stdio and git's exit code. Owned verbs\n * always win: `rig push` is the paid TOON push and shadows `git push`, and\n * `rig clone`/`rig fetch` (#278) are the free TOON transports shadowing\n * their git counterparts (plain-git clone/fetch/push stay available by\n * calling git directly).\n *\n * The NIP-34 status publish that used to be `rig status` lives at\n * `rig pr status` since #250 (BREAKING) — bare `rig status` is git's.\n *\n * `--json` (#265) follows the same ownership boundary: it is a flag OF the\n * owned subcommands, never a global rig flag. `rig --json status` starts\n * with a verb rig does not own (`--json`), so the WHOLE argv passes through\n * to git verbatim — rig neither consumes the flag nor applies the strict\n * stdout contract to git's inherited stdio. The owned-verb list is pinned to\n * ./output.ts's RIG_OWNED_VERBS (strict-json.test.ts keeps them in sync).\n */\n\nimport { createRequire } from 'node:module';\nimport { runBalance } from './balance.js';\nimport { runChannel } from './channel.js';\nimport { runClone } from './clone.js';\nimport { runComment, runIssue, runPr, type EventCommandDeps } from './events.js';\nimport { runFetch } from './fetch.js';\nimport { runFund } from './fund.js';\nimport { runGitPassthrough, type GitRunner } from './git-passthrough.js';\nimport { runInit } from './init.js';\nimport { runMaintainers } from './maintainers.js';\nimport { runPush, PUSH_USAGE } from './push.js';\nimport { runRemote } from './remote.js';\n\nexport const USAGE = `rig — git with a TOON remote (pay-to-write Nostr + Arweave)\n\nUsage: rig <command> [options]\n\nCommands rig owns:\n init set up this repo: resolve your identity\n (RIG_MNEMONIC) and write the toon.* git config\n remote add <name> <url> add a relay as a REAL git remote (\"origin\" is\n remote remove <name> the default publish target); remove/list manage\n remote list them — \\`git remote -v\\` shows the same data\n clone <relay-url> <owner>/<repo-id> [dir]\n clone a TOON repo (free): relay state + Arweave\n objects (SHA-1 verified) → a real git repository,\n push/pull-capable out of the box\n fetch [remote] fetch remote refs + missing objects (free) and\n update refs/remotes/<remote>/*; no merge. Shadows\n git fetch (plain \\`git fetch\\` stays available)\n push [remote] [refspecs...] plan, price, confirm, and execute a paid push\n to TOON (defaults to the \"origin\" remote). rig\n push is the TOON transport and shadows git push;\n plain-git pushes remain available by running\n \\`git push\\` directly\n issue create file an issue (kind:1621) against a repo\n issue list | show <id> read the repo's issues + comments (free)\n pr list | show <id> read the repo's patches; show prints the full\n patch text (free)\n comment <root-event-id> comment (kind:1622) on an issue or patch\n pr create publish a patch (kind:1617) with real\n \\`git format-patch\\` content\n pr status <event-id> <state> set an issue/patch status (kind:1630-1633):\n open | applied | closed | draft\n maintainers list show the repo's declared maintainers (free); add/\n maintainers add <pubkey> remove republish the kind:30617 to change who may\n maintainers remove <pubkey> author authoritative issue/PR status (owner is\n always an implicit maintainer)\n fund drip devnet faucet funds to this identity's\n wallet (free); on other networks prints the\n address(es) to fund externally\n balance wallet balances + payment-channel holdings\n (free — chain reads and local state only)\n channel list show the payment channels paid commands hold\n (free — reads local state)\n channel open explicitly open (or resume) the channel for a\n peer; --deposit adds collateral (on-chain)\n channel close <channelId> start the settlement challenge window (on-chain)\n channel settle <channelId> release collateral after the window (on-chain)\n\nAny other command is passed through to git verbatim: \\`rig status\\` runs\n\\`git status\\`, and \\`rig add -p\\`, \\`rig commit\\`, \\`rig log --oneline\\`,\n\\`rig rebase -i\\`, … behave exactly like git (same output, same exit code).\n\nRun \\`rig <command> --help\\` for a rig command's flags. \\`rig init\\`,\n\\`rig remote\\`, \\`rig clone\\`, \\`rig fetch\\`, \\`rig issue list/show\\`,\n\\`rig pr list/show\\`, \\`rig fund\\`, \\`rig balance\\`, and \\`rig channel list\\`\nare free; push/issue create/comment/pr create/pr status are paid writes —\npermanent and non-refundable —\nand channel open/close/settle are on-chain wallet transactions; each states\nwhat it will spend and asks for confirmation before doing so (--yes skips,\n--json emits machine output).\n\nWith --json, stdout carries exactly ONE JSON document (everything human-facing\ngoes to stderr), so \\`rig <command> --json | jq\\` always parses. --json is a\nper-subcommand flag on the commands rig owns, NOT a global rig flag: it does\nnot apply to the git passthrough (\\`rig status --json\\` runs\n\\`git status --json\\`), and flags placed before the subcommand\n(\\`rig --json status\\`) pass through to git untouched.`;\n\n/** Dispatch deps: the event-command deps plus an injectable git runner. */\nexport interface DispatchDeps extends EventCommandDeps {\n /** Runs the git passthrough (default: real spawned git; tests inject). */\n runGit?: GitRunner;\n}\n\n/**\n * Version of the @toon-protocol/rig package this CLI shipped in. Resolved at\n * runtime relative to this module, which tsup may emit either as the\n * dist/cli/rig.js entry or a dist/ chunk — hence the short upward walk.\n */\nexport function rigVersion(): string {\n const require = createRequire(import.meta.url);\n for (const rel of ['../package.json', '../../package.json', '../../../package.json']) {\n try {\n const pkg = require(rel) as { name?: string; version?: string };\n if (pkg.name === '@toon-protocol/rig' && pkg.version) return pkg.version;\n } catch {\n // keep walking up\n }\n }\n return 'unknown';\n}\n\n/** Route one rig invocation (argv WITHOUT node/script); returns the exit code. */\nexport async function dispatch(\n argv: string[],\n deps: DispatchDeps\n): Promise<number> {\n const [command, ...rest] = argv;\n const { io } = deps;\n\n switch (command) {\n case 'init':\n return runInit(rest, deps);\n case 'remote':\n return runRemote(rest, deps);\n // The #278 read path — FREE (relay + Arweave gateway reads, no payment).\n case 'clone':\n return runClone(rest, deps);\n case 'fetch':\n return runFetch(rest, deps);\n case 'push':\n return runPush(rest, deps);\n case 'issue':\n return runIssue(rest, deps);\n case 'comment':\n return runComment(rest, deps);\n case 'pr':\n return runPr(rest, deps);\n case 'maintainers':\n return runMaintainers(rest, deps);\n case 'channel':\n return runChannel(rest, deps);\n case 'fund':\n return runFund(rest, deps);\n case 'balance':\n return runBalance(rest, deps);\n case 'help':\n case '--help':\n case '-h':\n io.out(USAGE);\n io.out('');\n io.out(PUSH_USAGE);\n return 0;\n case '--version':\n io.out(`rig ${rigVersion()}`);\n return 0;\n case undefined:\n io.err(USAGE);\n return 2;\n default:\n // Git passthrough (#250): rig does not own this verb, so the EXACT\n // argv tail goes to system git — flags, quoting, and exit code intact.\n return (deps.runGit ?? runGitPassthrough)(argv, {\n cwd: deps.cwd,\n env: deps.env,\n err: (line) => io.err(line),\n });\n }\n}\n","/**\n * `rig balance` — the combined money view for the active identity (#263):\n * on-chain wallet balances plus open payment-channel holdings.\n *\n * FREE: no payment, no nonce guard, no channel, no relay. The wallet section\n * reuses the client's own balance readers (`ToonClient.getBalances()` on the\n * UNSTARTED embedded client) which read the SETTLEMENT chain the channels\n * actually use — the settlement-chain key wins over the network preset's\n * primary chain, so a devnet identity funded on `evm:anvil:31337` shows that\n * balance, not the preset chain's zero (the #260-era getBalances mismatch).\n * The channel section joins the #262 peer→channel map with the claim\n * watermark: deposited / claimed / available per recorded channel of THIS\n * identity. A write uplink is NOT required (`requireUplink: false`) — reads\n * work from a read-only config.\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n channelStatus,\n ChannelMapStore,\n resolveChannelPaths,\n} from '../standalone/channel-map.js';\nimport type { WalletBalanceInfo } from '../standalone/money.js';\nimport { emitCliError } from './errors.js';\nimport {\n defaultLoadStandalone,\n identityReport,\n type IdentityReport,\n type PushDeps,\n} from './push.js';\nimport { renderIdentityLine } from './render.js';\nimport type { StandaloneContext } from './standalone-context.js';\n\nexport const BALANCE_USAGE = `Usage: rig balance [--json]\n\nShow the active identity's money: on-chain wallet balances (per configured\nchain, read from the settlement chain the payment channels actually use) and\nrecorded payment-channel holdings (deposited / claimed / available). Free —\nreads chain RPCs and local state only; nothing is signed or paid.\n\nOptions:\n --json machine-readable envelope (base units as strings)\n -h, --help show this help`;\n\n/** What `rig balance` needs — the shared paid-command deps (loader seam). */\nexport type BalanceDeps = PushDeps;\n\n/** One recorded channel in the balance view. */\ninterface ChannelBalanceJson {\n channelId: string;\n destination: string;\n peerId: string;\n chain: string;\n status: 'open' | 'closing' | 'settleable' | 'settled';\n depositTotal: string | null;\n cumulativeClaimed: string | null;\n nonce: number | null;\n /** depositTotal − cumulativeClaimed, when both are known (floored at 0). */\n available: string | null;\n}\n\n/** `--json` envelope. */\ninterface BalanceJson {\n command: 'balance';\n identity: IdentityReport;\n wallet: WalletBalanceInfo[];\n channels: ChannelBalanceJson[];\n}\n\n/** Run `rig balance`; returns the process exit code. */\nexport async function runBalance(\n args: string[],\n deps: BalanceDeps\n): Promise<number> {\n const { io, env } = deps;\n let json = false;\n try {\n const { values } = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (values.help) {\n io.out(BALANCE_USAGE);\n return 0;\n }\n json = values.json ?? false;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(BALANCE_USAGE);\n return 2;\n }\n\n let ctx: StandaloneContext | undefined;\n try {\n ctx = await (deps.loadStandalone ?? defaultLoadStandalone)({\n env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n // Free read: works without a proxy/BTP write uplink.\n requireUplink: false,\n });\n const identity = identityReport(ctx);\n\n // ── Wallet: the client's own settlement-chain-aware balance readers ─────\n const wallet = ctx.money ? await ctx.money.walletBalances() : [];\n\n // ── Channels: #262 map ⋈ claim watermark, THIS identity only ────────────\n const store = new ChannelMapStore(resolveChannelPaths(env));\n const channels: ChannelBalanceJson[] = store\n .list()\n .filter((record) => record.identity === identity.pubkey)\n .map((record) => {\n const watermark = store.readWatermark(record.channelId);\n const deposited = record.depositTotal;\n const claimed = watermark?.cumulativeAmount;\n let available: string | null = null;\n if (deposited !== undefined && claimed !== undefined) {\n const remaining = BigInt(deposited) - BigInt(claimed);\n available = (remaining > 0n ? remaining : 0n).toString();\n }\n return {\n channelId: record.channelId,\n destination: record.destination,\n peerId: record.peerId,\n chain: record.chain,\n status: channelStatus(watermark),\n depositTotal: deposited ?? null,\n cumulativeClaimed: claimed ?? null,\n nonce: watermark?.nonce ?? null,\n available,\n };\n });\n\n if (json) {\n io.emitJson({\n command: 'balance',\n identity,\n wallet,\n channels,\n } satisfies BalanceJson);\n return 0;\n }\n\n io.out(renderIdentityLine(identity));\n io.out('');\n io.out('Wallet (on-chain):');\n if (wallet.length === 0) {\n io.out(\n ' (no balance readable — no chain configured, the RPC is unreachable, ' +\n \"or the chain's keys derive only during a client start)\"\n );\n }\n for (const balance of wallet) {\n io.out(\n ` ${balance.chain.padEnd(7)} ${balance.address} ${balance.amount}` +\n (balance.asset ? ` ${balance.asset}` : ' base units') +\n (balance.assetScale !== undefined ? ` (scale ${balance.assetScale})` : '')\n );\n }\n io.out('');\n io.out('Channels (recorded):');\n if (channels.length === 0) {\n io.out(\n ' none — paid commands record their channel on first use; ' +\n '`rig channel open` records one explicitly.'\n );\n }\n for (const c of channels) {\n io.out(\n ` ${c.channelId} [${c.status}] deposited ${c.depositTotal ?? '?'} ` +\n `claimed ${c.cumulativeClaimed ?? '?'} available ${c.available ?? '?'}` +\n ` (${c.chain} → ${c.destination})`\n );\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'balance', err);\n } finally {\n if (ctx) {\n try {\n await ctx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n","/**\n * Daemon-as-accelerator delegation for paid rig commands (#279).\n *\n * Standalone remains the DEFAULT and the guarantee: every paid command works\n * with no daemon anywhere. But standalone pays a fixed bootstrap tax (relay\n * discovery, peer negotiation, channel resume) on every invocation, while a\n * running `toon-clientd` already holds all of that state warm. When the\n * daemon holds the SAME identity, the pre-#279 nonce guard refused outright\n * (two writers would race the payment channel's cumulative-claim watermark).\n * #279 refines that: the same-identity case now DELEGATES the operation to\n * the daemon's loopback `/git/*` routes — one process (the daemon) owns the\n * watermark, which is exactly the safety property the refusal protected, and\n * the command finishes in daemon time instead of bootstrap time.\n *\n * Decision matrix ({@link resolvePaidSession}):\n *\n * daemon reachable + SAME identity → delegate (`path: 'daemon'`)\n * daemon reachable + other identity → standalone (its channels are keyed\n * to its own pubkey — no shared state)\n * daemon unreachable / not a daemon → standalone\n *\n * TRUST BOUNDARY: the daemon is trusted only because it is (a) loopback and\n * (b) proven to hold the same identity — the `GET /status` identity check\n * happens BEFORE any request body is sent. A same-identity daemon already\n * holds the mnemonic-derived keys and the channel, so delegating adds no\n * authority it does not have.\n *\n * Commands the daemon has NO route for — `rig fund`, `rig balance`,\n * `rig channel open|close|settle` — always run standalone; the on-chain\n * channel mutations among them still REFUSE under a same-identity daemon\n * (the nonce guard in ../standalone/nonce-guard.ts), because close/settle\n * must not race the daemon's live claims.\n *\n * The `DaemonGitClient` is a plain-fetch client, deliberately NOT built on\n * `@toon-protocol/client-mcp`'s ControlClient — that package depends on this\n * one (its daemon Publisher wraps our planner), so importing it back would\n * be circular. Route conventions (loopback base URL, JSON bodies, the error\n * envelope with structured 409 `non_fast_forward` / 413 `oversize_objects`\n * payloads) are mirrored here; the wire types live in `../routes.ts` for\n * client-mcp to adopt. Same duplication contract as\n * `../standalone/nonce-guard.ts` — keep in sync.\n */\n\nimport { defaultDaemonPort } from '../standalone/nonce-guard.js';\nimport type {\n GitCommentRequest,\n GitErrorEnvelope,\n GitEstimateRequest,\n GitEstimateResponse,\n GitEventResponse,\n GitIssueRequest,\n GitPatchRequest,\n GitPushRequest,\n GitPushResponse,\n GitStatusRequest,\n} from '../routes.js';\nimport { resolveIdentity, type IdentitySourceKind } from './identity.js';\nimport type {\n LoadStandalone,\n StandaloneContext,\n} from './standalone-context.js';\n\n// ---------------------------------------------------------------------------\n// Daemon probe (GET /status — identity check BEFORE anything is sent)\n// ---------------------------------------------------------------------------\n\n/** Result of probing the toon-clientd loopback `/status`. */\nexport interface DaemonProbe {\n /** Control API base URL probed, e.g. `http://127.0.0.1:8787`. */\n baseUrl: string;\n /** True when `/status` answered 200 with parseable JSON. */\n reachable: boolean;\n /** `identity.nostrPubkey` from the status body (when reachable). */\n identity?: string;\n /** `ready` from the status body (channel open, publish-ready). */\n ready?: boolean;\n /** Daemon's default relay URL (`relay.url`). */\n relayUrl?: string;\n /**\n * Daemon's flat per-event publish fee (`feePerEvent`, base units, decimal\n * string) — what the single-event subcommands quote before confirming.\n */\n feePerEvent?: string;\n}\n\n/** Injectable probe signature (tests fake this instead of the network). */\nexport type ProbeDaemon = (\n env: NodeJS.ProcessEnv,\n fetchImpl: typeof fetch\n) => Promise<DaemonProbe>;\n\n/** Loopback control API base URL (port: `TOON_CLIENT_HTTP_PORT`, else 8787). */\nexport function daemonBaseUrl(env: NodeJS.ProcessEnv): string {\n const raw = env['TOON_CLIENT_HTTP_PORT'];\n const parsed = raw ? Number(raw) : NaN;\n const port =\n Number.isFinite(parsed) && parsed > 0 ? parsed : defaultDaemonPort();\n return `http://127.0.0.1:${port}`;\n}\n\n/**\n * Probe `GET /status` on the loopback control API. Anything short of a 200\n * with JSON (no listener, timeout, some other local service) reports\n * unreachable — the caller then runs standalone.\n */\nexport async function probeDaemon(\n env: NodeJS.ProcessEnv,\n fetchImpl: typeof fetch,\n timeoutMs = 1500\n): Promise<DaemonProbe> {\n const baseUrl = daemonBaseUrl(env);\n try {\n const res = await fetchImpl(`${baseUrl}/status`, {\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!res.ok) return { baseUrl, reachable: false };\n const body = (await res.json()) as {\n ready?: unknown;\n identity?: { nostrPubkey?: unknown };\n relay?: { url?: unknown };\n feePerEvent?: unknown;\n };\n const probe: DaemonProbe = { baseUrl, reachable: true };\n const pubkey = body?.identity?.nostrPubkey;\n if (typeof pubkey === 'string' && pubkey !== '') probe.identity = pubkey;\n if (typeof body?.ready === 'boolean') probe.ready = body.ready;\n if (typeof body?.relay?.url === 'string' && body.relay.url !== '') {\n probe.relayUrl = body.relay.url;\n }\n if (typeof body?.feePerEvent === 'string' && body.feePerEvent !== '') {\n probe.feePerEvent = body.feePerEvent;\n }\n return probe;\n } catch {\n return { baseUrl, reachable: false };\n }\n}\n\n// ---------------------------------------------------------------------------\n// /git/* loopback client (plain fetch — see module doc for the no-import rule)\n// ---------------------------------------------------------------------------\n\n/** The daemon answered a `/git/*` route with a non-2xx error envelope. */\nexport class DaemonRouteError extends Error {\n constructor(\n /** HTTP status code (409 non_fast_forward, 413 oversize_objects, …). */\n public readonly status: number,\n /** The parsed error envelope (structured payloads at the top level). */\n public readonly envelope: GitErrorEnvelope\n ) {\n super(envelope.detail ?? envelope.error);\n this.name = 'DaemonRouteError';\n }\n}\n\n/** The daemon vanished between the identity probe and the operation. */\nexport class DaemonUnreachableError extends Error {\n constructor(\n public readonly baseUrl: string,\n cause: unknown\n ) {\n super(\n `toon-clientd stopped answering at ${baseUrl} after the identity ` +\n `probe — nothing was paid. Re-run: rig falls back to standalone ` +\n `automatically when no daemon responds` +\n (cause instanceof Error ? ` (${cause.message})` : '')\n );\n this.name = 'DaemonUnreachableError';\n }\n}\n\nexport class DaemonGitClient {\n constructor(\n private readonly baseUrl: string,\n private readonly fetchImpl: typeof fetch\n ) {}\n\n gitEstimate(req: GitEstimateRequest): Promise<GitEstimateResponse> {\n return this.post<GitEstimateResponse>('/git/estimate', req);\n }\n\n gitPush(req: GitPushRequest): Promise<GitPushResponse> {\n return this.post<GitPushResponse>('/git/push', req);\n }\n\n gitIssue(req: GitIssueRequest): Promise<GitEventResponse> {\n return this.post<GitEventResponse>('/git/issue', req);\n }\n\n gitComment(req: GitCommentRequest): Promise<GitEventResponse> {\n return this.post<GitEventResponse>('/git/comment', req);\n }\n\n gitPatch(req: GitPatchRequest): Promise<GitEventResponse> {\n return this.post<GitEventResponse>('/git/patch', req);\n }\n\n gitStatus(req: GitStatusRequest): Promise<GitEventResponse> {\n return this.post<GitEventResponse>('/git/status', req);\n }\n\n private async post<T>(path: string, body: unknown): Promise<T> {\n let res: Response;\n try {\n res = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n } catch (err) {\n throw new DaemonUnreachableError(this.baseUrl, err);\n }\n const text = await res.text();\n let parsed: unknown;\n try {\n parsed = text === '' ? {} : JSON.parse(text);\n } catch {\n throw new DaemonRouteError(res.status, {\n error: 'invalid_response',\n detail: `daemon returned non-JSON (HTTP ${res.status}): ${text.slice(0, 200)}`,\n });\n }\n if (!res.ok) {\n const envelope =\n parsed && typeof parsed === 'object' && 'error' in parsed\n ? (parsed as GitErrorEnvelope)\n : { error: 'http_error', detail: `HTTP ${res.status}` };\n throw new DaemonRouteError(res.status, envelope);\n }\n return parsed as T;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Paid-session resolution (the decision matrix)\n// ---------------------------------------------------------------------------\n\n/** Which transport a paid command ran on (stderr line + `--json` field). */\nexport type SessionPath = 'daemon' | 'standalone';\n\n/** The delegated fast path: a same-identity daemon owns the operation. */\nexport interface DaemonSession {\n path: 'daemon';\n client: DaemonGitClient;\n baseUrl: string;\n /** Locally-resolved identity (source tier + pubkey — never the phrase). */\n identity: {\n pubkey: string;\n source: IdentitySourceKind;\n sourceLabel: string;\n };\n /** Daemon's flat per-event fee (base units, decimal), when reported. */\n feePerEvent?: string;\n /** Daemon's configured relay URL, when reported (mismatch warning). */\n daemonRelayUrl?: string;\n}\n\n/** The default path: the embedded, nonce-guarded standalone context. */\nexport interface StandaloneSession {\n path: 'standalone';\n ctx: StandaloneContext;\n}\n\nexport type PaidSession = DaemonSession | StandaloneSession;\n\nexport interface ResolveSessionOptions {\n env: NodeJS.ProcessEnv;\n /** Working directory (identity `.env` walk / standalone loader). */\n cwd: string;\n /** Stderr line sink (the chosen-path line always prints here). */\n warn(line: string): void;\n /** Standalone factory (`deps.loadStandalone ?? defaultLoadStandalone`). */\n loadStandalone: LoadStandalone;\n /** Relay-origin for the standalone #264 network bootstrap, when resolved. */\n relayUrl?: string;\n /** Fetch impl for probe + delegated requests (tests). Default: global. */\n fetchImpl?: typeof fetch;\n /** Probe override (tests). Default: {@link probeDaemon}. */\n probeDaemon?: ProbeDaemon;\n}\n\n/**\n * Decide how this paid command pays (see the module-doc matrix) and return a\n * ready session. The chosen path is announced on stderr either way, BEFORE\n * the expensive work starts. Identity is confirmed against the daemon's\n * `/status` before anything else is sent to it.\n */\nexport async function resolvePaidSession(\n options: ResolveSessionOptions\n): Promise<PaidSession> {\n const fetchImpl = options.fetchImpl ?? fetch;\n const probe = await (options.probeDaemon ?? probeDaemon)(\n options.env,\n fetchImpl\n );\n\n if (probe.reachable && probe.identity !== undefined) {\n // Local identity resolution only happens when there is a daemon to\n // compare against — the standalone loader resolves it itself otherwise.\n const identity = await resolveIdentity({\n env: options.env,\n cwd: options.cwd,\n warn: options.warn,\n });\n if (identity.pubkey === probe.identity) {\n options.warn(\n `rig: paid path: daemon — toon-clientd at ${probe.baseUrl} holds ` +\n `this identity (${identity.pubkey.slice(0, 8)}…), delegating`\n );\n return {\n path: 'daemon',\n client: new DaemonGitClient(probe.baseUrl, fetchImpl),\n baseUrl: probe.baseUrl,\n identity: {\n pubkey: identity.pubkey,\n source: identity.source,\n sourceLabel: identity.sourceLabel,\n },\n ...(probe.feePerEvent !== undefined\n ? { feePerEvent: probe.feePerEvent }\n : {}),\n ...(probe.relayUrl !== undefined\n ? { daemonRelayUrl: probe.relayUrl }\n : {}),\n };\n }\n options.warn(\n `rig: paid path: standalone — the toon-clientd at ${probe.baseUrl} ` +\n `runs a different identity (${probe.identity.slice(0, 8)}…), no ` +\n 'shared channel state'\n );\n } else {\n options.warn(\n `rig: paid path: standalone (no toon-clientd at ${probe.baseUrl})`\n );\n }\n\n const ctx = await options.loadStandalone({\n env: options.env,\n cwd: options.cwd,\n warn: options.warn,\n ...(options.relayUrl !== undefined ? { relayUrl: options.relayUrl } : {}),\n });\n return { path: 'standalone', ctx };\n}\n","/**\n * Error UX for the `rig` commands: map structured planner/publisher errors\n * to actionable terminal output (and a machine-readable envelope for\n * `--json`). The CLI is standalone-only (#248), so everything here is either\n * a local planner error, an identity/config-chain error, or a tagged error\n * surfaced from the embedded publisher (matched by name — those classes live\n * behind the lazy `@toon-protocol/client` dynamic import).\n */\n\nimport { MAX_OBJECT_SIZE } from '../objects.js';\nimport {\n NonFastForwardError,\n OversizeObjectsError,\n type OversizeObject,\n type RejectedRefUpdate,\n} from '../push.js';\nimport { GitError } from '../repo-reader.js';\nimport { DaemonRouteError, DaemonUnreachableError } from './daemon-session.js';\nimport { MissingIdentityError } from './identity.js';\nimport type { CliIo } from './output.js';\n\n/** Normalized error description: terminal lines + `--json` envelope. */\nexport interface DescribedError {\n /** Stable machine code. */\n code: string;\n /** Human-facing lines (message first, remediation after). */\n lines: string[];\n /** Machine envelope for `--json` output (structured payload included). */\n json: Record<string, unknown>;\n}\n\n/**\n * A command could not resolve the NIP-34 repo address\n * (`30617:<ownerPubkey>:<repoId>`) from flags or the `toon.*` git config\n * keys `rig init` writes.\n */\nexport class UnconfiguredRepoAddressError extends Error {\n constructor(\n /** Which half of the address is missing. */\n public readonly missing: 'repository id' | 'repository owner'\n ) {\n super(\n `no ${missing} configured — this command addresses the repo as ` +\n '30617:<ownerPubkey>:<repoId>. Run `rig init` once inside the repo ' +\n '(it writes toon.repoid/toon.owner to the local git config), or ' +\n `pass ${missing === 'repository id' ? '--repo-id <id>' : '--owner <pubkey>'} ` +\n \"explicitly (use --owner for repos you don't own).\"\n );\n this.name = 'UnconfiguredRepoAddressError';\n }\n}\n\n/** A relay URL (flag, `rig remote add`, or a remote's stored URL) is junk. */\nexport class InvalidRelayUrlError extends Error {\n constructor(\n public readonly url: string,\n /** What was being resolved, e.g. `remote \"origin\"`. */\n context: string\n ) {\n super(\n `${context}: ${JSON.stringify(url)} is not a relay URL — relays are ` +\n 'ws://, wss://, http://, or https://'\n );\n this.name = 'InvalidRelayUrlError';\n }\n}\n\n/** A paid command addressed a git remote that is not configured. */\nexport class UnknownRemoteError extends Error {\n constructor(public readonly remote: string) {\n super(\n `no remote named ${JSON.stringify(remote)} is configured — ` +\n '`rig remote list` shows configured remotes; add it with ' +\n `\\`rig remote add ${remote} <relay-url>\\``\n );\n this.name = 'UnknownRemoteError';\n }\n}\n\n/**\n * The addressed git remote carries multiple URLs (`git remote set-url --add`\n * done by hand). rig publishes to exactly one relay per paid command, so this\n * is refused BEFORE anything is fetched, uploaded, or paid (the #243\n * single-relay guard, extended to remotes).\n */\nexport class MultiUrlRemoteError extends Error {\n constructor(\n public readonly remote: string,\n public readonly urls: string[]\n ) {\n super(\n `remote ${JSON.stringify(remote)} has ${urls.length} URLs ` +\n `(${urls.join(', ')}) — rig supports one relay URL per remote. ` +\n `Fix it with \\`git remote set-url ${remote} <relay-url>\\`. ` +\n 'Nothing was uploaded, published, or paid.'\n );\n this.name = 'MultiUrlRemoteError';\n }\n}\n\n/** No relay resolved: no --relay, no usable remote, no legacy toon.relay. */\nexport class NoOriginConfiguredError extends Error {\n constructor(\n /** URL of an existing `origin` remote that is NOT a relay, if any. */\n nonRelayOriginUrl?: string\n ) {\n super(\n 'no origin configured — run `rig remote add origin <relay-url>` ' +\n '(or pass --relay <url> for a one-off publish).' +\n (nonRelayOriginUrl !== undefined\n ? `\\nThe existing \"origin\" remote (${nonRelayOriginUrl}) is not a ` +\n 'relay URL, so rig ignores it — add the relay under another ' +\n 'name (`rig remote add toon <relay-url>`) and target it ' +\n 'explicitly (`rig push toon` / `--remote toon`).'\n : '')\n );\n this.name = 'NoOriginConfiguredError';\n }\n}\n\n/** A rig command ran outside any git repository. */\nexport class NotAGitRepositoryError extends Error {\n constructor(cwd: string) {\n super(\n `not a git repository: ${cwd}\\n` +\n 'rig works inside an existing repo — create one first with `git init` ' +\n '(rig never runs it for you), then re-run.'\n );\n this.name = 'NotAGitRepositoryError';\n }\n}\n\nfunction nonFastForwardLines(refs: RejectedRefUpdate[]): string[] {\n return [\n 'Push rejected: non-fast-forward update for:',\n ...refs.map(\n (r) =>\n ` ${r.refname} remote ${r.remoteSha.slice(0, 7)} is not an ancestor of local ${r.localSha.slice(0, 7)}`\n ),\n 'The remote moved since your last push. Re-run with --force to overwrite it',\n 'WARNING: --force rewrites the published ref history for every reader of this repo.',\n ];\n}\n\nfunction oversizeLines(objects: OversizeObject[]): string[] {\n return [\n `Push rejected: ${objects.length} object(s) exceed the ${MAX_OBJECT_SIZE}-byte (95KB) upload limit:`,\n ...objects.map(\n (o) => ` ${o.path ?? o.sha} ${o.type}, ${o.size} bytes`\n ),\n 'Objects over 95KB are a hard error in v1 — split or remove the file(s) from history to push.',\n 'Large-object support is tracked in toon-client#235.',\n ];\n}\n\n/**\n * Normalize any command-path error for rendering. `command` names the rig\n * subcommand for the generic \"rig <command> failed\" lines.\n */\nexport function describeError(err: unknown, command = 'push'): DescribedError {\n if (err instanceof UnconfiguredRepoAddressError) {\n return {\n code: 'unconfigured_repo_address',\n lines: err.message.split('\\n'),\n json: { error: 'unconfigured_repo_address', detail: err.message },\n };\n }\n if (err instanceof NotAGitRepositoryError) {\n return {\n code: 'not_a_git_repository',\n lines: err.message.split('\\n'),\n json: { error: 'not_a_git_repository', detail: err.message },\n };\n }\n if (err instanceof InvalidRelayUrlError) {\n return {\n code: 'invalid_relay_url',\n lines: err.message.split('\\n'),\n json: { error: 'invalid_relay_url', detail: err.message, url: err.url },\n };\n }\n if (err instanceof UnknownRemoteError) {\n return {\n code: 'unknown_remote',\n lines: err.message.split('\\n'),\n json: { error: 'unknown_remote', detail: err.message, remote: err.remote },\n };\n }\n if (err instanceof MultiUrlRemoteError) {\n return {\n code: 'multi_url_remote',\n lines: err.message.split('\\n'),\n json: {\n error: 'multi_url_remote',\n detail: err.message,\n remote: err.remote,\n urls: err.urls,\n },\n };\n }\n if (err instanceof NoOriginConfiguredError) {\n return {\n code: 'no_origin_configured',\n lines: err.message.split('\\n'),\n json: { error: 'no_origin_configured', detail: err.message },\n };\n }\n if (err instanceof MissingIdentityError) {\n return {\n code: 'missing_identity',\n lines: err.message.split('\\n'),\n json: { error: 'missing_identity', detail: err.message },\n };\n }\n if (err instanceof NonFastForwardError) {\n return {\n code: 'non_fast_forward',\n lines: nonFastForwardLines(err.refs),\n json: { error: 'non_fast_forward', detail: err.message, refs: err.refs },\n };\n }\n if (err instanceof OversizeObjectsError) {\n return {\n code: 'oversize_objects',\n lines: oversizeLines(err.objects),\n json: {\n error: 'oversize_objects',\n detail: err.message,\n objects: err.objects,\n },\n };\n }\n if (err instanceof GitError) {\n return {\n code: 'git_error',\n lines: [`git failed: ${err.message}`],\n json: { error: 'git_error', detail: err.message },\n };\n }\n\n // Delegated-daemon path (#279): the daemon's /git/* error envelope carries\n // the same structured payloads the local planner throws — render them\n // identically so the two paths are indistinguishable to the user.\n if (err instanceof DaemonRouteError) {\n const envelope = err.envelope;\n if (envelope.error === 'non_fast_forward' && Array.isArray(envelope['refs'])) {\n return {\n code: 'non_fast_forward',\n lines: nonFastForwardLines(envelope['refs'] as RejectedRefUpdate[]),\n json: { ...envelope },\n };\n }\n if (\n envelope.error === 'oversize_objects' &&\n Array.isArray(envelope['objects'])\n ) {\n return {\n code: 'oversize_objects',\n lines: oversizeLines(envelope['objects'] as OversizeObject[]),\n json: { ...envelope },\n };\n }\n const retryHint =\n envelope.retryable === true\n ? ['The daemon reports this as retryable — re-run shortly.']\n : [];\n return {\n code: envelope.error,\n lines: [\n `daemon rejected the operation (HTTP ${err.status}): ` +\n (envelope.detail ?? envelope.error),\n ...retryHint,\n ],\n json: { ...envelope },\n };\n }\n if (err instanceof DaemonUnreachableError) {\n return {\n code: 'daemon_unreachable',\n lines: err.message.split('\\n'),\n json: { error: 'daemon_unreachable', detail: err.message },\n };\n }\n\n // Standalone-path tagged errors (matched by name — the classes live behind\n // the optional dynamic import).\n const name = err instanceof Error ? err.name : '';\n const message = err instanceof Error ? err.message : String(err);\n if (name === 'DaemonIdentityConflictError') {\n return {\n code: 'daemon_identity_conflict',\n lines: [\n message,\n 'Paid writes delegate to a same-identity daemon automatically; ' +\n 'seeing this means the daemon appeared mid-run or this operation ' +\n 'has no daemon route — stop the daemon and re-run.',\n ],\n json: { error: 'daemon_identity_conflict', detail: message },\n };\n }\n if (name === 'MissingUplinkError') {\n return {\n code: 'missing_uplink',\n lines: [message],\n json: { error: 'missing_uplink', detail: message },\n };\n }\n // Peer→channel map corruption (#262) — matched by name so tsup chunk\n // duplication between the cli and standalone entries can't break instanceof.\n if (name === 'ChannelMapCorruptError') {\n return {\n code: 'channel_map_corrupt',\n lines: [message],\n json: { error: 'channel_map_corrupt', detail: message },\n };\n }\n // Settle attempted before the challenge window elapsed (#263) — the client\n // throws this retryable error BEFORE spending gas; surface when to retry.\n if (name === 'SettleTooEarlyError') {\n const settleableAt = (err as { settleableAt?: unknown }).settleableAt;\n return {\n code: 'settle_too_early',\n lines: [\n message,\n 'The settlement challenge window is still open — nothing was spent. ' +\n 'Re-run `rig channel settle` after the settleable time.',\n ],\n json: {\n error: 'settle_too_early',\n detail: message,\n ...(typeof settleableAt === 'string' ? { settleableAt } : {}),\n },\n };\n }\n\n // The #278 read path — matched by name (same tsup chunk-duplication\n // rationale as above; the classes live in clone.ts / object-fetch.ts /\n // materialize.ts).\n if (name === 'RepoNotFoundError') {\n return {\n code: 'repo_not_found',\n lines: message.split('\\n'),\n json: { error: 'repo_not_found', detail: message },\n };\n }\n if (name === 'MissingRemoteObjectsError') {\n const missing = (err as { missing?: unknown }).missing;\n return {\n code: 'missing_remote_objects',\n lines: message.split('\\n'),\n json: {\n error: 'missing_remote_objects',\n detail: message,\n ...(Array.isArray(missing) ? { missing } : {}),\n },\n };\n }\n if (name === 'ObjectIntegrityError' || name === 'ObjectWriteMismatchError') {\n return {\n code: 'object_integrity',\n lines: message.split('\\n'),\n json: { error: 'object_integrity', detail: message },\n };\n }\n\n return {\n code: 'error',\n lines: [`rig ${command} failed: ${message}`],\n json: { error: 'error', detail: message },\n };\n}\n\n/**\n * The one command-error emitter (#265): the machine envelope (tagged with\n * the command name) goes to stdout via `emitJson` when `--json` is active,\n * and the human-facing lines ALWAYS go to stderr — so JSON consumers get the\n * parseable envelope while a human tailing stderr still sees the detail.\n * Returns the exit code (always 1) so callers can `return emitCliError(…)`.\n */\nexport function emitCliError(\n io: CliIo,\n json: boolean,\n command: string,\n err: unknown\n): 1 {\n const described = describeError(err, command);\n if (json) io.emitJson({ command, ...described.json });\n for (const line of described.lines) io.err(line);\n return 1;\n}\n","/**\n * `rig push [remote] [refspecs...]` — estimate → confirm → execute (#229,\n * standalone since #248, git-like remote resolution since #249,\n * daemon-as-accelerator since #279).\n *\n * STANDALONE is the default and the guarantee: plan locally (`planPush`) and\n * execute through the embedded, nonce-guarded StandalonePublisher (loaded\n * via dynamic import so runs that fail earlier never need\n * `@toon-protocol/client`). The identity comes from the RIG_MNEMONIC\n * precedence chain (./identity.ts).\n *\n * DAEMON FAST PATH (#279, ./daemon-session.ts): when a running toon-clientd\n * holds the SAME identity, the whole estimate→push pipeline is delegated to\n * its loopback `/git/estimate` + `/git/push` routes instead of refusing —\n * the daemon already owns the channel watermark and its bootstrap is warm,\n * so the command finishes in seconds. A daemon on a different identity, or\n * no daemon, runs standalone. The chosen path prints to stderr and lands in\n * the `--json` envelope as `path`.\n *\n * Repo addressing comes from the `toon.*` git config keys `rig init` writes\n * (`--repo-id` overrides); an unconfigured repo is a hard \"run `rig init`\n * first\" error — nothing is written as a side effect of pushing.\n *\n * The relay comes from the repo's git remotes (#249): when the first\n * positional matches a configured remote name it is the push target,\n * otherwise it is a refspec and the remote defaults to `origin`. `--relay`\n * is an ad-hoc override that bypasses remotes (all positionals are then\n * refspecs); the deprecated v0.1 `git config toon.relay` still works with a\n * migration nudge. See ./remote.ts for the full resolution order.\n *\n * Money is only spent after the confirm gate: `--yes`, or an interactive\n * y/N prompt (a non-TTY session without `--yes` refuses). `--json` emits the\n * wire-shaped plan/receipts for agent consumers; without `--yes` it becomes\n * a pure estimate (plan JSON, nothing executed, exit 0).\n */\n\nimport { parseArgs } from 'node:util';\nimport { planPush, executePush } from '../push.js';\nimport { GitRepoReader } from '../repo-reader.js';\nimport { renderIdentityLine, renderPlan, renderResult } from './render.js';\nimport {\n serializePushPlan,\n serializePushResult,\n type GitEstimateResponse,\n type GitPushResponse,\n} from '../routes.js';\nimport {\n resolvePaidSession,\n type PaidSession,\n type ProbeDaemon,\n type SessionPath,\n} from './daemon-session.js';\nimport { emitCliError, UnconfiguredRepoAddressError } from './errors.js';\nimport { listGitRemotes, readToonConfig, resolveRepoRoot } from './git-config.js';\nimport type { IdentitySourceKind } from './identity.js';\nimport { resolveRelays, singleRelayRefusal } from './remote.js';\nimport type { LoadStandalone, StandaloneContext } from './standalone-context.js';\n\n// ---------------------------------------------------------------------------\n// Dependency seam (real wiring in rig.ts; tests inject fakes)\n// ---------------------------------------------------------------------------\n\n/**\n * Terminal I/O seam — lives in ./output.ts since #265 (the strict `--json`\n * stdout layer); re-exported here because every command module historically\n * imports it from push.ts.\n */\nexport type { CliIo } from './output.js';\nimport type { CliIo } from './output.js';\n\nexport interface PushDeps {\n io: CliIo;\n env: NodeJS.ProcessEnv;\n cwd: string;\n /** Standalone factory; defaults to the real dynamic-import loader. */\n loadStandalone?: LoadStandalone;\n /** Fetch for the daemon probe + delegated `/git/*` requests (tests). */\n fetchImpl?: typeof fetch;\n /** Daemon `/status` probe override (tests fake the loopback daemon). */\n probeDaemon?: ProbeDaemon;\n}\n\n/**\n * Resolve the paid session for a command from its deps (#279): probe for a\n * same-identity toon-clientd (→ delegate) before falling back to the\n * standalone loader. Shared by push and the single-event commands.\n */\nexport function loadPaidSession(\n deps: PushDeps,\n relayUrl: string | undefined\n): Promise<PaidSession> {\n return resolvePaidSession({\n env: deps.env,\n cwd: deps.cwd,\n warn: (line) => deps.io.err(line),\n loadStandalone: deps.loadStandalone ?? defaultLoadStandalone,\n ...(relayUrl !== undefined ? { relayUrl } : {}),\n ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),\n ...(deps.probeDaemon ? { probeDaemon: deps.probeDaemon } : {}),\n });\n}\n\n/**\n * Default standalone factory (shared by every paid command). Dynamic import:\n * `standalone-mode` (and its `@toon-protocol/client` dependency) only loads\n * once a command actually needs to sign or pay.\n */\nexport const defaultLoadStandalone: LoadStandalone = async (options) => {\n const mod = await import('./standalone-mode.js');\n return mod.createStandaloneContext(options);\n};\n\n/** Identity report shared by every paid command's `--json` envelope. */\nexport interface IdentityReport {\n /** Derived Nostr pubkey (hex) of the active identity. */\n pubkey: string;\n /** Which tier of the RIG_MNEMONIC precedence chain supplied it. */\n source: IdentitySourceKind;\n /** Human-facing source label, e.g. `RIG_MNEMONIC env` or a file path. */\n sourceLabel: string;\n}\n\n/** Build the identity report of a loaded standalone context. */\nexport function identityReport(ctx: StandaloneContext): IdentityReport {\n return {\n pubkey: ctx.ownerPubkey,\n source: ctx.identitySource,\n sourceLabel: ctx.identitySourceLabel,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Usage\n// ---------------------------------------------------------------------------\n\nexport const PUSH_USAGE = `Usage: rig push [remote] [refspecs...] [options]\n\nPush local git refs to TOON: uploads the object delta to Arweave (paid) and\npublishes the NIP-34 refs event (kind:30618; kind:30617 announce on first\npush). Writes are permanent and non-refundable.\n\nThe repo must be set up once with \\`rig init\\` (writes toon.repoid/toon.owner\nto the local git config); the identity comes from RIG_MNEMONIC (env or a\nproject .env), or the ~/.toon-client keystore/config.\n\nThe relay is a git remote: \\`rig push\\` publishes via \"origin\" (set up with\n\\`rig remote add origin <relay-url>\\`); \\`rig push <remote> [refspecs...]\\`\npublishes via a named remote. When the first positional matches a configured\nremote name it is the remote; otherwise it is a refspec and the remote\ndefaults to origin. Refspecs are branch/tag names or full refnames; default\nis the current branch.\n\nOptions:\n --force allow non-fast-forward ref updates (overwrites remote history)\n --all push all local branches\n --tags push all local tags\n --yes skip the fee confirmation (required when not a TTY)\n --json machine-readable plan/receipts; without --yes it is a pure\n estimate (nothing executed)\n --relay <url> ad-hoc relay override (exactly one) — bypasses the\n configured remotes; every positional is then a refspec.\n The deprecated v0.1 \\`git config toon.relay\\` still works\n as a fallback, with a migration nudge\n --repo-id <id> repository id / NIP-34 d-tag (default: git config\n toon.repoid — run \\`rig init\\` to set it)\n -h, --help show this help`;\n\n// ---------------------------------------------------------------------------\n// Refspec selection\n// ---------------------------------------------------------------------------\n\n/**\n * Expand positional refspecs / `--all` / `--tags` into full refnames using\n * the local ref list; default (no selection) is the current branch.\n */\nexport async function selectRefspecs(\n reader: GitRepoReader,\n positionals: string[],\n all: boolean,\n tags: boolean\n): Promise<string[]> {\n const { head, refs } = await reader.listRefs();\n const byName = new Set(refs.map((r) => r.refname));\n\n const selected: string[] = [];\n const add = (refname: string): void => {\n if (!selected.includes(refname)) selected.push(refname);\n };\n\n for (const spec of positionals) {\n if (byName.has(spec)) {\n add(spec);\n } else if (byName.has(`refs/heads/${spec}`)) {\n add(`refs/heads/${spec}`);\n } else if (byName.has(`refs/tags/${spec}`)) {\n add(`refs/tags/${spec}`);\n } else {\n throw new Error(\n `refspec ${JSON.stringify(spec)} matches no local branch or tag ` +\n '(ref deletion is out of scope in v1)'\n );\n }\n }\n if (all) {\n for (const ref of refs) {\n if (ref.refname.startsWith('refs/heads/')) add(ref.refname);\n }\n }\n if (tags) {\n for (const ref of refs) {\n if (ref.refname.startsWith('refs/tags/')) add(ref.refname);\n }\n }\n if (selected.length === 0) {\n if (!head) {\n throw new Error(\n 'HEAD is detached and no refspec was given — pass a branch/tag name, --all, or --tags'\n );\n }\n add(head);\n }\n return selected;\n}\n\n// ---------------------------------------------------------------------------\n// Command\n// ---------------------------------------------------------------------------\n\ninterface PushFlags {\n force: boolean;\n all: boolean;\n tags: boolean;\n yes: boolean;\n json: boolean;\n relay: string[];\n repoId?: string;\n help: boolean;\n positionals: string[];\n}\n\nfunction parsePushArgs(args: string[]): PushFlags {\n const { values, positionals } = parseArgs({\n args,\n options: {\n force: { type: 'boolean', default: false },\n all: { type: 'boolean', default: false },\n tags: { type: 'boolean', default: false },\n yes: { type: 'boolean', default: false },\n json: { type: 'boolean', default: false },\n relay: { type: 'string', multiple: true },\n 'repo-id': { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: true,\n });\n const flags: PushFlags = {\n force: values.force ?? false,\n all: values.all ?? false,\n tags: values.tags ?? false,\n yes: values.yes ?? false,\n json: values.json ?? false,\n relay: values.relay ?? [],\n help: values.help ?? false,\n positionals,\n };\n const repoId = values['repo-id'];\n if (repoId !== undefined) flags.repoId = repoId;\n return flags;\n}\n\n/** JSON envelope emitted by `--json` runs (agents consume this). */\ninterface PushJsonOutput {\n command: 'push';\n repoId: string;\n /** Which transport paid: delegated daemon or embedded standalone (#279). */\n path: SessionPath;\n /** Active identity: source tier + derived pubkey (never the phrase). */\n identity: IdentityReport;\n /** True when the paid execute step ran. */\n executed: boolean;\n /** True when every selected ref already matched the remote (no-op). */\n upToDate: boolean;\n plan: GitEstimateResponse;\n result?: GitPushResponse;\n hint?: string;\n}\n\n/** Run `rig push`; returns the process exit code. */\nexport async function runPush(args: string[], deps: PushDeps): Promise<number> {\n const { io } = deps;\n\n let flags: PushFlags;\n try {\n flags = parsePushArgs(args);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(PUSH_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(PUSH_USAGE);\n return 0;\n }\n\n let standaloneCtx: StandaloneContext | undefined;\n try {\n // ── Repo + config resolution (rig init writes these) ────────────────────\n const repoRoot = await resolveRepoRoot(deps.cwd);\n const toonConfig = await readToonConfig(repoRoot);\n const repoId = flags.repoId ?? toonConfig.repoId;\n if (!repoId) throw new UnconfiguredRepoAddressError('repository id');\n const reader = new GitRepoReader(repoRoot);\n\n // ── Remote-vs-refspec resolution (git-like: `rig push [remote] [refspecs…]`)\n // The first positional is the remote when it names a configured git\n // remote; with --relay the remotes are bypassed and every positional is\n // a refspec.\n let remoteName: string | undefined;\n let refspecArgs = flags.positionals;\n if (flags.relay.length === 0 && refspecArgs.length > 0) {\n const first = refspecArgs[0] as string;\n const remoteNames = new Set(\n (await listGitRemotes(repoRoot)).map((r) => r.name)\n );\n if (remoteNames.has(first)) {\n remoteName = first;\n refspecArgs = refspecArgs.slice(1);\n } else {\n // Not a remote, so it must be a refspec — distinguish a typo'd /\n // unconfigured remote from a bad refspec with one combined error.\n const { refs } = await reader.listRefs();\n const known = new Set(refs.map((r) => r.refname));\n if (\n !known.has(first) &&\n !known.has(`refs/heads/${first}`) &&\n !known.has(`refs/tags/${first}`)\n ) {\n throw new Error(\n `${JSON.stringify(first)} is neither a configured remote nor a ` +\n 'local branch/tag — add the relay remote ' +\n `(\\`rig remote add ${first} <relay-url>\\`; \\`rig remote list\\` ` +\n 'shows configured remotes) or fix the refspec'\n );\n }\n }\n }\n const refspecs = await selectRefspecs(\n reader,\n refspecArgs,\n flags.all,\n flags.tags\n );\n\n // ── Relay resolution (#249: --relay > named remote > origin > toon.relay)\n const resolved = await resolveRelays({\n relayFlags: flags.relay,\n remoteName,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n if (resolved.nudge !== undefined) io.err(resolved.nudge);\n const relaysUsed = resolved.relays;\n // StandalonePublisher publishes to exactly one relay (its publishEvent\n // throws on >1). Multiple relays can arrive here without explicit intent\n // (repeated --relay flags, an old multi-valued git config `toon.relay`).\n // Refuse up front, before anything is fetched, uploaded, or paid.\n if (relaysUsed.length > 1) {\n io.err(singleRelayRefusal(resolved, 'Nothing was uploaded or paid.'));\n return 1;\n }\n\n // ── Paid session (#279): same-identity daemon → delegate; else the\n // standalone context (identity chain + nonce guard).\n const session = await loadPaidSession(deps, relaysUsed[0]);\n const path = session.path;\n let identity: IdentityReport;\n if (session.path === 'standalone') {\n standaloneCtx = session.ctx;\n identity = identityReport(standaloneCtx);\n } else {\n identity = session.identity;\n }\n\n if (toonConfig.owner && toonConfig.owner !== identity.pubkey) {\n io.err(\n `warning: git config toon.owner (${toonConfig.owner.slice(0, 8)}…) differs from ` +\n `the active identity (${identity.pubkey.slice(0, 8)}…) — this push publishes ` +\n \"under the ACTIVE identity's repo namespace, not the configured owner's. \" +\n 'Re-run `rig init` to adopt the active identity.'\n );\n }\n\n // ── Estimate ────────────────────────────────────────────────────────────\n // Standalone plans locally; the daemon path delegates the plan to\n // `POST /git/estimate` (same wire shape — ../routes.ts).\n let plan: GitEstimateResponse;\n let execute: () => Promise<GitPushResponse>;\n if (session.path === 'standalone') {\n const ctx = session.ctx;\n const remoteState = await ctx.fetchRemote({\n ownerPubkey: ctx.ownerPubkey,\n repoId,\n relayUrls: relaysUsed,\n });\n const feeRates = await ctx.publisher.getFeeRates();\n const pushPlan = await planPush({\n repoReader: reader,\n remoteState,\n feeRates,\n repoId,\n refs: refspecs,\n force: flags.force,\n });\n plan = serializePushPlan(pushPlan);\n execute = async () =>\n serializePushResult(\n pushPlan,\n await executePush({\n plan: pushPlan,\n publisher: ctx.publisher,\n remoteState,\n repoReader: reader,\n relayUrls: relaysUsed,\n })\n );\n } else {\n const client = session.client;\n plan = await client.gitEstimate({\n repoPath: repoRoot,\n repoId,\n refspecs,\n force: flags.force,\n relayUrls: relaysUsed,\n });\n execute = () =>\n client.gitPush({\n repoPath: repoRoot,\n repoId,\n refspecs,\n force: flags.force,\n relayUrls: relaysUsed,\n confirm: true,\n });\n }\n\n // ── Up-to-date short-circuit (never publish a no-op refs event) ─────────\n const upToDate = plan.refUpdates.every((u) => u.kind === 'up-to-date');\n if (upToDate) {\n if (flags.json) {\n io.emitJson({\n command: 'push',\n repoId,\n path,\n identity,\n executed: false,\n upToDate: true,\n plan,\n } satisfies PushJsonOutput);\n } else {\n io.out('Everything up-to-date — nothing to push (and nothing paid).');\n }\n return 0;\n }\n\n // ── Confirm gate ────────────────────────────────────────────────────────\n if (!flags.json) {\n for (const line of renderPlan(plan)) io.out(line);\n io.out(renderIdentityLine(identity));\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n command: 'push',\n repoId,\n path,\n identity,\n executed: false,\n upToDate: false,\n plan,\n hint: 'estimate only — re-run with --yes to upload and publish (permanent, non-refundable)',\n } satisfies PushJsonOutput);\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n 'refusing to spend channel funds without confirmation in a non-interactive ' +\n 'session — re-run with --yes (or use --json for an estimate)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Proceed with paid push (total ${plan.estimate.totalFee} base units)? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was uploaded or published.');\n return 1;\n }\n }\n\n // ── Execute ─────────────────────────────────────────────────────────────\n const result = await execute();\n\n // ── Receipts ────────────────────────────────────────────────────────────\n if (flags.json) {\n io.emitJson({\n command: 'push',\n repoId,\n path,\n identity,\n executed: true,\n upToDate: false,\n plan,\n result,\n } satisfies PushJsonOutput);\n } else {\n for (const line of renderResult(result)) io.out(line);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, 'push', err);\n } finally {\n if (standaloneCtx) {\n try {\n await standaloneCtx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n","/**\n * Human-facing rendering for `rig push`: the pre-push confirm table and the\n * post-push receipts. Machine consumers use `--json` instead (the raw wire\n * shapes from ../routes.ts) — nothing here is meant to be parsed.\n */\n\nimport type {\n GitEstimateResponse,\n GitEventResponse,\n GitPushResponse,\n GitRefUpdate,\n GitRepoAddr,\n} from '../routes.js';\n\n/** Group thousands for readability: 1234567 → '1,234,567'. */\nexport function formatNumber(value: number | string | bigint): string {\n return String(value).replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n}\n\nfunction shortSha(sha: string | null): string {\n return sha ? sha.slice(0, 7) : '(none)';\n}\n\nfunction refLine(update: GitRefUpdate): string {\n const arrow = `${shortSha(update.remoteSha)} → ${shortSha(update.localSha)}`;\n return ` ${update.refname} ${arrow} (${update.kind})`;\n}\n\n/**\n * One-line identity report: derived pubkey + which chain tier supplied the\n * mnemonic (never the phrase itself).\n */\nexport function renderIdentityLine(identity: {\n pubkey: string;\n sourceLabel: string;\n}): string {\n return `Identity: ${identity.pubkey} (from ${identity.sourceLabel})`;\n}\n\n/** The pre-push confirm table (refs, objects, itemized fees, warning). */\nexport function renderPlan(plan: GitEstimateResponse): string[] {\n const lines: string[] = [];\n lines.push(\n `Push plan for repo \"${plan.repoId}\"` +\n (plan.announceNeeded ? ' — first push, will announce (kind:30617)' : '')\n );\n lines.push('Refs:');\n for (const update of plan.refUpdates) lines.push(refLine(update));\n\n const est = plan.estimate;\n const skipped = Object.keys(plan.knownShaToTxId).length;\n lines.push(\n `Objects: ${est.objectCount} to upload` +\n ` (${formatNumber(est.totalObjectBytes)} bytes)` +\n (skipped > 0 ? `; ${skipped} already on Arweave (free)` : '')\n );\n lines.push('Fees (base units):');\n lines.push(\n ` upload ${est.objectCount} object(s), ${formatNumber(est.totalObjectBytes)} bytes` +\n ` ${formatNumber(est.uploadFee)}`\n );\n lines.push(` events ${est.eventCount} event(s) ${formatNumber(est.eventFees)}`);\n lines.push(` total ${formatNumber(est.totalFee)}`);\n lines.push('Writes are permanent and non-refundable.');\n return lines;\n}\n\n/** Human label for a per-event fee that may be unknown (older daemons). */\nexport function feeLabel(fee: string | undefined): string {\n return fee !== undefined\n ? `${formatNumber(fee)} base units`\n : \"the publisher's configured per-event fee\";\n}\n\n/**\n * Pre-publish summary for the single-event subcommands\n * (issue/comment/pr/status): what is published, against which repo address,\n * at what fee — the confirm gate follows these lines.\n */\nexport function renderEventPlan(opts: {\n /** e.g. `issue \"Fix the flux\" (kind:1621)`. */\n action: string;\n addr: GitRepoAddr;\n /** Active identity (source + derived pubkey). */\n identity: { pubkey: string; sourceLabel: string };\n /** Per-event fee (base units, decimal string), when known. */\n fee?: string;\n}): string[] {\n return [\n `Publish ${opts.action}`,\n `Repo: 30617:${opts.addr.ownerPubkey}:${opts.addr.repoId}`,\n renderIdentityLine(opts.identity),\n `Fee: ${feeLabel(opts.fee)}. Writes are permanent and non-refundable.`,\n ];\n}\n\n/** Receipt line for one published single-event git write. */\nexport function renderEventReceipt(\n action: string,\n result: GitEventResponse\n): string[] {\n const lines = [\n `Published ${action}: ${result.eventId} paid ${formatNumber(result.feePaid)} base units`,\n ];\n if (result.channelBalanceAfter !== undefined) {\n lines.push(\n `Channel balance after: ${formatNumber(result.channelBalanceAfter)} base units`\n );\n }\n return lines;\n}\n\n/** Post-push receipts: per-object skipped/paid, event ids, paid-vs-estimate. */\nexport function renderResult(result: GitPushResponse): string[] {\n const lines: string[] = [];\n lines.push(`Pushed \"${result.repoId}\":`);\n const paid = result.uploads.filter((u) => !u.skipped);\n const skipped = result.uploads.filter((u) => u.skipped);\n for (const upload of result.uploads) {\n lines.push(\n ` object ${upload.sha.slice(0, 12)} ${upload.skipped ? 'skipped (already stored)' : `paid ${formatNumber(upload.feePaid)}`}` +\n ` ar:${upload.txId}`\n );\n }\n lines.push(\n `Uploads: ${paid.length} paid, ${skipped.length} skipped (content-addressed).`\n );\n if (result.announceReceipt) {\n lines.push(\n `Announcement (kind:30617): ${result.announceReceipt.eventId}` +\n ` paid ${formatNumber(result.announceReceipt.feePaid)}`\n );\n }\n lines.push(\n `Refs event (kind:30618): ${result.refsReceipt.eventId}` +\n ` paid ${formatNumber(result.refsReceipt.feePaid)}`\n );\n lines.push(\n `Total paid: ${formatNumber(result.totalFeePaid)} base units` +\n ` (estimate was ${formatNumber(result.estimate.totalFee)})`\n );\n return lines;\n}\n","/**\n * Repo-local `rig` configuration, persisted in git's own storage:\n *\n * toon.repoid NIP-34 repository identifier (`d` tag)\n * toon.owner repository owner's Nostr pubkey (hex) — the identity that\n * signs kind:30617/30618 (`a`-tag `30617:<owner>:<repoId>`)\n * toon.relay relay URL(s), multi-valued — DEPRECATED since #249 (relays\n * live in real git remotes now; the key stays readable as a\n * fallback and is removed in v0.3)\n *\n * plus the REAL git remotes (`remote.<name>.url`) that #249 maps relays onto:\n * `rig remote add origin <relay-url>` is `git remote add`, so `git remote -v`\n * shows rig's relays and plain git tooling round-trips them.\n *\n * All access goes through `execFile git` with argument arrays (same\n * injection posture as GitRepoReader — never a shell).\n */\n\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\n\nconst execFileAsync = promisify(execFile);\n\n/** The rig-relevant git config keys of one repository. */\nexport interface ToonRepoConfig {\n repoId?: string;\n owner?: string;\n relays: string[];\n}\n\nasync function git(\n repoPath: string,\n args: string[],\n allowExitCodes: number[] = []\n): Promise<{ stdout: string; exitCode: number }> {\n try {\n const { stdout } = await execFileAsync('git', args, {\n cwd: repoPath,\n encoding: 'utf-8',\n });\n return { stdout, exitCode: 0 };\n } catch (err) {\n const e = err as NodeJS.ErrnoException & {\n code?: number | string;\n stdout?: string;\n stderr?: string;\n };\n const exitCode = typeof e.code === 'number' ? e.code : undefined;\n if (exitCode !== undefined && allowExitCodes.includes(exitCode)) {\n return { stdout: e.stdout ?? '', exitCode };\n }\n throw new Error(\n `git ${args.join(' ')} failed${exitCode !== undefined ? ` (exit ${exitCode})` : ''}: ` +\n `${(e.stderr ?? e.message ?? '').trim()}`\n );\n }\n}\n\n/**\n * Resolve the repository worktree root for `cwd` via\n * `git rev-parse --show-toplevel`. Throws a clear error when `cwd` is not\n * inside a git repository.\n */\nexport async function resolveRepoRoot(cwd: string): Promise<string> {\n try {\n const { stdout } = await execFileAsync(\n 'git',\n ['rev-parse', '--show-toplevel'],\n { cwd, encoding: 'utf-8' }\n );\n const root = stdout.trim();\n if (!root) throw new Error('empty rev-parse output');\n return root;\n } catch (err) {\n const e = err as { stderr?: string; message?: string };\n throw new Error(\n `not a git repository (run rig inside a repo): ${(e.stderr ?? e.message ?? '').trim()}`\n );\n }\n}\n\n/** Read the `toon.*` git config keys of the repository at `repoPath`. */\nexport async function readToonConfig(repoPath: string): Promise<ToonRepoConfig> {\n // exit 1 = key unset (git config --get convention) — tolerated everywhere.\n const [repoId, owner, relays] = await Promise.all([\n git(repoPath, ['config', '--get', 'toon.repoid'], [1]),\n git(repoPath, ['config', '--get', 'toon.owner'], [1]),\n git(repoPath, ['config', '--get-all', 'toon.relay'], [1]),\n ]);\n const config: ToonRepoConfig = {\n relays: relays.stdout\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean),\n };\n const id = repoId.stdout.trim();\n if (repoId.exitCode === 0 && id) config.repoId = id;\n const own = owner.stdout.trim();\n if (owner.exitCode === 0 && own) config.owner = own;\n return config;\n}\n\n/** One configured git remote: its name + (possibly multiple) fetch URLs. */\nexport interface GitRemoteInfo {\n name: string;\n urls: string[];\n}\n\n/**\n * URLs of the git remote `name` (`remote.<name>.url`, multi-valued when\n * `git remote set-url --add` was used). `[]` when the remote does not exist.\n */\nexport async function getGitRemoteUrls(\n repoPath: string,\n name: string\n): Promise<string[]> {\n // exit 1 = key unset / invalid key — either way, no such remote.\n const { stdout } = await git(\n repoPath,\n ['config', '--get-all', `remote.${name}.url`],\n [1]\n );\n return stdout\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean);\n}\n\n/** All configured git remotes with their URLs (`git remote -v` data). */\nexport async function listGitRemotes(\n repoPath: string\n): Promise<GitRemoteInfo[]> {\n const { stdout } = await git(repoPath, ['remote']);\n const names = stdout\n .split('\\n')\n .map((l) => l.trim())\n .filter(Boolean);\n const remotes: GitRemoteInfo[] = [];\n for (const name of names) {\n remotes.push({ name, urls: await getGitRemoteUrls(repoPath, name) });\n }\n return remotes;\n}\n\n/** `git remote add <name> <url>` — real git remote storage, never a shell. */\nexport async function addGitRemote(\n repoPath: string,\n name: string,\n url: string\n): Promise<void> {\n await git(repoPath, ['remote', 'add', name, url]);\n}\n\n/** `git remote remove <name>`. */\nexport async function removeGitRemote(\n repoPath: string,\n name: string\n): Promise<void> {\n await git(repoPath, ['remote', 'remove', name]);\n}\n\n/**\n * Persist the `toon.*` keys (repo-local config). Only supplied fields are\n * written; `relays` replaces the whole multi-valued list.\n */\nexport async function writeToonConfig(\n repoPath: string,\n config: { repoId?: string; owner?: string; relays?: string[] }\n): Promise<void> {\n if (config.repoId !== undefined) {\n await git(repoPath, ['config', 'toon.repoid', config.repoId]);\n }\n if (config.owner !== undefined) {\n await git(repoPath, ['config', 'toon.owner', config.owner]);\n }\n if (config.relays !== undefined && config.relays.length > 0) {\n // Replace the whole list: unset-all (exit 5 = key did not exist) + re-add.\n await git(repoPath, ['config', '--unset-all', 'toon.relay'], [5]);\n for (const relay of config.relays) {\n await git(repoPath, ['config', '--add', 'toon.relay', relay]);\n }\n }\n}\n","/**\n * Relays as origins (#249): the `rig remote` subcommand and the relay\n * resolution every paid command shares.\n *\n * Remotes are stored as REAL git remotes (`git remote add/remove` under the\n * hood), so `git remote -v` shows them and plain git tooling round-trips the\n * config — no parallel store. Paid commands resolve their relay as:\n *\n * 1. `--relay <url>` ad-hoc override, bypasses remotes\n * 2. a named remote `rig push <remote>` / `--remote <name>`\n * 3. the `origin` remote the default target\n * 4. git config `toon.relay` DEPRECATED v0.1 fallback (one-line nudge;\n * the key is removed in v0.3)\n * 5. error \"no origin configured — run `rig remote\n * add origin <relay-url>`\"\n *\n * A remote with multiple URLs (`git remote set-url --add` done by hand) is\n * refused BEFORE anything is fetched, uploaded, or paid: rig publishes to\n * exactly one relay per paid command (the #243 single-relay guard). One\n * carve-out: a default `origin` whose URLs are ALL non-relay is a plain git\n * remote — it is skipped like any single non-relay origin, never refused.\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n emitCliError,\n InvalidRelayUrlError,\n MultiUrlRemoteError,\n NoOriginConfiguredError,\n NotAGitRepositoryError,\n UnknownRemoteError,\n} from './errors.js';\nimport {\n addGitRemote,\n getGitRemoteUrls,\n listGitRemotes,\n readToonConfig,\n removeGitRemote,\n resolveRepoRoot,\n} from './git-config.js';\nimport type { CliIo } from './push.js';\n\n// ---------------------------------------------------------------------------\n// Relay URL validation\n// ---------------------------------------------------------------------------\n\nconst RELAY_PROTOCOLS = new Set(['ws:', 'wss:', 'http:', 'https:']);\n\n/** True when `url` parses and uses a relay scheme (ws/wss/http/https). */\nexport function isRelayUrl(url: string): boolean {\n try {\n return RELAY_PROTOCOLS.has(new URL(url).protocol);\n } catch {\n return false;\n }\n}\n\n/** Throw {@link InvalidRelayUrlError} unless `url` is a relay URL. */\nexport function assertRelayUrl(url: string, context: string): void {\n if (!isRelayUrl(url)) throw new InvalidRelayUrlError(url, context);\n}\n\n// ---------------------------------------------------------------------------\n// Relay resolution (shared by push + the event commands)\n// ---------------------------------------------------------------------------\n\n/** Where the resolved relay came from. */\nexport type RelaySource = 'relay-flag' | 'remote' | 'toon.relay';\n\nexport interface ResolvedRelays {\n /** Relay URLs to publish to (paid commands still enforce exactly one). */\n relays: string[];\n source: RelaySource;\n /** The git remote that supplied the URL (source === 'remote'). */\n remoteName?: string;\n /** One-line stderr note (toon.relay deprecation), when applicable. */\n nudge?: string;\n}\n\nexport interface ResolveRelaysOptions {\n /** `--relay` flag values (may be >1 — the command-level guard refuses). */\n relayFlags: string[];\n /** Explicitly requested remote (`rig push <remote>` / `--remote <name>`). */\n remoteName?: string | undefined;\n /** Repo worktree root; undefined when not inside a git repository. */\n repoRoot?: string | undefined;\n /** Deprecated `git config toon.relay` values (v0.1 fallback). */\n toonRelays: string[];\n}\n\n/**\n * Resolve the relay(s) for a paid command. Throws (before any payment):\n * {@link UnknownRemoteError}, {@link MultiUrlRemoteError},\n * {@link InvalidRelayUrlError}, {@link NoOriginConfiguredError}.\n */\nexport async function resolveRelays(\n opts: ResolveRelaysOptions\n): Promise<ResolvedRelays> {\n // 1. Ad-hoc --relay override: bypasses the configured remotes entirely.\n if (opts.relayFlags.length > 0) {\n return { relays: opts.relayFlags, source: 'relay-flag' };\n }\n\n // 2. Explicitly named remote: must exist, carry ONE URL, and be a relay.\n if (opts.remoteName !== undefined) {\n const urls =\n opts.repoRoot !== undefined\n ? await getGitRemoteUrls(opts.repoRoot, opts.remoteName)\n : [];\n if (urls.length === 0) throw new UnknownRemoteError(opts.remoteName);\n if (urls.length > 1) throw new MultiUrlRemoteError(opts.remoteName, urls);\n const url = urls[0] as string;\n assertRelayUrl(url, `remote ${JSON.stringify(opts.remoteName)}`);\n return { relays: urls, source: 'remote', remoteName: opts.remoteName };\n }\n\n // 3. Default remote: origin — when it looks like a relay. A PURELY\n // non-relay origin (e.g. a GitHub clone URL, even one with several\n // mirror push URLs) is skipped, not an error: rig shares git's remote\n // namespace, so pre-existing git origins must not break paid commands\n // that can still resolve via toon.relay. But the moment ANY of a\n // multi-URL origin's URLs is relay-shaped, the publish target is\n // ambiguous — refuse before anything is fetched, uploaded, or paid\n // (the #243 single-relay guard).\n let nonRelayOriginUrl: string | undefined;\n if (opts.repoRoot !== undefined) {\n const urls = await getGitRemoteUrls(opts.repoRoot, 'origin');\n if (urls.length === 1 && isRelayUrl(urls[0] as string)) {\n return { relays: urls, source: 'remote', remoteName: 'origin' };\n }\n if (urls.length > 1 && urls.some(isRelayUrl)) {\n throw new MultiUrlRemoteError('origin', urls);\n }\n // Reachable only when every remaining URL is non-relay (single relay URL\n // returned above; multi-URL with any relay URL threw above), so urls[0]\n // is guaranteed non-relay — NoOriginConfiguredError's message relies on\n // that (\"the existing origin is not a relay URL\").\n if (urls.length > 0) nonRelayOriginUrl = urls[0] as string;\n }\n\n // 4. Deprecated v0.1 fallback: git config toon.relay (nudges to migrate).\n if (opts.toonRelays.length > 0) {\n return {\n relays: opts.toonRelays,\n source: 'toon.relay',\n nudge:\n 'note: git config toon.relay is deprecated (removed in v0.3) — ' +\n `migrate: rig remote add origin ${opts.toonRelays[0]}`,\n };\n }\n\n // 5. Nothing resolved.\n throw new NoOriginConfiguredError(nonRelayOriginUrl);\n}\n\n/**\n * Refusal line for >1 resolved relays: the StandalonePublisher publishes to\n * exactly one relay per paid command, and multiple can arrive without\n * explicit intent (repeated --relay flags, a multi-valued toon.relay).\n * `nothingHappened` names what was NOT done, e.g. 'Nothing was uploaded or\n * paid.'\n */\nexport function singleRelayRefusal(\n resolved: ResolvedRelays,\n nothingHappened: string\n): string {\n const fix =\n resolved.source === 'relay-flag'\n ? 'pass exactly one --relay <url>'\n : 'trim git config toon.relay to one URL (better: migrate — ' +\n '`rig remote add origin <relay-url>`)';\n return (\n `rig publishes to a single relay, but ${resolved.relays.length} are ` +\n `configured (${resolved.relays.join(', ')}) — ${fix}. ${nothingHappened}`\n );\n}\n\n// ---------------------------------------------------------------------------\n// rig remote <add|remove|list>\n// ---------------------------------------------------------------------------\n\nexport const REMOTE_USAGE = `Usage: rig remote <add|remove|list> [args] [options]\n\nManage the relays this repo publishes to. Remotes are stored as REAL git\nremotes (\\`git remote -v\\` shows them; plain git tooling round-trips). Paid\ncommands publish via the \"origin\" remote by default; \\`rig push <remote>\\`\nand \\`--remote <name>\\` target another one. Free — nothing is published or\npaid.\n\nCommands:\n add <name> <relay-url> add a remote pointing at a relay (the URL must be\n ws://, wss://, http://, or https://)\n remove <name> remove a remote\n list list remote names + URLs (the default subcommand)\n\nOptions:\n --json machine-readable envelope (all subcommands)\n -h, --help show this help`;\n\n/** Deps subset `rig remote` needs (free — no publisher, no identity). */\nexport interface RemoteDeps {\n io: CliIo;\n cwd: string;\n}\n\n/** Run `rig remote …`; returns the process exit code. */\nexport async function runRemote(\n args: string[],\n deps: RemoteDeps\n): Promise<number> {\n const { io } = deps;\n\n let sub: string | undefined;\n let rest: string[];\n let json: boolean;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: true,\n });\n if (values.help) {\n io.out(REMOTE_USAGE);\n return 0;\n }\n json = values.json ?? false;\n [sub, ...rest] = positionals;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(REMOTE_USAGE);\n return 2;\n }\n\n // Argument-shape validation (exit 2) before touching the repository.\n switch (sub) {\n case undefined:\n case 'list':\n if (rest.length > 0) {\n io.err(`rig remote list takes no arguments (got ${rest.join(' ')})`);\n io.err(REMOTE_USAGE);\n return 2;\n }\n break;\n case 'add': {\n if (rest.length !== 2) {\n io.err('usage: rig remote add <name> <relay-url>');\n io.err(REMOTE_USAGE);\n return 2;\n }\n const url = rest[1] as string;\n if (!isRelayUrl(url)) {\n io.err(\n `cannot add remote: ${JSON.stringify(url)} is not a relay URL — ` +\n 'relays are ws://, wss://, http://, or https://'\n );\n return 2;\n }\n break;\n }\n case 'remove':\n if (rest.length !== 1) {\n io.err('usage: rig remote remove <name>');\n io.err(REMOTE_USAGE);\n return 2;\n }\n break;\n default:\n io.err(`unknown rig remote subcommand: ${sub}`);\n io.err(REMOTE_USAGE);\n return 2;\n }\n\n try {\n let repoRoot: string;\n try {\n repoRoot = await resolveRepoRoot(deps.cwd);\n } catch {\n throw new NotAGitRepositoryError(deps.cwd);\n }\n\n switch (sub) {\n case undefined:\n case 'list': {\n const remotes = await listGitRemotes(repoRoot);\n if (json) {\n io.emitJson({ command: 'remote', remotes });\n return 0;\n }\n if (remotes.length === 0) {\n io.out(\n 'no remotes configured — add one: rig remote add origin <relay-url>'\n );\n return 0;\n }\n for (const remote of remotes) {\n for (const url of remote.urls) {\n io.out(\n `${remote.name}\\t${url}` +\n (isRelayUrl(url) ? '' : '\\t(not a relay URL — ignored by rig)')\n );\n }\n if (remote.urls.length > 1) {\n io.err(\n `warning: remote \"${remote.name}\" has ${remote.urls.length} ` +\n 'URLs — rig supports one relay URL per remote (fix with ' +\n `\\`git remote set-url ${remote.name} <relay-url>\\`)`\n );\n }\n }\n return 0;\n }\n\n case 'add': {\n const [name, url] = rest as [string, string];\n const existing = await getGitRemoteUrls(repoRoot, name);\n if (existing.length > 0) {\n const detail =\n `remote ${JSON.stringify(name)} already exists ` +\n `(${existing.join(', ')}) — nothing changed. Point it ` +\n `somewhere else with \\`git remote set-url ${name} <relay-url>\\`, ` +\n `or \\`rig remote remove ${name}\\` first.`;\n if (json) {\n io.emitJson({\n command: 'remote',\n error: 'remote_exists',\n detail,\n remote: name,\n urls: existing,\n });\n }\n io.err(detail);\n return 1;\n }\n await addGitRemote(repoRoot, name, url);\n if (!json) io.out(`Added remote ${name} → ${url}`);\n if (name === 'origin') {\n if (!json) {\n io.out(\n '`rig push` and the event commands now publish here by default.'\n );\n }\n const toonConfig = await readToonConfig(repoRoot);\n if (toonConfig.relays.length > 0) {\n io.err(\n `note: git config toon.relay (${toonConfig.relays.join(', ')}) ` +\n 'is deprecated and now shadowed by the origin remote — drop ' +\n 'it with `git config --unset-all toon.relay` (the key is ' +\n 'removed in v0.3).'\n );\n }\n }\n if (json) {\n io.emitJson({ command: 'remote', action: 'add', name, url });\n }\n return 0;\n }\n\n case 'remove': {\n const name = rest[0] as string;\n const existing = await getGitRemoteUrls(repoRoot, name);\n if (existing.length === 0) {\n const detail =\n `no remote named ${JSON.stringify(name)} — ` +\n '`rig remote list` shows configured remotes.';\n if (json) {\n io.emitJson({\n command: 'remote',\n error: 'unknown_remote',\n detail,\n remote: name,\n });\n }\n io.err(detail);\n return 1;\n }\n await removeGitRemote(repoRoot, name);\n if (json) {\n io.emitJson({ command: 'remote', action: 'remove', name });\n } else {\n io.out(`Removed remote ${name}`);\n }\n return 0;\n }\n\n /* v8 ignore next 2 -- unreachable: validated above */\n default:\n return 2;\n }\n } catch (err) {\n return emitCliError(io, json, 'remote', err);\n }\n}\n","/**\n * `rig channel` — the payment channels paid rig commands hold (#262), plus\n * the explicit money lifecycle (#263): open / close / settle.\n *\n * Paid commands open a channel lazily on first use and RECORD it in the\n * peer→channel map under `TOON_CLIENT_HOME` (default `~/.toon-client`,\n * `rig-channels.json`), so later invocations resume the same channel instead\n * of opening (and funding) a new one per run. `rig channel list` reads that\n * map plus the client's nonce-watermark store (`channels.json`) and shows\n * current holdings — a FREE command: local files only, no client start, no\n * network, no payment (and therefore no `@toon-protocol/client` import).\n *\n * The lifecycle subcommands are ON-CHAIN wallet operations (gas + collateral\n * movement, not relay claims), so they follow the push confirm idiom: print\n * what will happen, then require `--yes` (mandatory in a non-TTY session) or\n * an interactive y/N confirm; `--json` without `--yes` is a pure plan.\n *\n * open the SAME resume-or-open path lazy paid writes use (factored, not\n * forked): resumes the recorded channel when one is live, else\n * opens + records a fresh one; `--deposit` adds collateral on top.\n * close starts the settlement challenge window for a recorded channel —\n * the channel stops paying immediately; collateral is released by\n * `settle` once the window elapses.\n * settle releases the remaining collateral after the challenge window\n * (the client refuses a too-early settle BEFORE spending gas).\n *\n * close/settle recover deposits stranded by pre-#262 one-channel-per-run\n * behaviour: any channel present in the map can be driven to settled.\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n channelStatus,\n ChannelMapStore,\n resolveChannelPaths,\n type ChannelMapRecord,\n type WatermarkEntry,\n} from '../standalone/channel-map.js';\nimport { emitCliError } from './errors.js';\nimport {\n defaultLoadStandalone,\n identityReport,\n type CliIo,\n type IdentityReport,\n type PushDeps,\n} from './push.js';\nimport { renderIdentityLine } from './render.js';\nimport type { StandaloneContext } from './standalone-context.js';\nimport type { StandaloneMoneyOps } from '../standalone/money.js';\n\nexport const CHANNEL_USAGE = `Usage: rig channel <subcommand>\n\nManage the payment channels paid rig commands hold with relay/store peers.\nPaid commands open a channel lazily on first use and record it under\nTOON_CLIENT_HOME (default ~/.toon-client, rig-channels.json), so later\ninvocations resume the same channel instead of opening a new one per run.\n\nSubcommands:\n list [--json] show recorded channels — peer, chain, channel id, deposit,\n cumulative claimed, status. Free: reads local state only.\n\n open [--peer <ilp-destination>] [--deposit <base-units>]\n explicitly open the payment channel for a peer — the SAME\n path paid commands use lazily: resumes the recorded live\n channel if one exists (no on-chain spend), else opens and\n records a fresh one (locks the peer-negotiated initial\n deposit on-chain). --peer is the ILP destination to anchor\n to (default: the configured destination, e.g. the devnet\n apex); --deposit adds that much extra collateral after the\n open/resume. On-chain: asks for confirmation (--yes skips).\n\n close <channelId>\n close a recorded channel — an on-chain tx that starts the\n settlement challenge window (the peer's settlementTimeout).\n The channel stops paying immediately; the remaining\n collateral stays locked until \\`rig channel settle\\` after\n the window elapses. Asks for confirmation (--yes skips).\n\n settle <channelId>\n settle a closed channel once its challenge window elapsed —\n an on-chain tx that releases the remaining collateral back\n to your wallet. Refused (without spending gas) while the\n window is still open. Asks for confirmation (--yes skips).\n\nCommon options: --json (machine-readable envelopes; without --yes lifecycle\ncommands emit a pure plan and execute nothing), --yes, -h/--help.`;\n\n/**\n * What `rig channel` needs from the command environment — the shared paid\n * command deps (io/env/cwd + injectable standalone loader): `list` uses only\n * io/env, the lifecycle subcommands load the standalone context.\n */\nexport type ChannelDeps = PushDeps;\n\n/** One channel in the `--json` envelope (unknowns are null, bigints strings). */\ninterface ChannelJson {\n channelId: string;\n peerId: string;\n identity: string;\n destination: string;\n chain: string;\n tokenNetwork: string;\n depositTotal: string | null;\n cumulativeClaimed: string | null;\n nonce: number | null;\n status: 'open' | 'closing' | 'settleable' | 'settled';\n openedAt: string;\n lastUsedAt: string;\n}\n\n/** Route one `rig channel …` invocation; returns the exit code. */\nexport async function runChannel(\n args: string[],\n deps: ChannelDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n switch (sub) {\n case 'list':\n return runChannelList(rest, deps);\n case 'open':\n return runChannelOpen(rest, deps);\n case 'close':\n return runChannelWithdrawStep(rest, deps, 'close');\n case 'settle':\n return runChannelWithdrawStep(rest, deps, 'settle');\n case 'help':\n case '--help':\n case '-h':\n io.out(CHANNEL_USAGE);\n return 0;\n case undefined:\n io.err(CHANNEL_USAGE);\n return 2;\n default:\n io.err(`rig channel: unknown subcommand ${JSON.stringify(sub)}`);\n io.err(CHANNEL_USAGE);\n return 2;\n }\n}\n\n// ---------------------------------------------------------------------------\n// list (#262)\n// ---------------------------------------------------------------------------\n\nfunction runChannelList(args: string[], deps: ChannelDeps): number {\n const { io, env } = deps;\n let json = false;\n try {\n const { values } = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (values.help) {\n io.out(CHANNEL_USAGE);\n return 0;\n }\n json = values.json ?? false;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CHANNEL_USAGE);\n return 2;\n }\n\n try {\n const paths = resolveChannelPaths(env);\n const store = new ChannelMapStore(paths);\n const records = store.list();\n const rows = records.map((record) => describeChannel(record, store));\n\n if (json) {\n io.emitJson({ command: 'channel list', channels: rows });\n return 0;\n }\n if (rows.length === 0) {\n io.out(\n 'No payment channels recorded — paid rig commands (push, issue, ' +\n 'comment, pr) record the channel they open on first use, and ' +\n '`rig channel open` records an explicit one.'\n );\n return 0;\n }\n io.out(\n `${rows.length} payment channel${rows.length === 1 ? '' : 's'} ` +\n `recorded in ${paths.mapPath}:`\n );\n for (const row of rows) {\n io.out('');\n for (const line of renderChannel(row)) io.out(line);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'channel list', err);\n }\n}\n\n/** Join one map record with its watermark state. */\nfunction describeChannel(\n record: ChannelMapRecord,\n store: ChannelMapStore\n): ChannelJson {\n const watermark: WatermarkEntry | undefined = store.readWatermark(\n record.channelId\n );\n return {\n channelId: record.channelId,\n peerId: record.peerId,\n identity: record.identity,\n destination: record.destination,\n chain: record.chain,\n tokenNetwork: record.tokenNetwork,\n depositTotal: record.depositTotal ?? null,\n cumulativeClaimed: watermark?.cumulativeAmount ?? null,\n nonce: watermark?.nonce ?? null,\n status: channelStatus(watermark),\n openedAt: record.openedAt,\n lastUsedAt: record.lastUsedAt,\n };\n}\n\nfunction renderChannel(row: ChannelJson): string[] {\n const claimed =\n row.cumulativeClaimed === null\n ? 'unknown (no local claim state)'\n : `${row.cumulativeClaimed} base units (nonce ${row.nonce})`;\n return [\n `channel ${row.channelId} [${row.status}]`,\n ` peer ${row.destination} (${row.peerId})`,\n ` identity ${row.identity.slice(0, 8)}…`,\n ` chain ${row.chain}` +\n (row.tokenNetwork ? ` token-network ${row.tokenNetwork}` : ''),\n ` deposited ${row.depositTotal ?? 'unrecorded'}` +\n (row.depositTotal ? ' base units' : ''),\n ` claimed ${claimed}`,\n ` opened ${row.openedAt} (last used ${row.lastUsedAt})`,\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Shared money-command plumbing (#263)\n// ---------------------------------------------------------------------------\n\n/** Load the standalone context and require its money-ops surface. */\nasync function loadMoneyContext(\n deps: ChannelDeps,\n options?: { channelDestination?: string }\n): Promise<{ ctx: StandaloneContext; money: StandaloneMoneyOps }> {\n const ctx = await (deps.loadStandalone ?? defaultLoadStandalone)({\n env: deps.env,\n cwd: deps.cwd,\n warn: (line) => deps.io.err(line),\n ...(options?.channelDestination\n ? { channelDestination: options.channelDestination }\n : {}),\n });\n const money = ctx.money;\n if (!money) {\n await ctx.stop().catch(() => undefined);\n throw new Error(\n 'this standalone loader does not expose money operations — ' +\n 'channel open/close/settle need a loader with the money lifecycle'\n );\n }\n return { ctx, money };\n}\n\n/**\n * The push-idiom confirm gate for an ON-CHAIN money operation. Returns the\n * exit code to bail out with, or undefined to proceed. In `--json` mode\n * without `--yes` the caller emits its plan envelope (exit 0) — this gate\n * signals that with `'json-plan'`.\n */\nasync function confirmOnChain(\n io: CliIo,\n flags: { yes: boolean; json: boolean },\n question: string\n): Promise<'proceed' | 'json-plan' | number> {\n if (flags.yes) return 'proceed';\n if (flags.json) return 'json-plan';\n if (!io.isInteractive) {\n io.err(\n 'refusing to move on-chain funds without confirmation in a ' +\n 'non-interactive session — re-run with --yes (or use --json for a plan)'\n );\n return 1;\n }\n const proceed = await io.confirm(question);\n if (proceed) return 'proceed';\n io.err('aborted — no on-chain transaction was sent.');\n return 1;\n}\n\n/** Format a string-encoded unix-seconds timestamp for humans. */\nfunction formatUnixSeconds(value: string): string {\n const ms = Number(value) * 1000;\n return Number.isFinite(ms) ? new Date(ms).toISOString() : `t=${value}s`;\n}\n\n/** Whole seconds from now until a string-encoded unix-seconds timestamp. */\nfunction secondsUntil(value: string, nowSec: number): number {\n return Number(value) - nowSec;\n}\n\n// ---------------------------------------------------------------------------\n// open\n// ---------------------------------------------------------------------------\n\ninterface ChannelOpenJson {\n command: 'channel open';\n identity: IdentityReport;\n executed: boolean;\n plan: { destination: string | null; deposit: string | null };\n result?: {\n channelId: string;\n resumed: boolean;\n destination: string;\n chain: string | null;\n peerId: string | null;\n depositTotal: string | null;\n depositAdded: string | null;\n depositTxHash: string | null;\n };\n hint?: string;\n}\n\nasync function runChannelOpen(\n args: string[],\n deps: ChannelDeps\n): Promise<number> {\n const { io } = deps;\n let peer: string | undefined;\n let deposit: bigint | undefined;\n let yes = false;\n let json = false;\n try {\n const { values } = parseArgs({\n args,\n options: {\n peer: { type: 'string' },\n deposit: { type: 'string' },\n yes: { type: 'boolean', default: false },\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (values.help) {\n io.out(CHANNEL_USAGE);\n return 0;\n }\n peer = values.peer;\n yes = values.yes ?? false;\n json = values.json ?? false;\n if (values.deposit !== undefined) {\n if (!/^\\d+$/.test(values.deposit) || BigInt(values.deposit) <= 0n) {\n throw new Error(\n `--deposit must be a positive base-unit integer, got ${JSON.stringify(values.deposit)}`\n );\n }\n deposit = BigInt(values.deposit);\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CHANNEL_USAGE);\n return 2;\n }\n\n let ctx: StandaloneContext | undefined;\n try {\n const loaded = await loadMoneyContext(deps, {\n ...(peer ? { channelDestination: peer } : {}),\n });\n ctx = loaded.ctx;\n const identity = identityReport(ctx);\n const plan = {\n destination: peer ?? null,\n deposit: deposit?.toString() ?? null,\n };\n\n if (!json) {\n io.out('Channel open plan:');\n io.out(` peer (ILP) ${peer ?? '(configured default destination)'}`);\n io.out(\n ` deposit ${deposit !== undefined ? `+${deposit} base units of extra collateral after the open/resume` : 'none beyond the peer-negotiated initial deposit'}`\n );\n io.out(renderIdentityLine(identity));\n io.out(\n 'If a live channel is already recorded for this peer it is RESUMED ' +\n '(no on-chain spend); otherwise an on-chain channel open locks the ' +\n 'peer-negotiated initial deposit from your wallet (plus gas).'\n );\n }\n\n const gate = await confirmOnChain(\n io,\n { yes, json },\n 'Proceed with on-chain channel open? [y/N] '\n );\n if (gate === 'json-plan') {\n io.emitJson({\n command: 'channel open',\n identity,\n executed: false,\n plan,\n hint: 'plan only — re-run with --yes to open (on-chain: locks collateral and spends gas)',\n } satisfies ChannelOpenJson);\n return 0;\n }\n if (gate !== 'proceed') return gate;\n\n const outcome = await loaded.money.openChannel(\n deposit !== undefined ? { deposit } : undefined\n );\n\n if (json) {\n io.emitJson({\n command: 'channel open',\n identity,\n executed: true,\n plan,\n result: {\n channelId: outcome.channelId,\n resumed: outcome.resumed,\n destination: outcome.destination,\n chain: outcome.chain ?? null,\n peerId: outcome.peerId ?? null,\n depositTotal: outcome.depositTotal ?? null,\n depositAdded: outcome.depositAdded ?? null,\n depositTxHash: outcome.depositTxHash ?? null,\n },\n } satisfies ChannelOpenJson);\n return 0;\n }\n io.out(\n outcome.resumed\n ? `Resumed recorded channel ${outcome.channelId} — no on-chain open was needed.`\n : `Opened channel ${outcome.channelId}${outcome.chain ? ` on ${outcome.chain}` : ''} and recorded it for reuse.`\n );\n io.out(` peer ${outcome.destination}${outcome.peerId ? ` (${outcome.peerId})` : ''}`);\n if (outcome.depositAdded) {\n io.out(\n ` deposited +${outcome.depositAdded} base units` +\n (outcome.depositTxHash ? ` (tx ${outcome.depositTxHash})` : '')\n );\n }\n if (outcome.depositTotal) {\n io.out(` collateral ${outcome.depositTotal} base units total on-chain`);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'channel open', err);\n } finally {\n await stopQuietly(ctx);\n }\n}\n\n// ---------------------------------------------------------------------------\n// close / settle (the two halves of withdraw)\n// ---------------------------------------------------------------------------\n\ninterface WithdrawJson {\n command: 'channel close' | 'channel settle';\n identity: IdentityReport;\n executed: boolean;\n channelId: string;\n result?: {\n txHash: string | null;\n closedAt?: string;\n settleableAt?: string;\n };\n hint?: string;\n}\n\n/**\n * Fail-fast local pre-checks from the recorded watermark timers — before any\n * identity resolution or client start (chain state stays authoritative: the\n * client re-checks before spending gas).\n */\nfunction withdrawPrecheck(\n step: 'close' | 'settle',\n channelId: string,\n watermark: WatermarkEntry | undefined,\n nowSec: number\n): string | undefined {\n const status = channelStatus(watermark, nowSec);\n if (status === 'settled') {\n return `channel ${channelId} is already settled — nothing left to ${step}.`;\n }\n if (step === 'close') {\n if (status === 'closing' || status === 'settleable') {\n const at = watermark?.settleableAt;\n return (\n `channel ${channelId} is already closing — ` +\n (status === 'settleable'\n ? 'its challenge window has elapsed; run `rig channel settle` to release the collateral.'\n : `settleable at ${at ? formatUnixSeconds(at) : 'the end of its challenge window'} (run \\`rig channel settle\\` then).`)\n );\n }\n return undefined;\n }\n // settle\n if (status === 'open') {\n return (\n `channel ${channelId} is not closed — run \\`rig channel close ${channelId}\\` ` +\n 'first (settle only releases collateral after the challenge window of a closed channel).'\n );\n }\n if (status === 'closing' && watermark?.settleableAt !== undefined) {\n const remain = secondsUntil(watermark.settleableAt, nowSec);\n return (\n `channel ${channelId} is not settleable yet — the challenge window is ` +\n `still open (${remain}s remain, settleable at ${formatUnixSeconds(watermark.settleableAt)}). ` +\n 'Nothing was spent; re-run after that time.'\n );\n }\n return undefined;\n}\n\nasync function runChannelWithdrawStep(\n args: string[],\n deps: ChannelDeps,\n step: 'close' | 'settle'\n): Promise<number> {\n const { io, env } = deps;\n const command = `channel ${step}` as WithdrawJson['command'];\n let channelId: string | undefined;\n let yes = false;\n let json = false;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: {\n yes: { type: 'boolean', default: false },\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: true,\n });\n if (values.help) {\n io.out(CHANNEL_USAGE);\n return 0;\n }\n yes = values.yes ?? false;\n json = values.json ?? false;\n if (positionals.length !== 1) {\n throw new Error(\n `rig channel ${step} takes exactly one <channelId> (got ${positionals.length}) — \\`rig channel list\\` shows recorded channels`\n );\n }\n channelId = positionals[0] as string;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CHANNEL_USAGE);\n return 2;\n }\n\n let ctx: StandaloneContext | undefined;\n try {\n // ── Local state: the recorded channel + its watermark (free, fail-fast) ──\n const store = new ChannelMapStore(resolveChannelPaths(env));\n const record = store.list().find((r) => r.channelId === channelId);\n if (!record) {\n throw new Error(\n `no recorded channel ${JSON.stringify(channelId)} — \\`rig channel list\\` shows the channels this identity holds`\n );\n }\n const watermark = store.readWatermark(channelId);\n const nowSec = Math.floor(Date.now() / 1000);\n const refusal = withdrawPrecheck(step, channelId, watermark, nowSec);\n if (refusal) throw new Error(refusal);\n\n // ── Identity (must match the channel's opener — its claims/keys) ────────\n const loaded = await loadMoneyContext(deps);\n ctx = loaded.ctx;\n const identity = identityReport(ctx);\n if (record.identity !== identity.pubkey) {\n throw new Error(\n `channel ${channelId} was opened by identity ${record.identity.slice(0, 8)}… ` +\n `but the active identity is ${identity.pubkey.slice(0, 8)}… ` +\n `(from ${identity.sourceLabel}) — on-chain ${step} must be signed by ` +\n \"the opener's wallet key. Switch RIG_MNEMONIC (or the keystore) to that identity.\"\n );\n }\n\n // ── Plan + confirm gate ──────────────────────────────────────────────────\n if (!json) {\n const claimed = watermark?.cumulativeAmount;\n io.out(`Channel ${step} plan:`);\n io.out(` channel ${channelId} [${channelStatus(watermark, nowSec)}]`);\n io.out(` peer ${record.destination} (${record.peerId})`);\n io.out(` chain ${record.chain}`);\n io.out(\n ` deposited ${record.depositTotal ?? 'unrecorded'}` +\n (claimed !== undefined ? ` claimed ${claimed} base units` : '')\n );\n io.out(renderIdentityLine(identity));\n if (step === 'close') {\n io.out(\n 'Closing is an ON-CHAIN transaction (gas) that starts the settlement ' +\n 'challenge window: the channel stops paying immediately, and the ' +\n 'remaining collateral stays locked until `rig channel settle` ' +\n 'succeeds after the window elapses.'\n );\n } else {\n io.out(\n 'Settling is an ON-CHAIN transaction (gas) that releases the ' +\n \"remaining collateral back to your wallet. The chain's challenge \" +\n 'window is authoritative — a too-early settle is refused before ' +\n 'any gas is spent.'\n );\n }\n }\n const gate = await confirmOnChain(\n io,\n { yes, json },\n `Proceed with on-chain channel ${step}? [y/N] `\n );\n if (gate === 'json-plan') {\n io.emitJson({\n command,\n identity,\n executed: false,\n channelId,\n hint: `plan only — re-run with --yes to ${step} (on-chain transaction)`,\n } satisfies WithdrawJson);\n return 0;\n }\n if (gate !== 'proceed') return gate;\n\n // ── Execute ──────────────────────────────────────────────────────────────\n if (step === 'close') {\n const result = await loaded.money.closeChannel(record);\n if (json) {\n io.emitJson({\n command,\n identity,\n executed: true,\n channelId,\n result: {\n txHash: result.txHash ?? null,\n closedAt: result.closedAt,\n settleableAt: result.settleableAt,\n },\n } satisfies WithdrawJson);\n return 0;\n }\n io.out(\n `Channel ${channelId} is closing` +\n (result.txHash ? ` (tx ${result.txHash})` : '') +\n '.'\n );\n io.out(\n ` challenge window: settleable at ${formatUnixSeconds(result.settleableAt)} ` +\n `(~${Math.max(0, secondsUntil(result.settleableAt, nowSec))}s from now)`\n );\n io.out(\n ` run \\`rig channel settle ${channelId}\\` after that time to release the collateral.`\n );\n return 0;\n }\n\n const result = await loaded.money.settleChannel(record);\n if (json) {\n io.emitJson({\n command,\n identity,\n executed: true,\n channelId,\n result: { txHash: result.txHash ?? null },\n } satisfies WithdrawJson);\n return 0;\n }\n io.out(\n `Channel ${channelId} settled` +\n (result.txHash ? ` (tx ${result.txHash})` : '') +\n ' — the remaining collateral was released to your wallet.'\n );\n return 0;\n } catch (err) {\n return emitCliError(io, json, command, err);\n } finally {\n await stopQuietly(ctx);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Small shared helpers\n// ---------------------------------------------------------------------------\n\nasync function stopQuietly(ctx: StandaloneContext | undefined): Promise<void> {\n if (!ctx) return;\n try {\n await ctx.stop();\n } catch {\n // best-effort teardown\n }\n}\n","/**\n * `rig clone` (#278) — bootstrap a repository from TOON, no payments anywhere:\n *\n * rig clone <relay-url> <owner-npub-or-hex>/<repo-id> [dir]\n *\n * Pipeline: fetch kind:30617/30618 from the relay (../remote-state.ts) →\n * download every object the refs need from Arweave gateways with SHA-1\n * verification (../read-pipeline.ts) → materialize a REAL git repository via\n * git plumbing (../materialize.ts): `git hash-object -w --stdin -t <type>`\n * per object (written SHA re-checked), `git update-ref` per ref, HEAD from\n * the 30618 symref, worktree checkout. The clone is immediately push/pull\n * capable: toon.repoid/toon.owner are configured and the relay is added as\n * the `origin` remote.\n *\n * ATOMICITY: everything lands in a temp dir next to the destination and is\n * renamed into place only on full success — a failed clone never leaves a\n * partial/corrupt repository. Missing objects (Arweave propagation lag) are\n * an honest error listing the SHAs; corrupt objects are an integrity error.\n */\n\nimport { mkdtemp, mkdir, readdir, rename, rm, rmdir } from 'node:fs/promises';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport { parseArgs } from 'node:util';\nimport {\n setHeadSymref,\n isSafeRefname,\n runGit,\n updateRef,\n writeGitObjects,\n} from '../materialize.js';\nimport { npubToHex, ownerToHex } from '../npub.js';\nimport {\n collectRepoObjects,\n missingObjectsMessage,\n type MissingObject,\n} from '../read-pipeline.js';\nimport { fetchRemoteState, type RemoteState } from '../remote-state.js';\nimport { emitCliError } from './errors.js';\nimport type { ReadCommandDeps } from './read-seams.js';\n\nexport const CLONE_USAGE = `Usage: rig clone <relay-url> <owner>/<repo-id> [dir] [options]\n\nClone a TOON repository — FREE (relay reads + Arweave gateway downloads; no\npayments, no channel, no identity needed). <relay-url> is a ws:// or wss://\nNIP-01 relay; <owner> is the repo owner's pubkey as npub1… or 64-char hex;\n[dir] defaults to <repo-id>.\n\nFetches the kind:30617/30618 repository state, downloads every git object\nthe refs need from Arweave gateways (SHA-1 verified — corrupt content is\nrejected), and materializes a real git repository: objects via git plumbing,\nrefs, HEAD, checked-out worktree, toon.* config, and the relay preconfigured\nas the \"origin\" remote — so \\`rig fetch\\`, \\`rig push\\`, and the issue/pr\ncommands work immediately.\n\nNote: recently pushed objects can take 10-20 minutes to become fetchable\nfrom Arweave gateways. A clone right after a push may report missing\nobjects — retry after propagation.\n\nOptions:\n --concurrency <n> parallel gateway downloads (default 8)\n --json machine-readable result envelope\n -h, --help show this help`;\n\n/** Repo has no announcement AND no state on the relay. */\nexport class RepoNotFoundError extends Error {\n constructor(relay: string, owner: string, repoId: string) {\n super(\n `repository 30617:${owner}:${repoId} not found on ${relay} — ` +\n 'no kind:30617 announcement or kind:30618 state event exists there. ' +\n 'Check the relay URL, the owner pubkey (npub or hex), and the repo id.'\n );\n this.name = 'RepoNotFoundError';\n }\n}\n\n/** Reachable objects could not be downloaded (Arweave propagation lag). */\nexport class MissingRemoteObjectsError extends Error {\n constructor(\n public readonly missing: MissingObject[],\n context: string\n ) {\n super(missingObjectsMessage(missing, context));\n this.name = 'MissingRemoteObjectsError';\n }\n}\n\nconst WS_URL_RE = /^wss?:\\/\\//i;\n\ninterface CloneArgs {\n relayUrl: string;\n owner: string;\n repoId: string;\n dir: string | undefined;\n concurrency: number | undefined;\n json: boolean;\n}\n\nfunction parseCloneArgs(args: string[]): CloneArgs | { help: true } {\n const { values, positionals } = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n concurrency: { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: true,\n });\n if (values.help) return { help: true };\n if (positionals.length < 2 || positionals.length > 3) {\n throw new Error('expected: rig clone <relay-url> <owner>/<repo-id> [dir]');\n }\n const [relayUrl, addr, dir] = positionals as [string, string, string?];\n if (!WS_URL_RE.test(relayUrl)) {\n throw new Error(\n `<relay-url> must be ws:// or wss:// (got ${JSON.stringify(relayUrl)})`\n );\n }\n const slash = addr.indexOf('/');\n if (slash <= 0 || slash === addr.length - 1) {\n throw new Error(\n `expected <owner>/<repo-id> (npub or 64-char hex owner), got ${JSON.stringify(addr)}`\n );\n }\n const owner = ownerToHex(addr.slice(0, slash));\n const repoId = addr.slice(slash + 1);\n let concurrency: number | undefined;\n if (values.concurrency !== undefined) {\n concurrency = Number.parseInt(values.concurrency, 10);\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) {\n throw new Error(`--concurrency must be a positive integer`);\n }\n }\n return {\n relayUrl,\n owner,\n repoId,\n dir,\n concurrency,\n json: values.json === true,\n };\n}\n\n/** True when `dir` does not exist or is an empty directory. */\nasync function isUsableDestination(dir: string): Promise<boolean> {\n try {\n const entries = await readdir(dir);\n return entries.length === 0;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'ENOENT';\n }\n}\n\n/** Pick the branch `git init --initial-branch` should use. */\nfunction initialBranch(headSymref: string | null): string {\n if (headSymref?.startsWith('refs/heads/')) {\n const name = headSymref.slice('refs/heads/'.length);\n if (name && isSafeRefname(headSymref)) return name;\n }\n return 'main';\n}\n\n/** Run `rig clone …`; returns the process exit code. */\nexport async function runClone(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let parsed: CloneArgs;\n try {\n const result = parseCloneArgs(args);\n if ('help' in result) {\n io.out(CLONE_USAGE);\n return 0;\n }\n parsed = result;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CLONE_USAGE);\n return 2;\n }\n\n const { relayUrl, owner, repoId, json } = parsed;\n const dest = resolve(deps.cwd, parsed.dir ?? repoId);\n let tempDir: string | undefined;\n\n try {\n if (!(await isUsableDestination(dest))) {\n throw new Error(\n `destination path ${JSON.stringify(dest)} already exists and is not an empty directory`\n );\n }\n\n if (!json) io.out(`Cloning into '${basename(dest)}'...`);\n\n // ── Remote state (kind:30617 + 30618) ───────────────────────────────────\n const remoteState: RemoteState = await fetchRemoteState({\n relayUrls: [relayUrl],\n ownerPubkey: owner,\n repoId,\n ...(deps.webSocketFactory\n ? { webSocketFactory: deps.webSocketFactory }\n : {}),\n ...(deps.resolveSha ? { resolveSha: deps.resolveSha } : {}),\n });\n if (!remoteState.announced && remoteState.refsEvent === null) {\n throw new RepoNotFoundError(relayUrl, owner, repoId);\n }\n\n // Refs from the 30618, filtered through the hostile-relay refname gate.\n const refs = new Map<string, string>();\n for (const [refname, sha] of remoteState.refs) {\n if (!isSafeRefname(refname)) {\n io.err(\n `warning: skipping unsafe ref name from relay: ${JSON.stringify(refname)}`\n );\n continue;\n }\n refs.set(refname, sha);\n }\n if (refs.size === 0) {\n io.err(\n 'warning: the repository has no refs yet (announced but never pushed) — ' +\n 'cloning an empty repository'\n );\n }\n\n // ── Download + verify the object closure (FREE) ─────────────────────────\n const tips = [...new Set(refs.values())];\n const collected = await collectRepoObjects({\n tips,\n shaToTxId: remoteState.shaToTxId,\n resolveMissing: (shas) => remoteState.resolveMissing(shas),\n ...(deps.fetchFn ? { fetchFn: deps.fetchFn } : {}),\n ...(parsed.concurrency !== undefined\n ? { concurrency: parsed.concurrency }\n : {}),\n });\n if (collected.missing.length > 0) {\n throw new MissingRemoteObjectsError(\n collected.missing,\n `cannot clone ${owner.slice(0, 8)}…/${repoId}`\n );\n }\n for (const { sha, txId } of collected.skippedUnavailable) {\n io.err(\n `warning: unreachable object ${sha} (tx ${txId}) could not be downloaded — ` +\n 'not needed by any ref, continuing'\n );\n }\n\n // ── Materialize into a temp dir, move into place on success ────────────\n const parent = dirname(dest);\n await mkdir(parent, { recursive: true });\n tempDir = await mkdtemp(join(parent, `.${basename(dest)}.rig-clone-`));\n\n await runGit(tempDir, [\n 'init',\n '--quiet',\n `--initial-branch=${initialBranch(remoteState.headSymref)}`,\n ]);\n const written = await writeGitObjects(tempDir, collected.objects.values());\n for (const [refname, sha] of refs) {\n await updateRef(tempDir, refname, sha);\n // Remote-tracking refs, exactly like `git clone` — so `rig fetch`\n // reports honest deltas and `rig merge origin/<branch>` works.\n if (refname.startsWith('refs/heads/')) {\n const branch = refname.slice('refs/heads/'.length);\n await updateRef(tempDir, `refs/remotes/origin/${branch}`, sha);\n }\n }\n const head =\n remoteState.headSymref !== null &&\n isSafeRefname(remoteState.headSymref) &&\n refs.has(remoteState.headSymref)\n ? remoteState.headSymref\n : ([...refs.keys()].find((r) => r.startsWith('refs/heads/')) ?? null);\n if (head !== null) {\n await setHeadSymref(tempDir, head);\n await runGit(tempDir, ['reset', '--hard', '--quiet']);\n }\n\n // toon.* config + origin remote: immediately push/pull-capable.\n await runGit(tempDir, ['config', 'toon.repoid', repoId]);\n await runGit(tempDir, ['config', 'toon.owner', owner]);\n await runGit(tempDir, ['remote', 'add', 'origin', relayUrl]);\n if (head !== null) {\n // Upstream config for the checked-out branch, like `git clone`.\n const branch = head.slice('refs/heads/'.length);\n await runGit(tempDir, ['config', `branch.${branch}.remote`, 'origin']);\n await runGit(tempDir, ['config', `branch.${branch}.merge`, head]);\n }\n\n // Atomic move into place (destination may exist as an empty directory).\n try {\n await rmdir(dest);\n } catch {\n // ENOENT — the destination does not exist yet; rename creates it.\n }\n await rename(tempDir, dest);\n tempDir = undefined;\n\n // ── Report ──────────────────────────────────────────────────────────────\n if (json) {\n io.emitJson({\n command: 'clone',\n repoAddr: { ownerPubkey: owner, repoId },\n relay: relayUrl,\n directory: dest,\n head,\n refs: Object.fromEntries(refs),\n name: remoteState.name,\n objectsDownloaded: written,\n executed: true,\n });\n } else {\n io.out(`Downloaded ${written} object(s) from Arweave (SHA-1 verified).`);\n for (const [refname, sha] of refs) {\n io.out(` ${sha.slice(0, 7)} ${refname}`);\n }\n if (head !== null) io.out(`HEAD is now at ${head}`);\n io.out(\n `Configured toon.repoid=${repoId}, toon.owner=${owner.slice(0, 8)}…, ` +\n `origin → ${relayUrl}`\n );\n io.out('Done.');\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'clone', err);\n } finally {\n if (tempDir !== undefined) {\n await rm(tempDir, { recursive: true, force: true }).catch(\n () => undefined\n );\n }\n }\n}\n\n// Re-exported for the acceptance flow + tests (owner column rendering).\nexport { npubToHex };\n","/**\n * The single-event `rig` subcommands (#231): issue / comment / pr, where\n * `pr` nests `create` and `status` (#250 moved the NIP-34 status publish\n * from top-level `rig status` to `rig pr status` — bare `rig status` now\n * passes through to `git status`).\n *\n * One shared pipeline behind four thin arg-parsers, mirroring `rig push`\n * (./push.ts) exactly: repo addressing from the `toon.*` git config keys\n * `rig init` writes (`--repo-id`/`--owner` override; actionable \"run\n * `rig init`\" error when unconfigured), a fee-quoting confirm gate (`--yes`\n * skips; a non-TTY session without it refuses; `--json` without `--yes` is a\n * pure estimate), and two transports (#279, ./daemon-session.ts):\n *\n * standalone (default + guarantee) — build the NIP-34 event locally\n * (../nip34-events.ts — the same builders the toon-clientd daemon uses)\n * and pay-to-publish through the embedded, nonce-guarded\n * StandalonePublisher;\n * daemon (automatic fast path) — when a running toon-clientd holds the\n * SAME identity, delegate to its loopback POST\n * /git/issue|comment|patch|status route instead: the daemon builds,\n * signs, and pays from its warm bootstrap, and it owns the channel\n * watermark (the safety goal the old refusal protected). NOTE: the\n * single-event daemon routes publish via the daemon's own configured\n * relay route — a resolved relay that differs from it draws a warning.\n *\n * The relay resolves like `rig push` (#249): `--remote <name>`\n * (default: the `origin` git remote), `--relay <url>` as an ad-hoc override\n * that bypasses remotes, deprecated `git config toon.relay` as a nudged\n * fallback. Publishes go to a SINGLE relay; multiple configured relays and\n * multi-URL remotes are refused before anything is paid (same guard as push).\n *\n * `rig pr create --range` runs REAL `git format-patch --stdout <range>` in\n * the local repository and publishes its output as the kind:1617 content —\n * one event for the whole series (cover-letter threading is out of scope in\n * v1; see the usage text).\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { parseArgs } from 'node:util';\nimport {\n REPOSITORY_ANNOUNCEMENT_KIND,\n STATUS_APPLIED_KIND,\n STATUS_CLOSED_KIND,\n STATUS_DRAFT_KIND,\n STATUS_OPEN_KIND,\n} from '@toon-protocol/core/nip34';\nimport {\n authorizedStatusAuthors,\n buildComment,\n buildIssue,\n buildPatch,\n buildStatus,\n type StatusKind,\n type UnsignedEvent,\n} from '../nip34-events.js';\nimport { fetchRemoteState } from '../remote-state.js';\nimport { GitRepoReader } from '../repo-reader.js';\nimport {\n serializeEventReceipt,\n type GitEventResponse,\n type GitRepoAddr,\n type GitStatusValue,\n} from '../routes.js';\nimport {\n type DaemonGitClient,\n type SessionPath,\n} from './daemon-session.js';\nimport { emitCliError, UnconfiguredRepoAddressError } from './errors.js';\nimport { readToonConfig, resolveRepoRoot, type ToonRepoConfig } from './git-config.js';\nimport {\n identityReport,\n loadPaidSession,\n type IdentityReport,\n type PushDeps,\n} from './push.js';\nimport type { ReadSeams } from './read-seams.js';\nimport { resolveRelays, singleRelayRefusal } from './remote.js';\nimport { feeLabel, renderEventPlan, renderEventReceipt } from './render.js';\nimport type { StandaloneContext } from './standalone-context.js';\nimport {\n ISSUE_LIST_USAGE,\n ISSUE_SHOW_USAGE,\n PR_LIST_USAGE,\n PR_SHOW_USAGE,\n runIssueList,\n runIssueShow,\n runPrList,\n runPrShow,\n} from './tracker.js';\n\n// ---------------------------------------------------------------------------\n// Deps\n// ---------------------------------------------------------------------------\n\n/**\n * Push deps plus a stdin reader (issue-body fallback) and the #278 read-path\n * seams (relay WebSocket / gateway fetch / SHA resolver — used by the FREE\n * `issue list|show` and `pr list|show` subcommands); tests inject all.\n */\nexport interface EventCommandDeps extends PushDeps, ReadSeams {\n /** Read all of stdin as UTF-8 (default: the real process stdin). */\n readStdin?: () => Promise<string>;\n}\n\nconst defaultReadStdin = async (): Promise<string> => {\n // Never block waiting for keyboard input (e.g. stdout piped but stdin a\n // TTY): an interactive stdin yields no body, which surfaces as the clear\n // \"body is empty\" error instead of a hang.\n if (process.stdin.isTTY) return '';\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString('utf-8');\n};\n\n// ---------------------------------------------------------------------------\n// Usage\n// ---------------------------------------------------------------------------\n\n/** Flags every single-event subcommand shares (mirrors `rig push`). */\nconst COMMON_FLAGS_USAGE = ` --repo-id <id> repository id / NIP-34 d-tag (default: git config\n toon.repoid — run \\`rig init\\` to set it)\n --owner <pubkey> repository owner pubkey, 64-char hex (default: git config\n toon.owner, then the active identity)\n --remote <name> publish via this configured git remote (default: the\n \"origin\" remote — \\`rig remote add origin <relay-url>\\`)\n --relay <url> ad-hoc relay override (exactly one) — bypasses the\n configured remotes. The deprecated v0.1 \\`git config\n toon.relay\\` still works as a fallback, with a nudge\n --yes skip the fee confirmation (required when not a TTY)\n --json machine-readable receipt; without --yes it is a pure\n estimate (nothing published, exit 0)\n -h, --help show this help`;\n\nexport const ISSUE_USAGE = `Usage: rig issue create --title <title> [options]\n\nFile an issue (kind:1621) against a TOON repo — a paid publish; writes are\npermanent and non-refundable. The repo address (30617:<owner>:<repoId>) comes\nfrom the toon.* git config keys \\`rig init\\` writes.\n\nBody source (exactly one): --body, --body-file, or piped stdin.\n\nOptions:\n --title <title> issue title (subject tag) [required]\n --body <text> issue body (Markdown)\n --body-file <path> read the issue body from a file\n --label <label> label (t tag); repeatable\n${COMMON_FLAGS_USAGE}\n\nRelated (FREE reads — no payment):\n rig issue list [--state open|closed|all] list the repo's issues\n rig issue show <event-id> one issue + its comments`;\n\nexport const COMMENT_USAGE = `Usage: rig comment <root-event-id> --body <text> [options]\n\nComment (kind:1622) on an issue or patch — a paid publish; writes are\npermanent and non-refundable. <root-event-id> is the 64-char hex id of the\nkind:1621 issue / kind:1617 patch being commented on.\n\nOptions:\n --body <text> comment body (Markdown) [required]\n --parent-author <pubkey> pubkey of the TARGET event's author (p threading\n tag; default: the repo owner)\n --marker <root|reply> e-tag marker (default: root — commenting directly\n on the issue/patch)\n${COMMON_FLAGS_USAGE}`;\n\nexport const PR_CREATE_USAGE = `Usage: rig pr create --title <title> (--range <range> | --patch-file <path>) [options]\n\nPublish a patch (kind:1617) whose content is REAL \\`git format-patch\\` output —\na paid publish; writes are permanent and non-refundable. --range runs\n\\`git format-patch --stdout <range>\\` in the local repository and derives the\ncommit/parent-commit tags; --patch-file publishes a pre-generated patch\nverbatim. A multi-commit range publishes ONE kind:1617 event carrying the\nfull series text — cover-letter threading (one event per commit) is out of\nscope in v1.\n\nThe PR body (--body/--body-file) is carried in a dedicated \\`description\\`\ntag, not in the event content — the content stays pure format-patch output so\n\\`rig pr show … | git am\\` keeps working.\n\nOptions:\n --title <title> patch/PR title (subject tag) [required]\n --range <range> revision range for format-patch: <rev>, <rev>..<rev>,\n or <rev>...<rev> (mutually exclusive with --patch-file)\n --patch-file <path> literal patch text to publish\n --body <text> PR description (Markdown; description tag)\n --body-file <path> read the PR description from a file\n --branch <name> branch name (t tag)\n${COMMON_FLAGS_USAGE}`;\n\nexport const PR_STATUS_USAGE = `Usage: rig pr status <target-event-id> <open|applied|closed|draft> [options]\n\nSet the status of an issue or patch — a paid publish; writes are permanent\nand non-refundable. Publishes kind:1630 (open), 1631 (applied), 1632\n(closed), or 1633 (draft) against the 64-char hex id of the target event,\nwith the repo a-tag attached so readers can scope a status stream to the\nrepository. (This command was \\`rig status\\` before v2 — bare \\`rig status\\`\nnow passes through to \\`git status\\`.)\n\nOptions:\n${COMMON_FLAGS_USAGE}`;\n\nexport const PR_USAGE = `${PR_CREATE_USAGE}\n\n${PR_STATUS_USAGE}\n\n${PR_LIST_USAGE}\n\n${PR_SHOW_USAGE}`;\n\n// ---------------------------------------------------------------------------\n// Shared flag parsing\n// ---------------------------------------------------------------------------\n\nconst HEX64_RE = /^[0-9a-f]{64}$/;\n\nfunction assertHex64(value: string, what: string): void {\n if (!HEX64_RE.test(value)) {\n throw new Error(\n `${what} must be a 64-char lowercase hex id (got ${JSON.stringify(value)})`\n );\n }\n}\n\n/** parseArgs options every subcommand accepts (mirrors `rig push`). */\nconst COMMON_OPTIONS = {\n yes: { type: 'boolean', default: false },\n json: { type: 'boolean', default: false },\n relay: { type: 'string', multiple: true },\n remote: { type: 'string' },\n 'repo-id': { type: 'string' },\n owner: { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n} as const;\n\ninterface CommonFlags {\n yes: boolean;\n json: boolean;\n relay: string[];\n remote?: string;\n repoId?: string;\n owner?: string;\n help: boolean;\n}\n\nfunction pickCommon(values: Record<string, unknown>): CommonFlags {\n const flags: CommonFlags = {\n yes: values['yes'] === true,\n json: values['json'] === true,\n relay: Array.isArray(values['relay']) ? (values['relay'] as string[]) : [],\n help: values['help'] === true,\n };\n const remote = values['remote'];\n if (typeof remote === 'string') flags.remote = remote;\n const repoId = values['repo-id'];\n if (typeof repoId === 'string') flags.repoId = repoId;\n const owner = values['owner'];\n if (typeof owner === 'string') {\n assertHex64(owner, '--owner');\n flags.owner = owner;\n }\n return flags;\n}\n\n// ---------------------------------------------------------------------------\n// Shared publish pipeline\n// ---------------------------------------------------------------------------\n\ntype EventCommand = 'issue' | 'comment' | 'pr' | 'pr status';\n\ninterface RunEventOptions {\n command: EventCommand;\n flags: CommonFlags;\n deps: EventCommandDeps;\n /** Human action label WITHOUT the kind, e.g. `issue \"Fix the flux\"`. */\n actionLabel: string;\n /**\n * Build the unsigned NIP-34 event for the resolved repo address — the\n * publish payload, and the source of truth for the kind. May do real work\n * (pr runs format-patch here), so failures land in the normal error path.\n * ALWAYS called (both paths) — the kind drives rendering, and the daemon\n * path reuses locally-derived values (e.g. the format-patch output).\n */\n buildEvent: (addr: GitRepoAddr) => Promise<UnsignedEvent>;\n /**\n * Drive the matching daemon `/git/*` route (#279 delegated fast path).\n * Called only after the same-identity check and the confirm gate.\n */\n sendDaemon: (\n client: DaemonGitClient,\n addr: GitRepoAddr\n ) => Promise<GitEventResponse>;\n /**\n * Optional pre-confirm hook (#287): runs AFTER the identity + repo address\n * are resolved and the event is built, but BEFORE the plan is rendered and\n * the confirm gate. Used by `pr status` to WARN when the active identity is\n * not an authorized maintainer of the target repo (the write is still\n * allowed — the relay is permissionless — but clients honoring repo\n * authority will ignore it). Failures here must be non-fatal: emit a soft\n * note and proceed. The warning prints to stderr so the existing confirm\n * gate (or --yes) still governs whether money moves.\n */\n preConfirm?: (args: {\n identity: IdentityReport;\n addr: GitRepoAddr;\n relayUrl: string | undefined;\n }) => Promise<void>;\n}\n\n/** JSON envelope emitted by `--json` runs (agents consume this). */\ninterface EventJsonOutput {\n command: EventCommand;\n repoAddr: GitRepoAddr;\n /** Which transport paid: delegated daemon or embedded standalone (#279). */\n path: SessionPath;\n /** Active identity: source tier + derived pubkey (never the phrase). */\n identity: IdentityReport;\n /** NIP-34 kind this command publishes. */\n kind: number;\n /** True when the paid publish ran. */\n executed: boolean;\n /** Per-event fee (base units, decimal string). */\n feeEstimate: string | null;\n result?: GitEventResponse;\n hint?: string;\n}\n\n/**\n * The estimate → confirm → execute flow shared by all four subcommands.\n * Money moves only after the confirm gate and the single-relay guard.\n */\nasync function runEvent(opts: RunEventOptions): Promise<number> {\n const { command, flags, deps, actionLabel } = opts;\n const { io } = deps;\n\n let standaloneCtx: StandaloneContext | undefined;\n try {\n // ── Repo addressing (best-effort git config; flags can stand alone) ─────\n let repoRoot: string | undefined;\n let toonConfig: ToonRepoConfig = { relays: [] };\n try {\n repoRoot = await resolveRepoRoot(deps.cwd);\n toonConfig = await readToonConfig(repoRoot);\n } catch {\n // Not inside a git repository — --repo-id/--owner must carry the address.\n }\n const repoId = flags.repoId ?? toonConfig.repoId;\n if (!repoId) throw new UnconfiguredRepoAddressError('repository id');\n\n // ── Relay resolution (#249: --relay > --remote > origin > toon.relay) ───\n const resolved = await resolveRelays({\n relayFlags: flags.relay,\n remoteName: flags.remote,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n if (resolved.nudge !== undefined) io.err(resolved.nudge);\n const relaysUsed = resolved.relays;\n // Same pre-pay guard as push: StandalonePublisher publishes to exactly\n // one relay, and multiple can arrive without explicit intent (repeated\n // --relay flags, an old multi-valued git config `toon.relay`). Refuse\n // before anything is paid.\n if (relaysUsed.length > 1) {\n io.err(singleRelayRefusal(resolved, 'Nothing was published or paid.'));\n return 1;\n }\n\n // ── Paid session (#279): same-identity daemon → delegate; else the\n // standalone context (identity chain + nonce guard) + per-event fee.\n const session = await loadPaidSession(deps, relaysUsed[0]);\n const path = session.path;\n let identity: IdentityReport;\n let fee: string | undefined;\n if (session.path === 'standalone') {\n standaloneCtx = session.ctx;\n identity = identityReport(standaloneCtx);\n fee = (await standaloneCtx.publisher.getFeeRates()).eventFee.toString();\n } else {\n identity = session.identity;\n fee = session.feePerEvent;\n // The single-event /git/* routes publish via the daemon's own\n // configured relay route (no relayUrls field on the wire) — surface a\n // mismatch instead of silently ignoring the resolved relay.\n const resolvedRelay = relaysUsed[0];\n if (\n resolvedRelay !== undefined &&\n session.daemonRelayUrl !== undefined &&\n session.daemonRelayUrl !== resolvedRelay\n ) {\n io.err(\n `rig: the daemon publishes via its configured relay ` +\n `(${session.daemonRelayUrl}), not the resolved relay ` +\n `(${resolvedRelay}) — stop the daemon to force the standalone ` +\n 'path if that matters'\n );\n }\n }\n\n const owner = flags.owner ?? toonConfig.owner ?? identity.pubkey;\n const addr: GitRepoAddr = { ownerPubkey: owner, repoId };\n\n // Built once: the publish payload AND the kind for rendering.\n const event = await opts.buildEvent(addr);\n const action = `kind:${event.kind} ${actionLabel}`;\n\n // ── Authority pre-check (#287) — warn (do not block) before the gate ────\n if (opts.preConfirm) {\n await opts.preConfirm({ identity, addr, relayUrl: relaysUsed[0] });\n }\n\n // ── Confirm gate (identical semantics to `rig push`) ────────────────────\n if (!flags.json) {\n for (const line of renderEventPlan({\n action,\n addr,\n identity,\n ...(fee !== undefined ? { fee } : {}),\n })) {\n io.out(line);\n }\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: addr,\n path,\n identity,\n kind: event.kind,\n executed: false,\n feeEstimate: fee ?? null,\n hint: 'estimate only — re-run with --yes to publish (permanent, non-refundable)',\n } satisfies EventJsonOutput);\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n 'refusing to spend channel funds without confirmation in a non-interactive ' +\n 'session — re-run with --yes (or use --json for an estimate)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Proceed with paid publish (${feeLabel(fee)})? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was published.');\n return 1;\n }\n }\n\n // ── Execute ─────────────────────────────────────────────────────────────\n let result: GitEventResponse;\n if (session.path === 'standalone') {\n const receipt = await session.ctx.publisher.publishEvent(\n event,\n relaysUsed\n );\n result = serializeEventReceipt(event.kind, receipt);\n } else {\n result = await opts.sendDaemon(session.client, addr);\n }\n\n // ── Receipts ────────────────────────────────────────────────────────────\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: addr,\n path,\n identity,\n kind: result.kind,\n executed: true,\n feeEstimate: fee ?? null,\n result,\n } satisfies EventJsonOutput);\n } else {\n for (const line of renderEventReceipt(action, result)) io.out(line);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, command, err);\n } finally {\n if (standaloneCtx) {\n try {\n await standaloneCtx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// rig issue create\n// ---------------------------------------------------------------------------\n\n/** Run `rig issue …`; returns the process exit code. */\nexport async function runIssue(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n if (sub === '--help' || sub === '-h' || sub === 'help') {\n io.out(ISSUE_USAGE);\n io.out('');\n io.out(ISSUE_LIST_USAGE);\n io.out('');\n io.out(ISSUE_SHOW_USAGE);\n return 0;\n }\n // FREE read subcommands (#278): relay queries only, no payment path.\n if (sub === 'list') return runIssueList(rest, deps);\n if (sub === 'show') return runIssueShow(rest, deps);\n if (sub !== 'create') {\n io.err(\n sub === undefined\n ? 'missing subcommand: rig issue <create|list|show>'\n : `unknown rig issue subcommand: ${sub}`\n );\n io.err(ISSUE_USAGE);\n return 2;\n }\n\n let flags: CommonFlags;\n let title: string;\n let bodyFlag: string | undefined;\n let bodyFile: string | undefined;\n let labels: string[];\n try {\n const { values } = parseArgs({\n args: rest,\n options: {\n ...COMMON_OPTIONS,\n title: { type: 'string' },\n body: { type: 'string' },\n 'body-file': { type: 'string' },\n label: { type: 'string', multiple: true },\n },\n allowPositionals: false,\n });\n flags = pickCommon(values);\n if (!flags.help && (values.title === undefined || values.title === '')) {\n throw new Error('--title is required');\n }\n if (values.body !== undefined && values['body-file'] !== undefined) {\n throw new Error('--body and --body-file are mutually exclusive');\n }\n title = values.title ?? '';\n bodyFlag = values.body;\n bodyFile = values['body-file'];\n labels = values.label ?? [];\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(ISSUE_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(ISSUE_USAGE);\n return 0;\n }\n\n // Body source: --body → --body-file → piped stdin.\n let body: string;\n if (bodyFlag !== undefined) {\n body = bodyFlag;\n } else if (bodyFile !== undefined) {\n try {\n body = await readFile(bodyFile, 'utf-8');\n } catch (err) {\n io.err(\n `cannot read --body-file ${bodyFile}: ${err instanceof Error ? err.message : String(err)}`\n );\n return 2;\n }\n } else if (!io.isInteractive) {\n body = await (deps.readStdin ?? defaultReadStdin)();\n } else {\n io.err('an issue body is required: pass --body/--body-file or pipe stdin');\n io.err(ISSUE_USAGE);\n return 2;\n }\n if (body.trim() === '') {\n io.err('the issue body is empty — nothing to publish');\n return 2;\n }\n\n return runEvent({\n command: 'issue',\n flags,\n deps,\n actionLabel: `issue ${JSON.stringify(title)}`,\n buildEvent: async (addr) =>\n buildIssue(addr.ownerPubkey, addr.repoId, title, body, labels),\n sendDaemon: (client, addr) =>\n client.gitIssue({\n repoAddr: addr,\n title,\n body,\n ...(labels.length > 0 ? { labels } : {}),\n }),\n });\n}\n\n// ---------------------------------------------------------------------------\n// rig comment\n// ---------------------------------------------------------------------------\n\n/** Run `rig comment …`; returns the process exit code. */\nexport async function runComment(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let flags: CommonFlags;\n let rootEventId: string;\n let body: string;\n let parentAuthor: string | undefined;\n let marker: 'root' | 'reply';\n try {\n const { values, positionals } = parseArgs({\n args,\n options: {\n ...COMMON_OPTIONS,\n body: { type: 'string' },\n 'parent-author': { type: 'string' },\n marker: { type: 'string' },\n },\n allowPositionals: true,\n });\n flags = pickCommon(values);\n if (flags.help) {\n io.out(COMMENT_USAGE);\n return 0;\n }\n if (positionals.length !== 1) {\n throw new Error(\n positionals.length === 0\n ? '<root-event-id> is required'\n : `expected exactly one <root-event-id>, got ${positionals.length} positionals`\n );\n }\n rootEventId = positionals[0] as string;\n assertHex64(rootEventId, '<root-event-id>');\n if (values.body === undefined || values.body === '') {\n throw new Error('--body is required');\n }\n body = values.body;\n parentAuthor = values['parent-author'];\n if (parentAuthor !== undefined) assertHex64(parentAuthor, '--parent-author');\n const rawMarker = values.marker ?? 'root';\n if (rawMarker !== 'root' && rawMarker !== 'reply') {\n throw new Error(`--marker must be root or reply (got ${JSON.stringify(rawMarker)})`);\n }\n marker = rawMarker;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(COMMENT_USAGE);\n return 2;\n }\n\n return runEvent({\n command: 'comment',\n flags,\n deps,\n actionLabel: `comment on ${rootEventId.slice(0, 8)}…`,\n buildEvent: async (addr) =>\n buildComment(\n addr.ownerPubkey,\n addr.repoId,\n rootEventId,\n parentAuthor ?? addr.ownerPubkey,\n body,\n marker\n ),\n sendDaemon: (client, addr) =>\n client.gitComment({\n repoAddr: addr,\n rootEventId,\n body,\n ...(parentAuthor !== undefined\n ? { parentAuthorPubkey: parentAuthor }\n : {}),\n marker,\n }),\n });\n}\n\n// ---------------------------------------------------------------------------\n// rig pr create\n// ---------------------------------------------------------------------------\n\n/** `From <sha> <date>` separator lines of `git format-patch --stdout` output. */\nconst PATCH_FROM_RE = /^From ([0-9a-f]{40}) /gm;\n\n/** Commit SHAs of a format-patch series, in patch (oldest-first) order. */\nexport function extractPatchShas(patchText: string): string[] {\n return [...patchText.matchAll(PATCH_FROM_RE)].map((m) => m[1] as string);\n}\n\n/** Run `rig pr …` (nested dispatch: create | status); returns the exit code. */\nexport async function runPr(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n switch (sub) {\n case 'create':\n return runPrCreate(rest, deps);\n case 'status':\n return runPrStatus(rest, deps);\n // FREE read subcommands (#278): relay queries only, no payment path.\n case 'list':\n return runPrList(rest, deps);\n case 'show':\n return runPrShow(rest, deps);\n case '--help':\n case '-h':\n case 'help':\n io.out(PR_USAGE);\n return 0;\n default:\n io.err(\n sub === undefined\n ? 'missing subcommand: rig pr <create|status|list|show>'\n : `unknown rig pr subcommand: ${sub}`\n );\n io.err(PR_USAGE);\n return 2;\n }\n}\n\n/** `rig pr create` — kind:1617 patch publish. */\nasync function runPrCreate(\n rest: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let flags: CommonFlags;\n let title: string;\n let range: string | undefined;\n let patchFile: string | undefined;\n let branch: string | undefined;\n let bodyFlag: string | undefined;\n let bodyFile: string | undefined;\n try {\n const { values } = parseArgs({\n args: rest,\n options: {\n ...COMMON_OPTIONS,\n title: { type: 'string' },\n range: { type: 'string' },\n 'patch-file': { type: 'string' },\n body: { type: 'string' },\n 'body-file': { type: 'string' },\n branch: { type: 'string' },\n },\n allowPositionals: false,\n });\n flags = pickCommon(values);\n if (flags.help) {\n io.out(PR_CREATE_USAGE);\n return 0;\n }\n if (values.title === undefined || values.title === '') {\n throw new Error('--title is required');\n }\n if ((values.range === undefined) === (values['patch-file'] === undefined)) {\n throw new Error('exactly one of --range or --patch-file is required');\n }\n if (values.body !== undefined && values['body-file'] !== undefined) {\n throw new Error('--body and --body-file are mutually exclusive');\n }\n title = values.title;\n range = values.range;\n patchFile = values['patch-file'];\n branch = values.branch;\n bodyFlag = values.body;\n bodyFile = values['body-file'];\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(PR_CREATE_USAGE);\n return 2;\n }\n\n // PR description (optional): --body → --body-file. Carried in the event's\n // `description` tag — NEVER prepended to the content, which must stay pure\n // `git format-patch` output for `git am` (leading prose hard-fails git's\n // patch-format detection).\n let body: string | undefined;\n if (bodyFlag !== undefined) {\n body = bodyFlag;\n } else if (bodyFile !== undefined) {\n try {\n body = await readFile(bodyFile, 'utf-8');\n } catch (err) {\n io.err(\n `cannot read --body-file ${bodyFile}: ${err instanceof Error ? err.message : String(err)}`\n );\n return 2;\n }\n }\n if (body !== undefined && body.trim() === '') {\n io.err('the PR body is empty — drop --body/--body-file or pass text');\n return 2;\n }\n\n // Captured by buildEvent for the daemon path: what is SHOWN locally (the\n // built kind:1617 content) is exactly what the delegated /git/patch\n // publishes — the daemon never re-derives the series.\n let builtPatchText: string | undefined;\n let builtCommits: { sha: string; parentSha: string }[] = [];\n\n return runEvent({\n command: 'pr',\n flags,\n deps,\n actionLabel: `patch ${JSON.stringify(title)}`,\n buildEvent: async (addr) => {\n let patchText: string;\n let commits: { sha: string; parentSha: string }[];\n if (range !== undefined) {\n // REAL format-patch output from the local repository (v1 publishes\n // the whole series as ONE event; see PR_USAGE).\n const reader = new GitRepoReader(await resolveRepoRoot(deps.cwd));\n patchText = await reader.formatPatch(range);\n if (patchText === '') {\n throw new Error(\n `range ${JSON.stringify(range)} selects no commits — nothing to publish`\n );\n }\n // commit/parent-commit tags for exactly the commits the series\n // carries (parsed from the patch itself, so the tags can never drift\n // from the content). Root commits have no parent and contribute no\n // tag pair.\n const shas = extractPatchShas(patchText);\n const parents = await reader.commitParents(shas);\n commits = shas.flatMap((sha) => {\n const parentSha = parents.get(sha)?.[0];\n return parentSha ? [{ sha, parentSha }] : [];\n });\n } else {\n patchText = await readFile(patchFile as string, 'utf-8');\n if (patchText.trim() === '') {\n throw new Error(`--patch-file ${patchFile} is empty — nothing to publish`);\n }\n commits = [];\n }\n builtPatchText = patchText;\n builtCommits = commits;\n return buildPatch(\n addr.ownerPubkey,\n addr.repoId,\n title,\n commits,\n branch,\n patchText,\n body\n );\n },\n sendDaemon: (client, addr) => {\n if (builtPatchText === undefined) {\n throw new Error('internal: patch text not built before delegation');\n }\n return client.gitPatch({\n repoAddr: addr,\n title,\n patchText: builtPatchText,\n ...(body !== undefined ? { description: body } : {}),\n ...(builtCommits.length > 0 ? { commits: builtCommits } : {}),\n ...(branch !== undefined ? { branch } : {}),\n });\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// rig pr status (top-level `rig status` before #250 — now git's)\n// ---------------------------------------------------------------------------\n\n/** NIP-34 status kinds by wire value (mirrors the daemon's mapping). */\nconst STATUS_KIND_BY_VALUE: Record<GitStatusValue, StatusKind> = {\n open: STATUS_OPEN_KIND,\n applied: STATUS_APPLIED_KIND,\n closed: STATUS_CLOSED_KIND,\n draft: STATUS_DRAFT_KIND,\n};\n\nfunction isStatusValue(value: string): value is GitStatusValue {\n return Object.hasOwn(STATUS_KIND_BY_VALUE, value);\n}\n\n/** `rig pr status` — kind:1630-1633 status publish. */\nasync function runPrStatus(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let flags: CommonFlags;\n let targetEventId: string;\n let status: GitStatusValue;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: COMMON_OPTIONS,\n allowPositionals: true,\n });\n flags = pickCommon(values);\n if (flags.help) {\n io.out(PR_STATUS_USAGE);\n return 0;\n }\n if (positionals.length !== 2) {\n throw new Error(\n 'expected exactly two arguments: <target-event-id> <open|applied|closed|draft>'\n );\n }\n targetEventId = positionals[0] as string;\n assertHex64(targetEventId, '<target-event-id>');\n const rawStatus = positionals[1] as string;\n if (!isStatusValue(rawStatus)) {\n throw new Error(\n `status must be one of open | applied | closed | draft (got ${JSON.stringify(rawStatus)})`\n );\n }\n status = rawStatus;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(PR_STATUS_USAGE);\n return 2;\n }\n\n return runEvent({\n command: 'pr status',\n flags,\n deps,\n actionLabel: `status ${status} on ${targetEventId.slice(0, 8)}…`,\n buildEvent: async (addr) => {\n const event = buildStatus(targetEventId, STATUS_KIND_BY_VALUE[status]);\n // NIP-34 status events also carry the repo `a` tag so readers can scope\n // a status stream to the repository without resolving the target first\n // (mirrors the daemon's gitStatus).\n event.tags.push([\n 'a',\n `${REPOSITORY_ANNOUNCEMENT_KIND}:${addr.ownerPubkey}:${addr.repoId}`,\n ]);\n return event;\n },\n // Authority warning (#287): a status event only moves an issue/PR's\n // resolved state for repo-authority-honoring clients if its author is the\n // owner or a declared maintainer. Warn clearly when the active identity is\n // neither — the publish still happens (permissionless relay; the caller\n // may be acting on their own repo/fork), but the futility is made obvious.\n preConfirm: (args) => warnIfNotMaintainer(deps, args),\n sendDaemon: (client, addr) =>\n client.gitStatus({ repoAddr: addr, targetEventId, status }),\n });\n}\n\n/**\n * Read the target repo's kind:30617 and warn on stderr when the active\n * identity is NOT an authorized status author (owner ∪ declared maintainers,\n * #287). Never throws / never blocks: a relay read failure downgrades to a\n * \"could not verify\" note and the publish proceeds under the normal gate.\n */\nasync function warnIfNotMaintainer(\n deps: EventCommandDeps,\n args: {\n identity: IdentityReport;\n addr: GitRepoAddr;\n relayUrl: string | undefined;\n }\n): Promise<void> {\n const { io } = deps;\n const { identity, addr, relayUrl } = args;\n // The owner is always an implicit maintainer — no need to read the relay.\n if (identity.pubkey.toLowerCase() === addr.ownerPubkey.toLowerCase()) return;\n if (relayUrl === undefined) return;\n try {\n const remote = await fetchRemoteState({\n relayUrls: [relayUrl],\n ownerPubkey: addr.ownerPubkey,\n repoId: addr.repoId,\n ...(deps.webSocketFactory\n ? { webSocketFactory: deps.webSocketFactory }\n : {}),\n });\n const authorized = authorizedStatusAuthors(\n addr.ownerPubkey,\n remote.announceEvent?.tags ?? []\n );\n if (authorized.has(identity.pubkey.toLowerCase())) return;\n io.err(\n `warning: you (${identity.pubkey.slice(0, 8)}…) are not a maintainer of ` +\n `30617:${addr.ownerPubkey.slice(0, 8)}…:${addr.repoId} — clients honoring ` +\n 'repo authority (rig, rig-web) will IGNORE this status when resolving the ' +\n \"issue/PR's state. Publishing anyway (the relay is permissionless); ask the \" +\n 'owner to `rig maintainers add` you if this should stick.'\n );\n } catch {\n io.err(\n 'warning: could not read the repo announcement to verify your maintainer ' +\n 'status — if you are not the owner or a declared maintainer, ' +\n 'authority-honoring clients will ignore this status.'\n );\n }\n}\n","/**\n * The FREE tracker views (#278): `rig issue list|show` and `rig pr list|show`.\n *\n * Pure relay reads over NIP-01 (../remote-state.ts `queryRelay` — the same\n * decoder that tolerates the devnet relay's non-canonical EVENT payload\n * encodings): kind:1621 issues / kind:1617 patches scoped to the repo by the\n * `#a` tag (`30617:<owner>:<repoId>`), kind:1630-1633 status events to derive\n * each item's state (LATEST-WINS: highest created_at, ties broken by lowest\n * id), and kind:1622 comments under `show`. No payments, no channel, no\n * identity — reads are free on TOON.\n *\n * State derivation mirrors rig-web's proven `resolvePRStatus`, upgraded to\n * latest-wins for issues too (a re-opened issue is open again).\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n ISSUE_KIND,\n PATCH_KIND,\n REPOSITORY_ANNOUNCEMENT_KIND,\n STATUS_APPLIED_KIND,\n STATUS_CLOSED_KIND,\n STATUS_DRAFT_KIND,\n STATUS_OPEN_KIND,\n} from '@toon-protocol/core/nip34';\nimport { COMMENT_KIND, authorizedStatusAuthors } from '../nip34-events.js';\nimport { ownerToHex } from '../npub.js';\nimport {\n queryRelay,\n type NostrEvent,\n type NostrFilter,\n type WebSocketFactory,\n type WebSocketLike,\n} from '../remote-state.js';\nimport {\n emitCliError,\n UnconfiguredRepoAddressError,\n InvalidRelayUrlError,\n} from './errors.js';\nimport { readToonConfig, resolveRepoRoot } from './git-config.js';\nimport type { ReadCommandDeps } from './read-seams.js';\nimport { resolveRelays } from './remote.js';\n\n// ---------------------------------------------------------------------------\n// Usage\n// ---------------------------------------------------------------------------\n\nconst READ_COMMON_FLAGS = ` --repo-id <id> repository id / NIP-34 d-tag (default: git config)\n --owner <pubkey> repository owner (npub or 64-char hex; default: git config)\n --remote <name> read via this configured git remote (default: origin)\n --relay <url> ad-hoc relay override; repeatable — reads are merged\n --json machine-readable envelope\n -h, --help show this help`;\n\nexport const ISSUE_LIST_USAGE = `Usage: rig issue list [--state open|closed|all] [options]\n\nList the repo's issues (kind:1621) with their derived state — FREE (relay\nreads only). State comes from kind:1630-1633 status events: the latest status\nwins; an issue with no status events is open.\n\nOptions:\n --state <state> open | closed | all (default: all)\n${READ_COMMON_FLAGS}`;\n\nexport const ISSUE_SHOW_USAGE = `Usage: rig issue show <event-id> [options]\n\nShow one issue (kind:1621): metadata, derived state, body, and its\nkind:1622 comments — FREE (relay reads only). <event-id> is the 64-char hex\nid \\`rig issue create\\` printed (also visible in \\`rig issue list\\`).\n\nOptions:\n${READ_COMMON_FLAGS}`;\n\nexport const PR_LIST_USAGE = `Usage: rig pr list [--state open|applied|closed|draft|all] [options]\n\nList the repo's patches/PRs (kind:1617) with their derived state — FREE\n(relay reads only). State comes from kind:1630-1633 status events: the\nlatest status wins; a patch with no status events is open.\n\nOptions:\n --state <state> open | applied | closed | draft | all (default: all)\n${READ_COMMON_FLAGS}`;\n\nexport const PR_SHOW_USAGE = `Usage: rig pr show <event-id> [options]\n\nShow one patch/PR (kind:1617): metadata, derived state, the FULL patch text\n(real \\`git format-patch\\` output — pipe it to \\`git am\\` to apply), and its\nkind:1622 comments — FREE (relay reads only).\n\nOptions:\n${READ_COMMON_FLAGS}`;\n\n// ---------------------------------------------------------------------------\n// Status derivation (latest-wins)\n// ---------------------------------------------------------------------------\n\nexport type TrackerStatus = 'open' | 'applied' | 'closed' | 'draft';\n\nconst STATUS_BY_KIND: Record<number, TrackerStatus> = {\n [STATUS_OPEN_KIND]: 'open',\n [STATUS_APPLIED_KIND]: 'applied',\n [STATUS_CLOSED_KIND]: 'closed',\n [STATUS_DRAFT_KIND]: 'draft',\n};\n\nconst STATUS_KINDS = [\n STATUS_OPEN_KIND,\n STATUS_APPLIED_KIND,\n STATUS_CLOSED_KIND,\n STATUS_DRAFT_KIND,\n];\n\nfunction tagValue(tags: string[][], name: string): string | undefined {\n return tags.find((t) => t[0] === name)?.[1];\n}\n\nfunction tagValues(tags: string[][], name: string): string[] {\n return tags.filter((t) => t[0] === name && t[1]).map((t) => t[1] as string);\n}\n\n/**\n * Derive the state of an issue/patch from its status events: consider only\n * kind:1630-1633 events whose `e` tag references the target AND whose author\n * is AUTHORIZED — the repo owner ∪ declared maintainers (#287). Among the\n * authorized events the LATEST wins (highest created_at, ties broken by lowest\n * event id — the same replaceable convention remote-state uses). Unauthorized\n * status events (any funded stranger) are IGNORED for state; they never move\n * it. No authorized status events ⇒ open.\n *\n * `authorized` is the lowercased-hex set from {@link authorizedStatusAuthors}.\n * When it is empty (the 30617 could not be resolved) NOTHING is authorized and\n * the state stays open — a safe, non-spoofable default.\n */\nexport function deriveStatus(\n targetEventId: string,\n statusEvents: Iterable<NostrEvent>,\n authorized: ReadonlySet<string>\n): TrackerStatus {\n let winner: NostrEvent | null = null;\n for (const event of statusEvents) {\n if (STATUS_BY_KIND[event.kind] === undefined) continue;\n if (!authorized.has(event.pubkey.toLowerCase())) continue;\n if (!event.tags.some((t) => t[0] === 'e' && t[1] === targetEventId))\n continue;\n if (\n winner === null ||\n event.created_at > winner.created_at ||\n (event.created_at === winner.created_at && event.id < winner.id)\n ) {\n winner = event;\n }\n }\n return winner === null\n ? 'open'\n : (STATUS_BY_KIND[winner.kind] as TrackerStatus);\n}\n\n// ---------------------------------------------------------------------------\n// Relay querying (multi-relay merge; tolerant decode via queryRelay)\n// ---------------------------------------------------------------------------\n\nconst RELAY_TIMEOUT_MS = 10000;\nconst HEX64_RE = /^[0-9a-f]{64}$/;\nconst WS_URL_RE = /^wss?:\\/\\//i;\n\nfunction defaultWebSocketFactory(url: string): WebSocketLike {\n const ctor = (\n globalThis as { WebSocket?: new (url: string) => WebSocketLike }\n ).WebSocket;\n if (!ctor) {\n throw new Error(\n 'No global WebSocket constructor (Node >= 22 required) — pass webSocketFactory'\n );\n }\n return new ctor(url);\n}\n\n/**\n * Query every relay with every filter and merge events by id. Resolves as\n * long as at least one relay answered; throws when all fail.\n */\nasync function queryAll(\n relays: string[],\n filters: NostrFilter[],\n webSocketFactory: WebSocketFactory\n): Promise<Map<string, NostrEvent>> {\n const jobs = relays.flatMap((relay) =>\n filters.map((filter) =>\n queryRelay(relay, filter, RELAY_TIMEOUT_MS, webSocketFactory)\n )\n );\n const results = await Promise.allSettled(jobs);\n const byId = new Map<string, NostrEvent>();\n let failures = 0;\n let firstError: unknown;\n for (const result of results) {\n if (result.status === 'rejected') {\n failures += 1;\n firstError ??= result.reason;\n continue;\n }\n for (const event of result.value) {\n if (typeof event.id === 'string' && !byId.has(event.id)) {\n byId.set(event.id, event);\n }\n }\n }\n if (failures === results.length && results.length > 0) {\n throw firstError instanceof Error\n ? firstError\n : new Error(String(firstError));\n }\n return byId;\n}\n\n// ---------------------------------------------------------------------------\n// Shared context resolution (repo address + relays; NO identity, NO payment)\n// ---------------------------------------------------------------------------\n\ninterface TrackerFlags {\n json: boolean;\n help: boolean;\n state?: string;\n relay: string[];\n remote?: string;\n repoId?: string;\n owner?: string;\n}\n\nconst TRACKER_OPTIONS = {\n json: { type: 'boolean', default: false },\n state: { type: 'string' },\n relay: { type: 'string', multiple: true },\n remote: { type: 'string' },\n 'repo-id': { type: 'string' },\n owner: { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n} as const;\n\nfunction pickTrackerFlags(values: Record<string, unknown>): TrackerFlags {\n const flags: TrackerFlags = {\n json: values['json'] === true,\n help: values['help'] === true,\n relay: Array.isArray(values['relay']) ? (values['relay'] as string[]) : [],\n };\n if (typeof values['state'] === 'string') flags.state = values['state'];\n if (typeof values['remote'] === 'string') flags.remote = values['remote'];\n if (typeof values['repo-id'] === 'string') flags.repoId = values['repo-id'];\n if (typeof values['owner'] === 'string')\n flags.owner = ownerToHex(values['owner']);\n return flags;\n}\n\ninterface TrackerContext {\n relays: string[];\n /** Set when the repo address resolved (list always has it; show may not). */\n repoAddr: { ownerPubkey: string; repoId: string } | null;\n webSocketFactory: WebSocketFactory;\n}\n\n/**\n * Resolve relays (+ repo address when `needRepoAddr`) from flags and the git\n * config, mirroring the paid commands' #249 chain — but reads may target\n * MULTIPLE relays (results are merged), and only ws/wss URLs are usable.\n */\nasync function resolveTrackerContext(\n flags: TrackerFlags,\n deps: ReadCommandDeps,\n needRepoAddr: boolean\n): Promise<TrackerContext> {\n let repoRoot: string | undefined;\n let toonConfig: { repoId?: string; owner?: string; relays: string[] } = {\n relays: [],\n };\n try {\n repoRoot = await resolveRepoRoot(deps.cwd);\n toonConfig = await readToonConfig(repoRoot);\n } catch {\n // Not inside a git repo — flags must carry everything.\n }\n\n // Resolve the repo address from flags/git config. `list` REQUIRES it (throws\n // when unresolved). `show` does not, but resolves it OPPORTUNISTICALLY when\n // available so it can fall back to it for the authority set (#287) when the\n // shown item lacks a parseable `a` tag — otherwise `show` would report a\n // falsely-`open` status that `list` (which always has the address) resolves\n // correctly.\n let repoAddr: TrackerContext['repoAddr'] = null;\n const repoId = flags.repoId ?? toonConfig.repoId;\n const owner = flags.owner ?? toonConfig.owner;\n if (repoId && owner) {\n repoAddr = { ownerPubkey: owner, repoId };\n } else if (needRepoAddr) {\n if (!repoId) throw new UnconfiguredRepoAddressError('repository id');\n throw new UnconfiguredRepoAddressError('repository owner');\n }\n\n const resolved = await resolveRelays({\n relayFlags: flags.relay,\n remoteName: flags.remote,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n const wsRelays = resolved.relays.filter((url) => WS_URL_RE.test(url));\n if (wsRelays.length === 0) {\n throw new InvalidRelayUrlError(\n resolved.relays[0] ?? '',\n 'reads need a ws:// or wss:// relay'\n );\n }\n\n return {\n relays: wsRelays,\n repoAddr,\n webSocketFactory: deps.webSocketFactory ?? defaultWebSocketFactory,\n };\n}\n\nfunction repoATag(addr: { ownerPubkey: string; repoId: string }): string {\n return `${REPOSITORY_ANNOUNCEMENT_KIND}:${addr.ownerPubkey}:${addr.repoId}`;\n}\n\n/**\n * Resolve the AUTHORIZED status authors (#287) for a repo: the owner ∪ the\n * maintainers declared on the repo's kind:30617 announcement. Reads the 30617\n * from the relay(s) — untrusted relays may over-return, so only the owner's\n * own announcement for this `d`-tag is honored. When no announcement is found\n * the set falls back to OWNER-ONLY (the owner is always an implicit\n * maintainer); this is the safe default — an unresolved 30617 can never widen\n * authority to a stranger.\n */\nasync function fetchAuthorizedAuthors(\n ctx: TrackerContext,\n ownerPubkey: string,\n repoId: string\n): Promise<Set<string>> {\n let announceTags: string[][] = [];\n try {\n const events = await queryAll(\n ctx.relays,\n [\n {\n kinds: [REPOSITORY_ANNOUNCEMENT_KIND],\n authors: [ownerPubkey],\n '#d': [repoId],\n },\n ],\n ctx.webSocketFactory\n );\n // Latest replaceable 30617 by (created_at, id) from the trusted owner.\n let latest: NostrEvent | null = null;\n for (const event of events.values()) {\n if (event.kind !== REPOSITORY_ANNOUNCEMENT_KIND) continue;\n if (event.pubkey !== ownerPubkey) continue;\n if (!event.tags.some((t) => t[0] === 'd' && t[1] === repoId)) continue;\n if (\n latest === null ||\n event.created_at > latest.created_at ||\n (event.created_at === latest.created_at && event.id < latest.id)\n ) {\n latest = event;\n }\n }\n if (latest) announceTags = latest.tags;\n } catch {\n // Relay read failed — fall back to owner-only authority.\n }\n return authorizedStatusAuthors(ownerPubkey, announceTags);\n}\n\n// ---------------------------------------------------------------------------\n// Shared list/show engines (issues and PRs differ only in kind + fields)\n// ---------------------------------------------------------------------------\n\ninterface TrackerItem {\n eventId: string;\n kind: number;\n title: string;\n status: TrackerStatus;\n authorPubkey: string;\n createdAt: number;\n labels: string[];\n content: string;\n /** kind:1617 only: `commit` tag SHAs. */\n commitShas?: string[];\n /** kind:1617 only: `branch` tag. */\n branch?: string;\n /**\n * kind:1617 only: the PR body from the `description` tag (#280). Separate\n * from `content`, which is pure `git format-patch` output for `git am`.\n */\n description?: string;\n}\n\nfunction parseTrackerItem(\n event: NostrEvent,\n status: TrackerStatus\n): TrackerItem {\n const item: TrackerItem = {\n eventId: event.id,\n kind: event.kind,\n title:\n tagValue(event.tags, 'subject') ??\n (event.content.split('\\n')[0] ?? '').slice(0, 120),\n status,\n authorPubkey: event.pubkey,\n createdAt: event.created_at,\n labels: tagValues(event.tags, 't'),\n content: event.content,\n };\n if (event.kind === PATCH_KIND) {\n item.commitShas = tagValues(event.tags, 'commit');\n const branch = tagValue(event.tags, 'branch');\n if (branch !== undefined) item.branch = branch;\n const description = tagValue(event.tags, 'description');\n if (description !== undefined) item.description = description;\n }\n return item;\n}\n\nfunction isoDate(createdAt: number): string {\n return new Date(createdAt * 1000).toISOString().slice(0, 10);\n}\n\n/** Fetch items of `kind` for the repo + their statuses; derive state. */\nasync function fetchItems(\n ctx: TrackerContext,\n kind: number\n): Promise<TrackerItem[]> {\n const addr = ctx.repoAddr as { ownerPubkey: string; repoId: string };\n const aTag = repoATag(addr);\n // Authority set (#287): owner ∪ declared maintainers from the 30617. Fetched\n // in parallel with the items — status resolution honors ONLY these authors.\n const authorizedPromise = fetchAuthorizedAuthors(\n ctx,\n addr.ownerPubkey,\n addr.repoId\n );\n const [itemEvents, aStatusEvents] = await Promise.all([\n queryAll(\n ctx.relays,\n [{ kinds: [kind], '#a': [aTag] }],\n ctx.webSocketFactory\n ),\n queryAll(\n ctx.relays,\n [{ kinds: STATUS_KINDS, '#a': [aTag] }],\n ctx.webSocketFactory\n ),\n ]);\n\n // Defense against over-returning relays: keep only the right kind + repo.\n const items = [...itemEvents.values()].filter(\n (e) => e.kind === kind && e.tags.some((t) => t[0] === 'a' && t[1] === aTag)\n );\n\n // Statuses may lack the repo `a` tag (other clients) — also query by `#e`.\n const statuses = new Map(aStatusEvents);\n if (items.length > 0) {\n const byE = await queryAll(\n ctx.relays,\n [{ kinds: STATUS_KINDS, '#e': items.map((i) => i.id) }],\n ctx.webSocketFactory\n );\n for (const [id, event] of byE)\n if (!statuses.has(id)) statuses.set(id, event);\n }\n\n const authorized = await authorizedPromise;\n return items\n .map((event) =>\n parseTrackerItem(event, deriveStatus(event.id, statuses.values(), authorized))\n )\n .sort((a, b) => b.createdAt - a.createdAt);\n}\n\ninterface ShownItem {\n item: TrackerItem;\n comments: {\n eventId: string;\n authorPubkey: string;\n createdAt: number;\n content: string;\n }[];\n repoATag: string | null;\n}\n\n/** Fetch one item by event id + its statuses and comments. */\nasync function fetchItem(\n ctx: TrackerContext,\n eventId: string,\n expectedKind: number\n): Promise<ShownItem> {\n const found = await queryAll(\n ctx.relays,\n [{ ids: [eventId] }],\n ctx.webSocketFactory\n );\n const event = found.get(eventId);\n if (!event) {\n throw new Error(`event ${eventId} not found on ${ctx.relays.join(', ')}`);\n }\n if (event.kind !== expectedKind) {\n const hint =\n event.kind === PATCH_KIND\n ? ' (it is a kind:1617 patch — use `rig pr show`)'\n : event.kind === ISSUE_KIND\n ? ' (it is a kind:1621 issue — use `rig issue show`)'\n : '';\n throw new Error(\n `event ${eventId} has kind ${event.kind}, expected ${expectedKind}${hint}`\n );\n }\n\n const [statusEvents, commentEvents] = await Promise.all([\n queryAll(\n ctx.relays,\n [{ kinds: STATUS_KINDS, '#e': [eventId] }],\n ctx.webSocketFactory\n ),\n queryAll(\n ctx.relays,\n [{ kinds: [COMMENT_KIND], '#e': [eventId] }],\n ctx.webSocketFactory\n ),\n ]);\n\n const comments = [...commentEvents.values()]\n .filter(\n (e) =>\n e.kind === COMMENT_KIND &&\n e.tags.some((t) => t[0] === 'e' && t[1] === eventId)\n )\n .sort((a, b) => a.created_at - b.created_at)\n .map((e) => ({\n eventId: e.id,\n authorPubkey: e.pubkey,\n createdAt: e.created_at,\n content: e.content,\n }));\n\n // Authority set (#287): prefer the shown item's own `a` tag\n // (30617:<owner>:<id>) and read that repo's 30617 for the maintainers. When\n // the item lacks a parseable `a` tag, fall back to the configured repo\n // address (--repo-id/--owner or git config) so `show` matches `list` instead\n // of reporting a falsely-`open` status. Only when NEITHER is available is the\n // set empty ⇒ status stays open (safe: no stranger can move it either way).\n const repoATag = tagValue(event.tags, 'a') ?? null;\n const parsedAddr = parseRepoATag(repoATag) ?? ctx.repoAddr;\n const authorized = parsedAddr\n ? await fetchAuthorizedAuthors(ctx, parsedAddr.ownerPubkey, parsedAddr.repoId)\n : new Set<string>();\n\n return {\n item: parseTrackerItem(\n event,\n deriveStatus(eventId, statusEvents.values(), authorized)\n ),\n comments,\n repoATag,\n };\n}\n\n/** Parse a NIP-34 repo `a` tag `30617:<owner-hex>:<repoId>` into its parts. */\nfunction parseRepoATag(\n aTag: string | null\n): { ownerPubkey: string; repoId: string } | null {\n if (!aTag) return null;\n const [kind, ownerPubkey, ...repoIdParts] = aTag.split(':');\n const repoId = repoIdParts.join(':');\n if (kind !== String(REPOSITORY_ANNOUNCEMENT_KIND) || !ownerPubkey || !repoId) {\n return null;\n }\n return { ownerPubkey, repoId };\n}\n\n// ---------------------------------------------------------------------------\n// list command (shared by issue/pr)\n// ---------------------------------------------------------------------------\n\ninterface ListSpec {\n command: 'issue list' | 'pr list';\n kind: number;\n usage: string;\n states: readonly TrackerStatus[];\n jsonKey: 'issues' | 'prs';\n}\n\nasync function runList(\n args: string[],\n deps: ReadCommandDeps,\n spec: ListSpec\n): Promise<number> {\n const { io } = deps;\n let flags: TrackerFlags;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: TRACKER_OPTIONS,\n allowPositionals: true,\n });\n if (positionals.length > 0) {\n throw new Error(`rig ${spec.command} takes no positional arguments`);\n }\n flags = pickTrackerFlags(values);\n if (\n flags.state !== undefined &&\n flags.state !== 'all' &&\n !spec.states.includes(flags.state as TrackerStatus)\n ) {\n throw new Error(\n `--state must be one of ${[...spec.states, 'all'].join(' | ')} (got ${JSON.stringify(flags.state)})`\n );\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(spec.usage);\n return 2;\n }\n if (flags.help) {\n io.out(spec.usage);\n return 0;\n }\n\n try {\n const ctx = await resolveTrackerContext(flags, deps, true);\n const all = await fetchItems(ctx, spec.kind);\n const state = flags.state ?? 'all';\n const items = state === 'all' ? all : all.filter((i) => i.status === state);\n\n if (flags.json) {\n io.emitJson({\n command: spec.command,\n repoAddr: ctx.repoAddr,\n relays: ctx.relays,\n state,\n count: items.length,\n [spec.jsonKey]: items,\n });\n return 0;\n }\n\n if (items.length === 0) {\n io.out(\n `no ${state === 'all' ? '' : `${state} `}${spec.jsonKey} found for ` +\n `${repoATag(ctx.repoAddr as { ownerPubkey: string; repoId: string })}`\n );\n return 0;\n }\n for (const item of items) {\n const labels =\n item.labels.length > 0 ? ` [${item.labels.join(', ')}]` : '';\n io.out(\n `${item.status.padEnd(7)} ${item.eventId.slice(0, 8)} ${item.title}` +\n ` (${item.authorPubkey.slice(0, 8)}, ${isoDate(item.createdAt)})${labels}`\n );\n }\n io.out(\n `${items.length} ${spec.jsonKey}${state === 'all' ? '' : ` (${state})`}`\n );\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, spec.command, err);\n }\n}\n\n// ---------------------------------------------------------------------------\n// show command (shared by issue/pr)\n// ---------------------------------------------------------------------------\n\ninterface ShowSpec {\n command: 'issue show' | 'pr show';\n kind: number;\n usage: string;\n jsonKey: 'issue' | 'pr';\n /** PRs print their full patch text; issues print the body. */\n bodyLabel: string;\n}\n\nasync function runShow(\n args: string[],\n deps: ReadCommandDeps,\n spec: ShowSpec\n): Promise<number> {\n const { io } = deps;\n let flags: TrackerFlags;\n let eventId: string;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: TRACKER_OPTIONS,\n allowPositionals: true,\n });\n flags = pickTrackerFlags(values);\n if (flags.help) {\n io.out(spec.usage);\n return 0;\n }\n if (positionals.length !== 1) {\n throw new Error('expected exactly one <event-id>');\n }\n eventId = positionals[0] as string;\n if (!HEX64_RE.test(eventId)) {\n throw new Error(\n `<event-id> must be a 64-char lowercase hex id (got ${JSON.stringify(eventId)})`\n );\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(spec.usage);\n return 2;\n }\n\n try {\n const ctx = await resolveTrackerContext(flags, deps, false);\n const shown = await fetchItem(ctx, eventId, spec.kind);\n\n if (flags.json) {\n io.emitJson({\n command: spec.command,\n relays: ctx.relays,\n repoATag: shown.repoATag,\n [spec.jsonKey]: shown.item,\n comments: shown.comments,\n });\n return 0;\n }\n\n const { item } = shown;\n io.out(`${spec.jsonKey} ${item.eventId}`);\n io.out(`Title: ${item.title}`);\n io.out(`Status: ${item.status}`);\n io.out(`Author: ${item.authorPubkey}`);\n io.out(`Date: ${isoDate(item.createdAt)}`);\n if (item.labels.length > 0) io.out(`Labels: ${item.labels.join(', ')}`);\n if (item.branch !== undefined) io.out(`Branch: ${item.branch}`);\n if (item.commitShas && item.commitShas.length > 0) {\n io.out(`Commits: ${item.commitShas.join(', ')}`);\n }\n if (shown.repoATag !== null) io.out(`Repo: ${shown.repoATag}`);\n if (item.description !== undefined) {\n // The `description` tag (`rig pr create --body`): shown as its own\n // section so the patch text below stays pipeable into `git am`.\n io.out('');\n io.out('Body:');\n for (const line of item.description.split('\\n')) io.out(line);\n }\n io.out('');\n io.out(`${spec.bodyLabel}:`);\n for (const line of item.content.split('\\n')) io.out(line);\n io.out('');\n io.out(`Comments (${shown.comments.length}):`);\n for (const comment of shown.comments) {\n io.out(\n `--- ${comment.eventId.slice(0, 8)} by ${comment.authorPubkey.slice(0, 8)} ` +\n `on ${isoDate(comment.createdAt)}`\n );\n for (const line of comment.content.split('\\n')) io.out(line);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, spec.command, err);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public entry points\n// ---------------------------------------------------------------------------\n\nconst ISSUE_STATES = ['open', 'closed', 'applied', 'draft'] as const;\nconst PR_STATES = ['open', 'applied', 'closed', 'draft'] as const;\n\n/** `rig issue list` */\nexport function runIssueList(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n return runList(args, deps, {\n command: 'issue list',\n kind: ISSUE_KIND,\n usage: ISSUE_LIST_USAGE,\n states: ISSUE_STATES,\n jsonKey: 'issues',\n });\n}\n\n/** `rig issue show <event-id>` */\nexport function runIssueShow(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n return runShow(args, deps, {\n command: 'issue show',\n kind: ISSUE_KIND,\n usage: ISSUE_SHOW_USAGE,\n jsonKey: 'issue',\n bodyLabel: 'Body',\n });\n}\n\n/** `rig pr list` */\nexport function runPrList(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n return runList(args, deps, {\n command: 'pr list',\n kind: PATCH_KIND,\n usage: PR_LIST_USAGE,\n states: PR_STATES,\n jsonKey: 'prs',\n });\n}\n\n/** `rig pr show <event-id>` */\nexport function runPrShow(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n return runShow(args, deps, {\n command: 'pr show',\n kind: PATCH_KIND,\n usage: PR_SHOW_USAGE,\n jsonKey: 'pr',\n bodyLabel: 'Patch',\n });\n}\n","/**\n * `rig fetch` (#278) — the clone pipeline against an EXISTING repository:\n * fetch the remote refs + sha→txId map from the relay, download only the\n * objects the local repository is missing (SHA-1 verified), and update the\n * remote-tracking refs (refs/remotes/<remote>/*; tags to refs/tags/*),\n * reporting what moved like `git fetch` does. FREE — no payments anywhere.\n *\n * No merge: integrating fetched refs is `rig merge origin/main` (the git\n * passthrough), exactly like plain git. `rig fetch` shadows `git fetch` the\n * same way `rig push` shadows `git push`; plain-git fetches stay available\n * by running `git fetch` directly.\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n isSafeRefname,\n runGit,\n updateRef,\n writeGitObjects,\n} from '../materialize.js';\nimport { ownerToHex } from '../npub.js';\nimport { collectRepoObjects } from '../read-pipeline.js';\nimport { fetchRemoteState } from '../remote-state.js';\nimport { GitRepoReader } from '../repo-reader.js';\nimport {\n emitCliError,\n InvalidRelayUrlError,\n MultiUrlRemoteError,\n UnconfiguredRepoAddressError,\n UnknownRemoteError,\n} from './errors.js';\nimport {\n readToonConfig,\n getGitRemoteUrls,\n resolveRepoRoot,\n} from './git-config.js';\nimport { MissingRemoteObjectsError } from './clone.js';\nimport type { ReadCommandDeps } from './read-seams.js';\n\nexport const FETCH_USAGE = `Usage: rig fetch [remote] [options]\n\nFetch from a TOON remote — FREE (relay reads + Arweave gateway downloads; no\npayments, no identity needed). Reads the kind:30618 repository state from the\nremote's relay, downloads only the git objects this repository is missing\n(SHA-1 verified), and updates the remote-tracking refs\n(refs/remotes/<remote>/*; tags land at refs/tags/*), reporting what moved.\n\nNo merge happens: integrate with the git passthrough, e.g.\n\\`rig merge origin/main\\`. \\`rig fetch\\` is the TOON transport and shadows\n\\`git fetch\\` — plain-git fetches remain available via \\`git fetch\\` directly.\n\nThe repo address (toon.repoid/toon.owner) comes from the config \\`rig init\\`\nor \\`rig clone\\` writes; --repo-id/--owner override.\n\nOptions:\n --repo-id <id> repository id / NIP-34 d-tag (default: git config)\n --owner <pubkey> repository owner (npub or 64-char hex; default: git config)\n --relay <url> ad-hoc relay override — bypasses the remote's URL\n --concurrency <n> parallel gateway downloads (default 8)\n --json machine-readable result envelope\n -h, --help show this help`;\n\n/** One remote-tracking ref movement, `git fetch`-style. */\nexport interface RefUpdate {\n /** Remote refname (as announced), e.g. `refs/heads/main`. */\n refname: string;\n /** Local ref that was updated, e.g. `refs/remotes/origin/main`. */\n localRef: string;\n oldSha: string | null;\n newSha: string;\n kind: 'new' | 'fast-forward' | 'forced' | 'up-to-date';\n}\n\nconst WS_URL_RE = /^wss?:\\/\\//i;\n\n/** Map an announced refname to its local destination for `remote`. */\nfunction localRefFor(refname: string, remote: string): string | null {\n if (refname.startsWith('refs/heads/')) {\n return `refs/remotes/${remote}/${refname.slice('refs/heads/'.length)}`;\n }\n if (refname.startsWith('refs/tags/')) return refname;\n return null; // exotic namespaces are skipped\n}\n\n/** rev-parse a ref, null when it doesn't exist. */\nasync function resolveLocalRef(\n repoRoot: string,\n refname: string\n): Promise<string | null> {\n try {\n const out = await runGit(repoRoot, [\n 'rev-parse',\n '--verify',\n '--quiet',\n refname,\n ]);\n const sha = out.trim();\n return /^[0-9a-f]{40}$/.test(sha) ? sha : null;\n } catch {\n return null;\n }\n}\n\n/** Run `rig fetch …`; returns the process exit code. */\nexport async function runFetch(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let json = false;\n let remote = 'origin';\n let relayFlag: string | undefined;\n let repoIdFlag: string | undefined;\n let ownerFlag: string | undefined;\n let concurrency: number | undefined;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n relay: { type: 'string' },\n 'repo-id': { type: 'string' },\n owner: { type: 'string' },\n concurrency: { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: true,\n });\n if (values.help) {\n io.out(FETCH_USAGE);\n return 0;\n }\n json = values.json === true;\n if (positionals.length > 1) {\n throw new Error(\n `expected at most one [remote] argument, got ${positionals.length}`\n );\n }\n if (positionals[0] !== undefined) remote = positionals[0];\n relayFlag = values.relay;\n repoIdFlag = values['repo-id'];\n ownerFlag =\n values.owner !== undefined ? ownerToHex(values.owner) : undefined;\n if (values.concurrency !== undefined) {\n concurrency = Number.parseInt(values.concurrency, 10);\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) {\n throw new Error('--concurrency must be a positive integer');\n }\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(FETCH_USAGE);\n return 2;\n }\n\n try {\n // ── Repo addressing + relay resolution ─────────────────────────────────\n const repoRoot = await resolveRepoRoot(deps.cwd);\n const toonConfig = await readToonConfig(repoRoot);\n const repoId = repoIdFlag ?? toonConfig.repoId;\n if (!repoId) throw new UnconfiguredRepoAddressError('repository id');\n const owner = ownerFlag ?? toonConfig.owner;\n if (!owner) throw new UnconfiguredRepoAddressError('repository owner');\n\n let relayUrl: string;\n if (relayFlag !== undefined) {\n relayUrl = relayFlag;\n } else {\n const urls = await getGitRemoteUrls(repoRoot, remote);\n if (urls.length === 0) throw new UnknownRemoteError(remote);\n if (urls.length > 1) throw new MultiUrlRemoteError(remote, urls);\n relayUrl = urls[0] as string;\n }\n if (!WS_URL_RE.test(relayUrl)) {\n throw new InvalidRelayUrlError(\n relayUrl,\n `remote ${JSON.stringify(remote)}`\n );\n }\n\n // ── Remote state ────────────────────────────────────────────────────────\n const remoteState = await fetchRemoteState({\n relayUrls: [relayUrl],\n ownerPubkey: owner,\n repoId,\n ...(deps.webSocketFactory\n ? { webSocketFactory: deps.webSocketFactory }\n : {}),\n ...(deps.resolveSha ? { resolveSha: deps.resolveSha } : {}),\n });\n\n // Plan the tracking-ref updates (hostile-relay refname gate included).\n const planned: { refname: string; localRef: string; newSha: string }[] = [];\n for (const [refname, sha] of remoteState.refs) {\n if (!isSafeRefname(refname)) {\n io.err(\n `warning: skipping unsafe ref name from relay: ${JSON.stringify(refname)}`\n );\n continue;\n }\n const localRef = localRefFor(refname, remote);\n if (localRef === null) {\n io.err(\n `warning: skipping ref outside refs/heads and refs/tags: ${refname}`\n );\n continue;\n }\n planned.push({ refname, localRef, newSha: sha });\n }\n\n // ── Delta: download only what the local repository is missing ──────────\n const reader = new GitRepoReader(repoRoot);\n const tips = [...new Set(planned.map((p) => p.newSha))];\n const candidates = [...new Set([...remoteState.shaToTxId.keys(), ...tips])];\n const { missing: absent } = await reader.statObjects(candidates);\n const absentSet = new Set(absent);\n const presentLocally = new Set(\n candidates.filter((sha) => !absentSet.has(sha))\n );\n\n const collected = await collectRepoObjects({\n tips,\n shaToTxId: remoteState.shaToTxId,\n resolveMissing: (shas) => remoteState.resolveMissing(shas),\n presentLocally,\n ...(deps.fetchFn ? { fetchFn: deps.fetchFn } : {}),\n ...(concurrency !== undefined ? { concurrency } : {}),\n });\n if (collected.missing.length > 0) {\n throw new MissingRemoteObjectsError(\n collected.missing,\n `cannot fetch from ${relayUrl}`\n );\n }\n const written = await writeGitObjects(repoRoot, collected.objects.values());\n\n // ── Update tracking refs + report movements ─────────────────────────────\n const updates: RefUpdate[] = [];\n for (const { refname, localRef, newSha } of planned) {\n const oldSha = await resolveLocalRef(repoRoot, localRef);\n if (oldSha === newSha) {\n updates.push({ refname, localRef, oldSha, newSha, kind: 'up-to-date' });\n continue;\n }\n let kind: RefUpdate['kind'];\n if (oldSha === null) {\n kind = 'new';\n } else {\n kind = (await reader.isAncestor(oldSha, newSha))\n ? 'fast-forward'\n : 'forced';\n }\n await updateRef(repoRoot, localRef, newSha);\n updates.push({ refname, localRef, oldSha, newSha, kind });\n }\n\n // ── Report ──────────────────────────────────────────────────────────────\n const moved = updates.filter((u) => u.kind !== 'up-to-date');\n if (json) {\n io.emitJson({\n command: 'fetch',\n repoAddr: { ownerPubkey: owner, repoId },\n remote,\n relay: relayUrl,\n objectsDownloaded: written,\n updates,\n executed: true,\n });\n return 0;\n }\n if (moved.length === 0) {\n io.out('Already up to date.');\n return 0;\n }\n io.out(`From ${relayUrl}`);\n for (const u of moved) {\n const short = (refname: string): string =>\n refname\n .replace(/^refs\\/heads\\//, '')\n .replace(/^refs\\/tags\\//, '')\n .replace(/^refs\\/remotes\\//, '');\n const src = short(u.refname);\n const dst = short(u.localRef);\n if (u.kind === 'new') {\n const label = u.refname.startsWith('refs/tags/')\n ? '[new tag]'\n : '[new branch]';\n io.out(` * ${label.padEnd(17)} ${src.padEnd(14)} -> ${dst}`);\n } else if (u.kind === 'forced') {\n io.out(\n ` + ${(u.oldSha as string).slice(0, 7)}...${u.newSha.slice(0, 7)} ${src.padEnd(14)} -> ${dst} (forced update)`\n );\n } else {\n io.out(\n ` ${(u.oldSha as string).slice(0, 7)}..${u.newSha.slice(0, 7)} ${src.padEnd(14)} -> ${dst}`\n );\n }\n }\n io.out(`Downloaded ${written} object(s) (SHA-1 verified).`);\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'fetch', err);\n }\n}\n","/**\n * `rig fund` — drip devnet test funds to the active identity's wallet (#263).\n *\n * A FREE command: no relay, no client start, no nonce guard, no payment\n * channel — just the identity chain (RIG_MNEMONIC precedence, ./identity.ts)\n * to derive the chain address, and one HTTP POST to the devnet faucet\n * (`@toon-protocol/client`'s `fundWallet`: `POST {faucet}/api/request` for\n * EVM, `/api/solana/request`, `/api/mina/request` — body `{ address }`; the\n * faucet drips FIXED amounts, so there is no --amount).\n *\n * Faucet resolution mirrors the toon-clientd conventions\n * (client-mcp/src/daemon/config.ts — no import, keep in sync):\n * `TOON_CLIENT_FAUCET_URL` env → `faucetUrl` in the shared client config →\n * the deployed devnet faucet when the network IS (or is inferred as) devnet.\n * A configured `*.devnet.toonprotocol.dev` origin infers devnet even when\n * `network` still reads its `custom` default (#288). On any other network\n * there is no faucet: the command prints the derived wallet address(es) to\n * fund externally instead of failing silently.\n *\n * The drip is awaited synchronously (a CLI has no background): the Mina\n * faucet legitimately takes ~75s, so the per-chain timeout is generous\n * (daemon convention: 90s, mina 130s; `TOON_CLIENT_FAUCET_TIMEOUT_MS` /\n * config `faucetTimeoutMs` override).\n */\n\nimport { readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { emitCliError } from './errors.js';\nimport { resolveIdentity } from './identity.js';\nimport type { CliIo, IdentityReport } from './push.js';\nimport { renderIdentityLine } from './render.js';\n\n/**\n * The deployed devnet faucet — the same edge the e2e suite drips from\n * (`client-mcp/src/e2e/devnet.ts`). Used only when the configured network is\n * `devnet` and no explicit faucet URL is set.\n */\nexport const DEVNET_FAUCET_URL = 'https://faucet.devnet.toonprotocol.dev';\n\n/** Supported faucet chains (client `FaucetChain`). */\nconst CHAINS = ['evm', 'solana', 'mina'] as const;\ntype FundChain = (typeof CHAINS)[number];\n\nexport const FUND_USAGE = `Usage: rig fund [options]\n\nDrip devnet test funds to the active identity's wallet — free (the faucet\npays). The identity comes from RIG_MNEMONIC (env or a project .env) or the\n~/.toon-client keystore/config; the faucet from TOON_CLIENT_FAUCET_URL, the\nfaucetUrl config field, or the deployed devnet faucet when the network is\ndevnet — including when a configured *.devnet.toonprotocol.dev origin infers\nit. The faucet drips a FIXED amount per chain (there is no --amount). On a\nnetwork without a faucet, prints the wallet address(es) to fund externally\ninstead.\n\nOptions:\n --chain <chain> evm | solana | mina (default: TOON_CLIENT_CHAIN, the\n \\`chain\\` config field, else evm)\n --address <address> fund this address instead of the identity's own\n --json machine-readable envelope\n -h, --help show this help`;\n\n/** What `rig fund` needs from the command environment. */\nexport interface FundDeps {\n io: CliIo;\n env: NodeJS.ProcessEnv;\n /** Working directory (starts the project-local `.env` walk). */\n cwd: string;\n /** fetch used for the faucet call (tests inject; default global fetch). */\n fetchImpl?: typeof fetch;\n}\n\n/** The slice of the shared client config file `rig fund` consumes. */\ninterface FundConfigFile {\n network?: string;\n faucetUrl?: string;\n faucetTimeoutMs?: number;\n chain?: string;\n relayUrl?: string;\n proxyUrl?: string;\n btpUrl?: string;\n}\n\n/** `--json` envelope. */\ninterface FundJson {\n command: 'fund';\n identity: IdentityReport;\n /** True when a faucet drip was performed (and succeeded). */\n funded: boolean;\n network: string | null;\n chain: FundChain;\n address?: string;\n faucetUrl?: string;\n /** Raw faucet response body (shape is faucet-defined). */\n response?: unknown;\n /**\n * Set when `network` was inferred as `devnet` from a configured\n * `*.devnet.toonprotocol.dev` origin (#288) rather than an explicit\n * `TOON_CLIENT_NETWORK`/config value — carries the origin that triggered it.\n */\n inferredDevnetFrom?: string;\n /** Non-devnet path: the derived wallet addresses to fund externally. */\n addresses?: { evm: string | null; solana: string | null; mina: string | null };\n guidance?: string;\n}\n\n/** Hostname suffix of every shared-devnet edge (relay, proxy, faucet …). */\nconst SHARED_DEVNET_SUFFIX = '.devnet.toonprotocol.dev';\n\n/**\n * The first configured relay/uplink URL that points at the shared devnet\n * (`*.devnet.toonprotocol.dev`), if any. When the user's endpoints already\n * target the shared devnet but `network` still says `custom`, the fix for a\n * failed `rig fund` is `TOON_CLIENT_NETWORK=devnet` — NOT hunting for a\n * faucet URL (the #280 UX-study trap). Exported for tests.\n */\nexport function sharedDevnetOrigin(\n env: NodeJS.ProcessEnv,\n file: FundConfigFile\n): string | undefined {\n const candidates = [\n env['TOON_CLIENT_RELAY_URL'] ?? file.relayUrl,\n env['TOON_CLIENT_PROXY_URL'] ?? file.proxyUrl,\n env['TOON_CLIENT_BTP_URL'] ?? file.btpUrl,\n ];\n for (const url of candidates) {\n if (!url) continue;\n try {\n const { hostname } = new URL(url);\n if (\n hostname.endsWith(SHARED_DEVNET_SUFFIX) ||\n hostname === SHARED_DEVNET_SUFFIX.slice(1)\n ) {\n return url;\n }\n } catch {\n // junk URL — other commands surface that; fund only sniffs\n }\n }\n return undefined;\n}\n\n/**\n * Remediation for `rig fund` on a network without a faucet. Orders the\n * suggestions by likelihood (#280): the network preset FIRST — a fresh\n * config defaults to `custom`, and on the shared devnet the whole fix is\n * `TOON_CLIENT_NETWORK=devnet` — then the faucet-URL override for\n * self-hosted networks, then external funding. Exported for tests.\n */\nexport function noFaucetGuidance(\n network: string | undefined,\n devnetOrigin: string | undefined\n): string {\n const head = `no faucet is configured for network ${JSON.stringify(network ?? 'custom')}`;\n const external =\n 'To fund the wallet externally instead, send the settlement token plus ' +\n 'native gas to the address below for the chain your channels settle on.';\n if (devnetOrigin !== undefined) {\n return (\n `${head} — but your configured origin (${devnetOrigin}) looks like ` +\n 'the shared devnet. Set TOON_CLIENT_NETWORK=devnet (or \"network\": ' +\n '\"devnet\" in the client config) and re-run `rig fund` — no faucet ' +\n `URL is needed there. ${external}`\n );\n }\n return (\n `${head}. If you meant the shared devnet, set TOON_CLIENT_NETWORK=devnet ` +\n 'and re-run `rig fund` — no faucet URL is needed there. If this is a ' +\n 'self-hosted network with its own faucet, set TOON_CLIENT_FAUCET_URL ' +\n `(or the faucetUrl config field). ${external}`\n );\n}\n\nfunction readFundConfig(env: NodeJS.ProcessEnv): {\n file: FundConfigFile;\n configPath: string;\n} {\n const dir = env['TOON_CLIENT_HOME'] ?? join(homedir(), '.toon-client');\n const configPath = join(dir, 'config.json');\n try {\n return {\n file: JSON.parse(readFileSync(configPath, 'utf8')) as FundConfigFile,\n configPath,\n };\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { file: {}, configPath };\n }\n throw new Error(\n `failed to read client config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n}\n\n/** Run `rig fund`; returns the process exit code. */\nexport async function runFund(args: string[], deps: FundDeps): Promise<number> {\n const { io, env } = deps;\n\n let chainFlag: string | undefined;\n let addressFlag: string | undefined;\n let json = false;\n try {\n const { values } = parseArgs({\n args,\n options: {\n chain: { type: 'string' },\n address: { type: 'string' },\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (values.help) {\n io.out(FUND_USAGE);\n return 0;\n }\n chainFlag = values.chain;\n addressFlag = values.address;\n json = values.json ?? false;\n if (chainFlag !== undefined && !CHAINS.includes(chainFlag as FundChain)) {\n throw new Error(\n `--chain must be one of ${CHAINS.join(' | ')}, got ${JSON.stringify(chainFlag)}`\n );\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(FUND_USAGE);\n return 2;\n }\n\n try {\n const { file } = readFundConfig(env);\n const chain = (chainFlag ??\n env['TOON_CLIENT_CHAIN'] ??\n file.chain ??\n 'evm') as FundChain;\n if (!CHAINS.includes(chain)) {\n throw new Error(\n `configured settlement chain ${JSON.stringify(chain)} has no faucet — pass --chain ${CHAINS.join(' | ')}`\n );\n }\n const network = env['TOON_CLIENT_NETWORK'] ?? file.network;\n // A configured `*.devnet.toonprotocol.dev` origin means the shared devnet\n // even when `network` still reads its `custom` default (#288): the host\n // already encodes it, so infer devnet and let the faucet \"just work\"\n // instead of making the user also export TOON_CLIENT_NETWORK=devnet. An\n // EXPLICIT non-`custom` network stays authoritative — it is never coerced.\n const devnetOrigin = sharedDevnetOrigin(env, file);\n const inferredDevnet =\n devnetOrigin !== undefined &&\n (network === undefined || network === 'custom');\n const effectiveNetwork = inferredDevnet ? 'devnet' : network;\n const faucetUrl =\n env['TOON_CLIENT_FAUCET_URL'] ??\n file.faucetUrl ??\n (effectiveNetwork === 'devnet' ? DEVNET_FAUCET_URL : undefined);\n\n // ── Identity chain → wallet addresses (never the phrase) ────────────────\n const resolved = await resolveIdentity({\n env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n });\n const identity: IdentityReport = {\n pubkey: resolved.pubkey,\n source: resolved.source,\n sourceLabel: resolved.sourceLabel,\n };\n // Dynamic import: `@toon-protocol/client` is heavy; runs that fail\n // earlier (usage errors) never pay its startup cost.\n const client = await import('@toon-protocol/client');\n const derived = await client.deriveFullIdentity(\n resolved.mnemonic,\n resolved.accountIndex\n );\n const addresses = {\n evm: derived.evm.address || null,\n solana: derived.solana.publicKey || null,\n mina: derived.mina.publicKey || null,\n };\n\n // ── No faucet on this network: name the ACTUAL knob first (#280) ────────\n if (!faucetUrl) {\n const guidance = noFaucetGuidance(network, devnetOrigin);\n if (json) {\n io.emitJson({\n command: 'fund',\n identity,\n funded: false,\n network: network ?? null,\n chain,\n addresses,\n guidance,\n } satisfies FundJson);\n return 0;\n }\n io.out(renderIdentityLine(identity));\n io.out(guidance);\n io.out('Wallet addresses:');\n io.out(` evm ${addresses.evm ?? '(no key derived)'}`);\n io.out(` solana ${addresses.solana ?? '(no key derived)'}`);\n io.out(` mina ${addresses.mina ?? '(no key derived — optional mina-signer dependency missing)'}`);\n return 0;\n }\n\n // ── Devnet faucet drip ───────────────────────────────────────────────────\n const address = addressFlag ?? addresses[chain];\n if (!address) {\n throw new Error(\n `no ${chain} address could be derived for this identity — pass an ` +\n 'explicit --address (for mina, install the optional mina-signer dependency)'\n );\n }\n // Generous, chain-aware timeout (daemon convention): the drip is awaited\n // here, and a Mina drip routinely takes >75s server-side.\n const timeoutEnv = env['TOON_CLIENT_FAUCET_TIMEOUT_MS'];\n const timeout =\n timeoutEnv && Number.isFinite(Number(timeoutEnv))\n ? Number(timeoutEnv)\n : (file.faucetTimeoutMs ?? (chain === 'mina' ? 130_000 : 90_000));\n\n if (!json && inferredDevnet) {\n io.out(\n `Inferred network 'devnet' from the configured origin ${devnetOrigin} ` +\n `(network was ${JSON.stringify(network ?? 'custom')}). ` +\n 'Set TOON_CLIENT_NETWORK explicitly to override.'\n );\n }\n if (!json) {\n io.out(\n `Requesting ${chain} drip from ${faucetUrl} for ${address} …` +\n (chain === 'mina' ? ' (mina settles slowly; this can take ~2 minutes)' : '')\n );\n }\n const { response } = await client.fundWallet(faucetUrl, address, chain, {\n timeout,\n ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),\n });\n\n if (json) {\n io.emitJson({\n command: 'fund',\n identity,\n funded: true,\n network: effectiveNetwork ?? null,\n chain,\n address,\n faucetUrl,\n response,\n ...(inferredDevnet ? { inferredDevnetFrom: devnetOrigin } : {}),\n } satisfies FundJson);\n return 0;\n }\n io.out(`Faucet drip succeeded: ${chain} → ${address}`);\n io.out(renderIdentityLine(identity));\n io.out('Re-check with `rig balance` (a drip can take a few blocks to land).');\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'fund', err);\n }\n}\n","/**\n * Git passthrough (#250): any subcommand `rig` does not own is executed as\n * `git <argv...>` verbatim — `rig status`, `rig add -p`, `rig commit`,\n * `rig log --oneline`, `rig rebase -i`, everything.\n *\n * The child git runs with `stdio: 'inherit'` so interactive commands, pagers,\n * colors, and prompts behave exactly as if the user had typed `git` (no\n * capture, no buffering). The child's exit code is propagated verbatim; a\n * child killed by a signal maps to the shell convention 128+N. While the\n * child runs, rig ignores-and-forwards SIGINT/SIGTERM/SIGHUP so git (not\n * rig) decides the outcome of a Ctrl-C — e.g. `rebase -i` gets to clean up —\n * and rig then reports git's exit.\n */\n\nimport { spawn } from 'node:child_process';\nimport { constants as osConstants } from 'node:os';\n\nexport interface GitPassthroughOptions {\n /** Working directory for the git child (default: the rig process cwd). */\n cwd?: string;\n /** Environment for the git child (default: the rig process env). */\n env?: NodeJS.ProcessEnv;\n /** Write one line to stderr (missing-git error); default: process.stderr. */\n err?: (line: string) => void;\n}\n\n/** The passthrough seam `dispatch` uses; tests inject a fake. */\nexport type GitRunner = (\n argv: string[],\n options?: GitPassthroughOptions\n) => Promise<number>;\n\n/** Exit code when the system git binary cannot be found (shell convention). */\nexport const GIT_NOT_FOUND_EXIT = 127;\n\n/** Signals relayed to the git child while it runs. */\nconst RELAYED_SIGNALS: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP'];\n\n/** Shell-convention exit code for a child terminated by `signal`. */\nfunction signalExitCode(signal: NodeJS.Signals): number {\n const num = osConstants.signals[signal];\n return num === undefined ? 1 : 128 + num;\n}\n\n/**\n * Run system `git` with the exact argv tail, inheriting rig's stdio.\n * Resolves to the exit code rig should exit with; never rejects.\n */\nexport const runGitPassthrough: GitRunner = (argv, options = {}) => {\n const err =\n options.err ?? ((line: string) => process.stderr.write(`${line}\\n`));\n\n return new Promise<number>((resolve) => {\n const child = spawn('git', argv, {\n stdio: 'inherit',\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\n env: options.env ?? process.env,\n });\n\n // Terminal-generated signals (Ctrl-C) already reach the child through the\n // shared foreground process group; the handlers stop rig's default\n // die-on-signal so the child controls the outcome, and forward the signal\n // for the cases where only rig was targeted (`kill <rig-pid>`).\n const relay = new Map<NodeJS.Signals, () => void>();\n for (const signal of RELAYED_SIGNALS) {\n const handler = (): void => {\n child.kill(signal);\n };\n relay.set(signal, handler);\n process.on(signal, handler);\n }\n const restoreSignals = (): void => {\n for (const [signal, handler] of relay) process.removeListener(signal, handler);\n };\n\n child.on('error', (spawnErr: NodeJS.ErrnoException) => {\n restoreSignals();\n if (spawnErr.code === 'ENOENT') {\n err(\n `rig: git not found — \\`rig ${argv[0] ?? ''}\\` is not a rig command, so it is ` +\n 'passed through to the system `git`, which is not on your PATH. ' +\n 'Install git (https://git-scm.com) or fix your PATH.'\n );\n resolve(GIT_NOT_FOUND_EXIT);\n return;\n }\n err(`rig: failed to run git: ${spawnErr.message}`);\n resolve(1);\n });\n\n child.on('close', (code, signal) => {\n restoreSignals();\n resolve(signal !== null ? signalExitCode(signal) : (code ?? 1));\n });\n });\n};\n","/**\n * `rig init` — one-shot, idempotent repo setup (#248).\n *\n * Replaces the old \"config written as a side effect of the first push\":\n *\n * 1. verifies the working directory is inside a git repository (hints at\n * `git init` when not — never runs it);\n * 2. resolves the signing identity via the RIG_MNEMONIC precedence chain\n * (./identity.ts) and reports the SOURCE + derived pubkey (never the\n * phrase); a chain miss errors with all three remediation options;\n * 3. writes `toon.repoid` (default: repo directory basename; existing\n * value kept on re-runs; `--repo-id` overrides) and `toon.owner` (the\n * derived pubkey) to the repository's LOCAL git config — the mnemonic\n * itself is never written to git config or any repo file;\n * 4. reports the relay setup (#249): when the deprecated v0.1\n * `git config toon.relay` is set and no `origin` remote exists, it\n * MIGRATES the value to a real `origin` git remote (the old key stays\n * readable as a fallback and is removed in v0.3); when nothing is\n * configured it suggests `rig remote add origin <relay-url>` as the\n * follow-up step.\n *\n * Re-running updates and reports instead of erroring. `--json` emits a\n * machine-readable report. Free — nothing is published or paid.\n */\n\nimport { basename } from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { emitCliError, NotAGitRepositoryError } from './errors.js';\nimport {\n addGitRemote,\n listGitRemotes,\n readToonConfig,\n resolveRepoRoot,\n writeToonConfig,\n type GitRemoteInfo,\n} from './git-config.js';\nimport { resolveIdentity, type ResolvedIdentity } from './identity.js';\nimport type { CliIo } from './push.js';\nimport { isRelayUrl } from './remote.js';\nimport { renderIdentityLine } from './render.js';\n\nexport const INIT_USAGE = `Usage: rig init [options]\n\nSet up the current git repository for rig (one-shot, idempotent, free):\nresolves your identity (RIG_MNEMONIC env → project .env → ~/.toon-client\nkeystore/config), then writes toon.repoid and toon.owner to the repo's\nLOCAL git config. Re-running updates and reports; it never errors on an\nalready-initialized repo. The seed phrase is never written anywhere.\n\nThe follow-up step is adding a relay: \\`rig remote add origin <relay-url>\\`\n(a real git remote — \\`git remote -v\\` shows it). A deprecated v0.1\n\\`git config toon.relay\\` is migrated to the origin remote automatically\nwhen no origin exists (the old key stays readable and is removed in v0.3).\n\nOptions:\n --repo-id <id> repository id / NIP-34 d-tag (default: the existing\n toon.repoid, then the repo directory basename)\n --json machine-readable report\n -h, --help show this help`;\n\n/** Deps subset `rig init` needs (no publisher — init is free). */\nexport interface InitDeps {\n io: CliIo;\n env: NodeJS.ProcessEnv;\n cwd: string;\n /** Identity resolver seam (tests); defaults to the real chain. */\n resolveIdentityImpl?: typeof resolveIdentity;\n}\n\ninterface InitFlags {\n repoId?: string;\n json: boolean;\n help: boolean;\n}\n\nfunction parseInitArgs(args: string[]): InitFlags {\n const { values, positionals } = parseArgs({\n args,\n options: {\n 'repo-id': { type: 'string' },\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: false,\n });\n if (positionals.length > 0) {\n throw new Error(`rig init takes no positional arguments`);\n }\n const flags: InitFlags = {\n json: values.json ?? false,\n help: values.help ?? false,\n };\n const repoId = values['repo-id'];\n if (repoId !== undefined) {\n if (repoId.trim() === '') throw new Error('--repo-id must not be empty');\n flags.repoId = repoId;\n }\n return flags;\n}\n\n/** JSON envelope emitted by `rig init --json`. */\ninterface InitJsonOutput {\n command: 'init';\n repoRoot: string;\n repoId: string;\n /** `toon.owner` — the derived pubkey of the active identity. */\n owner: string;\n identity: {\n source: ResolvedIdentity['source'];\n sourceLabel: string;\n pubkey: string;\n };\n /** Deprecated `git config toon.relay` values (kept readable until v0.3). */\n relays: string[];\n /** True when any relay source is configured (origin remote or toon.relay). */\n relayConfigured: boolean;\n /** Configured git remotes (post-migration). */\n remotes: GitRemoteInfo[];\n /** The single relay URL of the `origin` remote, when it is one. */\n origin: string | null;\n /** True when this run migrated toon.relay to a new `origin` remote. */\n migratedToonRelay: boolean;\n /** What this run changed in git config (false = already up to date). */\n changed: { repoId: boolean; owner: boolean };\n}\n\n/** Run `rig init`; returns the process exit code. */\nexport async function runInit(args: string[], deps: InitDeps): Promise<number> {\n const { io, env } = deps;\n\n let flags: InitFlags;\n try {\n flags = parseInitArgs(args);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(INIT_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(INIT_USAGE);\n return 0;\n }\n\n try {\n // ── (a) Must be a git repository — hint, never auto-run git init ────────\n let repoRoot: string;\n try {\n repoRoot = await resolveRepoRoot(deps.cwd);\n } catch {\n throw new NotAGitRepositoryError(deps.cwd);\n }\n\n // ── (b) Identity chain: source + derived pubkey (never the phrase) ──────\n const identity = await (deps.resolveIdentityImpl ?? resolveIdentity)({\n env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n });\n\n // ── (c) Write toon.repoid / toon.owner to LOCAL git config ──────────────\n const existing = await readToonConfig(repoRoot);\n const repoId = flags.repoId ?? existing.repoId ?? basename(repoRoot);\n const changed = {\n repoId: existing.repoId !== repoId,\n owner: existing.owner !== identity.pubkey,\n };\n await writeToonConfig(repoRoot, { repoId, owner: identity.pubkey });\n\n // ── (d) Relay setup (#249): migrate toon.relay → origin remote ──────────\n // toon.relay is the deprecated v0.1 key. When it is set, single-valued,\n // relay-shaped, and no `origin` remote exists, adopt it as a real git\n // remote. The old key stays readable (paid commands still fall back to\n // it, with a nudge) and is removed in v0.3.\n let remotes = await listGitRemotes(repoRoot);\n let migratedToonRelay = false;\n const legacyRelay = existing.relays[0];\n if (\n !remotes.some((r) => r.name === 'origin') &&\n existing.relays.length === 1 &&\n legacyRelay !== undefined &&\n isRelayUrl(legacyRelay)\n ) {\n await addGitRemote(repoRoot, 'origin', legacyRelay);\n migratedToonRelay = true;\n remotes = await listGitRemotes(repoRoot);\n }\n const origin = remotes.find((r) => r.name === 'origin');\n const originRelay =\n origin !== undefined &&\n origin.urls.length === 1 &&\n isRelayUrl(origin.urls[0] as string)\n ? (origin.urls[0] as string)\n : undefined;\n\n // ── (e) Report ───────────────────────────────────────────────────────────\n if (flags.json) {\n const output: InitJsonOutput = {\n command: 'init',\n repoRoot,\n repoId,\n owner: identity.pubkey,\n identity: {\n source: identity.source,\n sourceLabel: identity.sourceLabel,\n pubkey: identity.pubkey,\n },\n relays: existing.relays,\n relayConfigured: originRelay !== undefined || existing.relays.length > 0,\n remotes,\n origin: originRelay ?? null,\n migratedToonRelay,\n changed,\n };\n io.emitJson(output);\n return 0;\n }\n\n io.out(`Initialized rig for ${repoRoot}`);\n io.out(renderIdentityLine(identity));\n io.out(\n ` toon.repoid = ${repoId}` +\n (changed.repoId ? '' : ' (unchanged)') +\n (existing.repoId && changed.repoId ? ` (was ${existing.repoId})` : '')\n );\n io.out(\n ` toon.owner = ${identity.pubkey}` +\n (changed.owner ? '' : ' (unchanged)') +\n (existing.owner && changed.owner ? ` (was ${existing.owner})` : '')\n );\n if (originRelay !== undefined) {\n io.out(\n ` origin = ${originRelay}` +\n (migratedToonRelay ? ' (migrated from git config toon.relay)' : '')\n );\n if (migratedToonRelay) {\n io.out(\n 'note: toon.relay is deprecated — it stays readable as a fallback ' +\n 'and is removed in v0.3; drop it now with ' +\n '`git config --unset-all toon.relay`.'\n );\n }\n io.out('Ready: `rig push` publishes this repo via remote \"origin\".');\n } else if (existing.relays.length > 0) {\n // toon.relay is set but could not be migrated (multi-valued, junk URL,\n // or a non-relay `origin` remote already occupies the name).\n io.out(` toon.relay = ${existing.relays.join(', ')} (deprecated)`);\n io.out(\n origin !== undefined\n ? `The \"origin\" remote (${origin.urls.join(', ')}) is not a single ` +\n 'relay URL, so toon.relay stays the fallback — add the relay ' +\n 'under another name (`rig remote add toon <relay-url>`) and ' +\n 'push with `rig push toon`.'\n : existing.relays.length > 1\n ? `toon.relay has ${existing.relays.length} values and rig ` +\n 'publishes to one relay — migrate the right one: ' +\n '`rig remote add origin <relay-url>`.'\n : 'This value is not a relay URL (ws://, wss://, http://, or ' +\n 'https://) — set a real one: `rig remote add origin <relay-url>`.'\n );\n } else if (origin !== undefined) {\n // The origin name is occupied by a non-relay remote (e.g. a GitHub\n // clone) and no legacy toon.relay exists.\n io.out(\n `No relay configured yet — \"origin\" (${origin.urls.join(', ')}) is ` +\n 'not a relay URL, so add the relay under another name: ' +\n '`rig remote add toon <relay-url>`, then `rig push toon`.'\n );\n } else {\n io.out(\n 'No relay configured yet — add one as the follow-up step: ' +\n '`rig remote add origin <relay-url>` (a real git remote; ' +\n '`git remote -v` shows it). One-off pushes can pass --relay <url>.'\n );\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, 'init', err);\n }\n}\n","/**\n * `rig maintainers list|add|remove <pubkey>` (#287) — manage the declared\n * maintainer set on a repo's kind:30617 announcement.\n *\n * Status authority is CONSUMER-side: rig and rig-web resolve an issue/PR's\n * state ONLY from kind:1630-1633 events signed by the repo owner ∪ its\n * declared maintainers. The owner is ALWAYS an implicit maintainer; this\n * command edits the EXPLICIT set carried by the `[\"maintainers\", …]` tag.\n *\n * list FREE relay read — print owner + declared maintainers\n * add <pubkey> PAID — republish the 30617 with <pubkey> added\n * remove <pubkey> PAID — republish the 30617 with <pubkey> removed\n *\n * add/remove republish the WHOLE announcement (a replaceable event keyed by\n * author + `d` tag), so they preserve the existing name/description and only\n * mutate the maintainers list. Because the 30617 is addressed by its author,\n * only the OWNER's republish is authoritative — running add/remove under a\n * non-owner identity writes that identity's own (irrelevant) announcement, so\n * we refuse it. The daemon has no announcement route, so this always runs the\n * embedded standalone publisher; the confirm gate matches every other paid\n * write (`--yes` skips; a non-TTY without it refuses; `--json` without `--yes`\n * is a pure estimate).\n */\n\nimport { parseArgs } from 'node:util';\nimport { buildRepoAnnouncement, parseMaintainers } from '../nip34-events.js';\nimport { ownerToHex } from '../npub.js';\nimport { fetchRemoteState } from '../remote-state.js';\nimport {\n serializeEventReceipt,\n type GitEventResponse,\n} from '../routes.js';\nimport type { EventCommandDeps } from './events.js';\nimport {\n emitCliError,\n InvalidRelayUrlError,\n UnconfiguredRepoAddressError,\n} from './errors.js';\nimport { readToonConfig, resolveRepoRoot } from './git-config.js';\nimport {\n defaultLoadStandalone,\n identityReport,\n type IdentityReport,\n} from './push.js';\nimport { feeLabel } from './render.js';\nimport {\n resolveRelays,\n singleRelayRefusal,\n type ResolvedRelays,\n} from './remote.js';\nimport type { StandaloneContext } from './standalone-context.js';\n\nconst HEX64_RE = /^[0-9a-f]{64}$/;\nconst WS_URL_RE = /^wss?:\\/\\//i;\n\nexport const MAINTAINERS_USAGE = `Usage: rig maintainers <list|add|remove> [<pubkey>] [options]\n\nManage a repo's declared maintainers (#287). Status authority is consumer-side:\nrig and rig-web honor an issue/PR status (kind:1630-1633) ONLY when its author\nis the repo owner or a declared maintainer. The owner is always an implicit\nmaintainer; this command edits the explicit set on the kind:30617 announcement.\n\nSubcommands:\n list show the owner + declared maintainers — FREE (relay read)\n add <pubkey> add a maintainer (npub or 64-char hex) — PAID: republishes\n the kind:30617 (permanent, non-refundable)\n remove <pubkey> remove a maintainer — PAID: republishes the kind:30617\n\nadd/remove must run under the repo OWNER's identity (only the owner's\nannouncement is authoritative).\n\nOptions:\n --repo-id <id> repository id / NIP-34 d-tag (default: git config)\n --owner <pubkey> repository owner (npub or hex; default: git config)\n --remote <name> publish/read via this configured git remote (default: origin)\n --relay <url> ad-hoc relay override (exactly one for add/remove)\n --yes skip the fee confirmation (required when not a TTY)\n --json machine-readable envelope\n -h, --help show this help`;\n\ninterface MaintFlags {\n json: boolean;\n yes: boolean;\n help: boolean;\n relay: string[];\n remote?: string;\n repoId?: string;\n owner?: string;\n}\n\nconst MAINT_OPTIONS = {\n json: { type: 'boolean', default: false },\n yes: { type: 'boolean', default: false },\n relay: { type: 'string', multiple: true },\n remote: { type: 'string' },\n 'repo-id': { type: 'string' },\n owner: { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n} as const;\n\nfunction pickFlags(values: Record<string, unknown>): MaintFlags {\n const flags: MaintFlags = {\n json: values['json'] === true,\n yes: values['yes'] === true,\n help: values['help'] === true,\n relay: Array.isArray(values['relay']) ? (values['relay'] as string[]) : [],\n };\n if (typeof values['remote'] === 'string') flags.remote = values['remote'];\n if (typeof values['repo-id'] === 'string') flags.repoId = values['repo-id'];\n if (typeof values['owner'] === 'string')\n flags.owner = ownerToHex(values['owner']);\n return flags;\n}\n\ninterface RepoContext {\n repoId: string;\n owner: string;\n relays: string[];\n /** The full relay resolution (source/nudge) — for the single-relay refusal. */\n resolved: ResolvedRelays;\n repoRoot?: string;\n}\n\n/** Resolve repo address (repoId + owner) and relays from flags + git config. */\nasync function resolveContext(\n flags: MaintFlags,\n deps: EventCommandDeps\n): Promise<RepoContext> {\n let repoRoot: string | undefined;\n let toonConfig: { repoId?: string; owner?: string; relays: string[] } = {\n relays: [],\n };\n try {\n repoRoot = await resolveRepoRoot(deps.cwd);\n toonConfig = await readToonConfig(repoRoot);\n } catch {\n // Not inside a git repo — flags must carry everything.\n }\n const repoId = flags.repoId ?? toonConfig.repoId;\n if (!repoId) throw new UnconfiguredRepoAddressError('repository id');\n const owner = flags.owner ?? toonConfig.owner;\n if (!owner) throw new UnconfiguredRepoAddressError('repository owner');\n\n const resolved = await resolveRelays({\n relayFlags: flags.relay,\n remoteName: flags.remote,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n if (resolved.nudge !== undefined) deps.io.err(resolved.nudge);\n return {\n repoId,\n owner,\n relays: resolved.relays,\n resolved,\n ...(repoRoot !== undefined ? { repoRoot } : {}),\n };\n}\n\n/** Run `rig maintainers …`; returns the process exit code. */\nexport async function runMaintainers(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n switch (sub) {\n case 'list':\n return runList(rest, deps);\n case 'add':\n return runMutate('add', rest, deps);\n case 'remove':\n return runMutate('remove', rest, deps);\n case '--help':\n case '-h':\n case 'help':\n io.out(MAINTAINERS_USAGE);\n return 0;\n default:\n io.err(\n sub === undefined\n ? 'missing subcommand: rig maintainers <list|add|remove>'\n : `unknown rig maintainers subcommand: ${sub}`\n );\n io.err(MAINTAINERS_USAGE);\n return 2;\n }\n}\n\n// ---------------------------------------------------------------------------\n// list (FREE)\n// ---------------------------------------------------------------------------\n\nasync function runList(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n let flags: MaintFlags;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: MAINT_OPTIONS,\n allowPositionals: true,\n });\n if (positionals.length > 0) {\n throw new Error('rig maintainers list takes no positional arguments');\n }\n flags = pickFlags(values);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(MAINTAINERS_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(MAINTAINERS_USAGE);\n return 0;\n }\n\n try {\n const ctx = await resolveContext(flags, deps);\n const wsRelays = ctx.relays.filter((url) => WS_URL_RE.test(url));\n if (wsRelays.length === 0) {\n throw new InvalidRelayUrlError(\n ctx.relays[0] ?? '',\n 'reads need a ws:// or wss:// relay'\n );\n }\n const remote = await fetchRemoteState({\n relayUrls: wsRelays,\n ownerPubkey: ctx.owner,\n repoId: ctx.repoId,\n ...(deps.webSocketFactory\n ? { webSocketFactory: deps.webSocketFactory }\n : {}),\n });\n const maintainers = remote.maintainers;\n if (flags.json) {\n io.emitJson({\n command: 'maintainers list',\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n announced: remote.announced,\n owner: ctx.owner,\n maintainers,\n });\n return 0;\n }\n io.out(`Repo: 30617:${ctx.owner}:${ctx.repoId}`);\n io.out(`Owner: ${ctx.owner} (implicit maintainer)`);\n if (!remote.announced) {\n io.out('No kind:30617 announcement found — owner-only authority.');\n return 0;\n }\n if (maintainers.length === 0) {\n io.out('Maintainers: (none declared — owner-only authority)');\n } else {\n io.out(`Maintainers (${maintainers.length}):`);\n for (const m of maintainers) io.out(` ${m}`);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, 'maintainers list', err);\n }\n}\n\n// ---------------------------------------------------------------------------\n// add / remove (PAID — republish the 30617 under the owner's identity)\n// ---------------------------------------------------------------------------\n\ninterface MaintJsonOutput {\n command: 'maintainers add' | 'maintainers remove';\n repoAddr: { ownerPubkey: string; repoId: string };\n identity: IdentityReport;\n executed: boolean;\n feeEstimate: string | null;\n maintainers: string[];\n result?: GitEventResponse;\n hint?: string;\n}\n\nasync function runMutate(\n op: 'add' | 'remove',\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const command = `maintainers ${op}` as\n | 'maintainers add'\n | 'maintainers remove';\n\n let flags: MaintFlags;\n let pubkey: string;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: MAINT_OPTIONS,\n allowPositionals: true,\n });\n flags = pickFlags(values);\n if (flags.help) {\n io.out(MAINTAINERS_USAGE);\n return 0;\n }\n if (positionals.length !== 1) {\n throw new Error(`expected exactly one <pubkey> to ${op}`);\n }\n pubkey = ownerToHex(positionals[0] as string).toLowerCase();\n if (!HEX64_RE.test(pubkey)) {\n throw new Error(`<pubkey> must resolve to 64-char hex (got ${JSON.stringify(positionals[0])})`);\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(MAINTAINERS_USAGE);\n return 2;\n }\n\n let standaloneCtx: StandaloneContext | undefined;\n try {\n const ctx = await resolveContext(flags, deps);\n // A single relay for a paid publish (mirror push/events guard).\n if (ctx.relays.length > 1) {\n io.err(singleRelayRefusal(ctx.resolved, 'Nothing was published or paid.'));\n return 1;\n }\n const relayUrl = ctx.relays[0];\n if (relayUrl === undefined || !WS_URL_RE.test(relayUrl)) {\n throw new InvalidRelayUrlError(\n relayUrl ?? '',\n 'a paid publish needs a ws:// or wss:// relay'\n );\n }\n\n // Standalone only: the daemon has no announcement route.\n const load = deps.loadStandalone ?? defaultLoadStandalone;\n standaloneCtx = await load({\n env: deps.env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n relayUrl,\n });\n const identity = identityReport(standaloneCtx);\n\n // Only the owner's 30617 is authoritative — refuse a non-owner republish.\n if (identity.pubkey.toLowerCase() !== ctx.owner.toLowerCase()) {\n io.err(\n `rig: only the repo owner (${ctx.owner.slice(0, 8)}…) can change the ` +\n `maintainer set — the active identity is ${identity.pubkey.slice(0, 8)}…. ` +\n 'A non-owner republish would write your own (ignored) announcement. ' +\n 'Nothing was published or paid.'\n );\n return 1;\n }\n\n // Read the current announcement to preserve name/description + base set.\n const remote = await fetchRemoteState({\n relayUrls: [relayUrl],\n ownerPubkey: ctx.owner,\n repoId: ctx.repoId,\n ...(deps.webSocketFactory\n ? { webSocketFactory: deps.webSocketFactory }\n : {}),\n });\n // Refuse on an unannounced repo: republishing here would MINT a phantom\n // kind:30617 with a placeholder name (= repoId) and empty description, for\n // real money. Worse, `rig push` only announces when the repo is NOT already\n // announced (see push.ts), so that placeholder would permanently shadow the\n // real name/description the first push intended, with no way to fix it.\n // Managing maintainers presupposes the repo exists — announce it first.\n if (!remote.announced) {\n io.err(\n `rig: 30617:${ctx.owner.slice(0, 8)}…:${ctx.repoId} has no announcement ` +\n 'yet — run `rig push` to publish the repo (with its real ' +\n 'name/description) before managing maintainers. Nothing was published ' +\n 'or paid.'\n );\n return 1;\n }\n const current = remote.announceEvent\n ? parseMaintainers(remote.announceEvent.tags)\n : [];\n const currentSet = new Set(current);\n if (op === 'add' && currentSet.has(pubkey)) {\n io.err(\n `rig: ${pubkey.slice(0, 8)}… is already a maintainer — nothing to do (not published).`\n );\n return 0;\n }\n if (op === 'remove' && !currentSet.has(pubkey)) {\n io.err(\n `rig: ${pubkey.slice(0, 8)}… is not a declared maintainer — nothing to do (not published).`\n );\n return 0;\n }\n const next =\n op === 'add'\n ? [...current, pubkey]\n : current.filter((m) => m !== pubkey);\n\n const name = remote.name ?? ctx.repoId;\n const description = remote.description ?? '';\n const event = buildRepoAnnouncement(ctx.repoId, name, description, next);\n const fee = (await standaloneCtx.publisher.getFeeRates()).eventFee.toString();\n const action = `kind:30617 maintainers ${op} ${pubkey.slice(0, 8)}…`;\n\n // ── Confirm gate ────────────────────────────────────────────────────────\n if (!flags.json) {\n io.out(`Republish ${action}`);\n io.out(`Repo: 30617:${ctx.owner}:${ctx.repoId}`);\n io.out(`Maintainers after: ${next.length === 0 ? '(none)' : next.join(', ')}`);\n io.out(`Fee: ${feeLabel(fee)}. Writes are permanent and non-refundable.`);\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n identity,\n executed: false,\n feeEstimate: fee,\n maintainers: next,\n hint: 'estimate only — re-run with --yes to publish (permanent, non-refundable)',\n } satisfies MaintJsonOutput);\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n 'refusing to spend channel funds without confirmation in a non-interactive ' +\n 'session — re-run with --yes (or use --json for an estimate)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Proceed with paid republish (${feeLabel(fee)})? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was published.');\n return 1;\n }\n }\n\n // ── Execute ───────────────────────────────────────────────────────────────\n const receipt = await standaloneCtx.publisher.publishEvent(event, [\n relayUrl,\n ]);\n const result = serializeEventReceipt(event.kind, receipt);\n\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n identity,\n executed: true,\n feeEstimate: fee,\n maintainers: next,\n result,\n } satisfies MaintJsonOutput);\n } else {\n io.out(\n `Published ${action}: ${result.eventId} paid ${result.feePaid} base units`\n );\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, command, err);\n } finally {\n if (standaloneCtx) {\n try {\n await standaloneCtx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n","/**\n * The rig CLI output layer (#265): the strict `--json` stdout guarantee.\n *\n * CONTRACT — when `--json` is set on a rig-owned command, stdout carries\n * EXACTLY ONE parseable JSON document and nothing else. Agents consume this\n * stream (`rig … --json | jq`), so any stray banner, progress line, warning,\n * deprecation nudge, or third-party `console.log` on stdout breaks pipelines\n * (the #260 addendum: `[Bootstrap] …` logs from the embedded client's core\n * polluted `rig push --json`). Everything human-facing goes to stderr.\n *\n * Three layers enforce the contract (composed in ./rig.ts; the enforcement\n * matrix in ./strict-json.test.ts mirrors that composition):\n *\n * 1. {@link makeCliIo} — the ONLY output surface commands use. In JSON mode\n * `out()` (human lines) reroutes to stderr and `emitJson()` is the sole\n * writer that reaches the real stdout.\n * 2. {@link redirectStdoutToStderr} — a process-level guard for code the io\n * seam cannot reach: dependencies that `console.log` directly (the\n * embedded `@toon-protocol/client`'s core bootstrap does). Installed\n * before any command code runs, it reroutes EVERY `process.stdout.write`\n * to stderr; only the writer it returns (wired into `emitJson`) still\n * reaches the real stdout.\n * 3. {@link RigIo.ensureSingleJsonDoc} — the backstop for paths that bail\n * out before emitting an envelope (usage errors, pre-payment refusals):\n * after dispatch it emits one error envelope built from the collected\n * stderr lines, so stdout is never empty in JSON mode.\n *\n * GIT PASSTHROUGH IS EXEMPT: `--json` is a per-subcommand flag on rig-owned\n * verbs, not a global rig flag. Any verb rig does not own goes to system git\n * with the EXACT argv tail and inherited stdio — `rig status --json` runs\n * `git status --json` (git rejects it), and flags BEFORE the subcommand\n * (`rig --json status`) are not rig's either: the whole argv passes through\n * to git verbatim. {@link isJsonInvocation} implements exactly that boundary.\n */\n\n// ---------------------------------------------------------------------------\n// The io seam\n// ---------------------------------------------------------------------------\n\n/** Terminal I/O seam — every rig-owned command writes ONLY through this. */\nexport interface CliIo {\n /**\n * One HUMAN-facing line: stdout normally, stderr when `--json` is active\n * (chatter must never pollute the machine stream).\n */\n out(line: string): void;\n /** One human-facing line to stderr (warnings, nudges, errors). */\n err(line: string): void;\n /**\n * THE machine-readable JSON document of a `--json` run — serialized here\n * (2-space indent) and written to the REAL stdout. Must be a command's\n * single stdout emission; call it at most once per invocation.\n */\n emitJson(payload: unknown): void;\n /** True when stdin+stdout are TTYs (interactive confirm possible). */\n isInteractive: boolean;\n /** Ask a y/N question; resolves true on explicit yes. */\n confirm(question: string): Promise<boolean>;\n}\n\n/** {@link CliIo} plus the JSON-mode bookkeeping the entrypoint needs. */\nexport interface RigIo extends CliIo {\n /** True when this invocation runs in `--json` mode. */\n readonly jsonMode: boolean;\n /** True once `emitJson` has written the machine document. */\n readonly emittedJson: boolean;\n /**\n * The #265 backstop: called once after dispatch (see ./rig.ts). In JSON\n * mode, when NO machine document was emitted (usage error, pre-payment\n * refusal, unexpected crash), emits one error envelope carrying the\n * human-facing lines the run wrote to stderr — so `--json` stdout always\n * parses. No-op outside JSON mode or after a real emission.\n */\n ensureSingleJsonDoc(exitCode: number): void;\n}\n\n/** Sinks + terminal facts {@link makeCliIo} builds a {@link RigIo} from. */\nexport interface CliIoOptions {\n /** Whether this invocation is a rig-owned command with `--json`. */\n jsonMode: boolean;\n /**\n * Write to the REAL stdout (in JSON mode: the pre-guard writer returned by\n * {@link redirectStdoutToStderr}). Receives full text including newlines.\n */\n writeStdout(text: string): void;\n /** Write to stderr. Receives full text including newlines. */\n writeStderr(text: string): void;\n isInteractive: boolean;\n confirm(question: string): Promise<boolean>;\n}\n\n/**\n * Build the {@link RigIo} for one invocation. Centralizes the #265 routing:\n * human lines → stderr in JSON mode, and `emitJson` as the only stdout path.\n */\nexport function makeCliIo(options: CliIoOptions): RigIo {\n const { jsonMode, writeStdout, writeStderr } = options;\n let emittedJson = false;\n /** Human lines collected in JSON mode — the backstop envelope's detail. */\n const humanLines: string[] = [];\n\n const toStderr = (line: string): void => {\n if (jsonMode) humanLines.push(line);\n writeStderr(`${line}\\n`);\n };\n\n return {\n jsonMode,\n get emittedJson() {\n return emittedJson;\n },\n out: (line) => {\n if (jsonMode) {\n toStderr(line);\n } else {\n writeStdout(`${line}\\n`);\n }\n },\n err: toStderr,\n emitJson: (payload) => {\n emittedJson = true;\n writeStdout(`${JSON.stringify(payload, null, 2)}\\n`);\n },\n isInteractive: options.isInteractive,\n confirm: options.confirm,\n ensureSingleJsonDoc(exitCode: number): void {\n if (!jsonMode || emittedJson) return;\n const detail =\n humanLines.join('\\n') ||\n (exitCode === 0\n ? 'the command produced no machine output'\n : 'the command failed before emitting machine output — see stderr');\n this.emitJson(\n exitCode === 0\n ? { error: null, exitCode, detail }\n : { error: 'error', exitCode, detail }\n );\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// JSON-mode detection (and the git-passthrough exemption)\n// ---------------------------------------------------------------------------\n\n/**\n * The verbs rig owns — everything else is `git <argv…>` verbatim. Must match\n * the ./dispatch.ts switch (dispatch.test.ts pins both directions).\n */\nexport const RIG_OWNED_VERBS: ReadonlySet<string> = new Set([\n 'init',\n 'remote',\n 'clone',\n 'fetch',\n 'push',\n 'issue',\n 'comment',\n 'pr',\n 'maintainers',\n 'channel',\n 'fund',\n 'balance',\n]);\n\n/**\n * True when this argv is a rig-owned command run with `--json` — the strict\n * stdout contract applies. Deliberately NOT true for:\n *\n * - non-owned verbs (`rig status --json` IS `git status --json`: inherited\n * stdio, git's own semantics, rig adds nothing);\n * - flags before the subcommand (`rig --json status`): rig has no global\n * flags besides help/--version, so the argv passes to git verbatim;\n * - `--json` after a bare `--` (parseArgs treats those tokens as\n * positionals, so rig's flag parsers never see it as a flag either).\n *\n * Mirrors a plain token scan rather than each command's full parseArgs\n * config: the one divergence is `--json` consumed as a STRING option's value\n * (e.g. `rig push --relay --json`) — a pathological invocation that ends up\n * with chatter on stderr and a backstop envelope on stdout, which still\n * honors the parse guarantee.\n */\nexport function isJsonInvocation(argv: string[]): boolean {\n const [verb, ...rest] = argv;\n if (verb === undefined || !RIG_OWNED_VERBS.has(verb)) return false;\n for (const arg of rest) {\n if (arg === '--') return false;\n if (arg === '--json') return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Process-level stdout guard (third-party console.log defense)\n// ---------------------------------------------------------------------------\n\n/** Handle on an installed stdout guard. */\nexport interface StdoutGuard {\n /** Write to the REAL stdout (bypasses the redirection). */\n write(text: string): void;\n /** Undo the patch (tests; the one-shot CLI process never needs it). */\n restore(): void;\n}\n\n/**\n * Reroute every `process.stdout.write` — including `console.log` from\n * dependencies rig cannot re-route at the io seam, like the embedded\n * client's `[Bootstrap] …` logs (#260) — to stderr. Returns the ONLY writer\n * that still reaches the real stdout; ./rig.ts wires it into\n * {@link makeCliIo}'s `writeStdout` so `emitJson` output is the single\n * survivor on the machine stream.\n *\n * @param realWrite Override the saved real-stdout writer (tests capture it);\n * defaults to the unpatched `process.stdout.write`.\n */\n// ---------------------------------------------------------------------------\n// Process-level stderr calmer (third-party bootstrap noise defense, #280)\n// ---------------------------------------------------------------------------\n\n/** Handle on an installed stderr calmer. */\nexport interface StderrCalmer {\n /** Undo the patch (tests; the one-shot CLI process never needs it). */\n restore(): void;\n}\n\n/** The embedded client's core self-announce failure log line. */\nconst ANNOUNCE_FAILED_RE = /\\[Bootstrap\\] Announce failed/;\n/** … specifically the EXPECTED pre-payment 402 refusal (x402 challenge). */\nconst ANNOUNCE_402_RE = /402|payment required/i;\n\n/**\n * The calm reframe of the announce-402: what happened, why it is expected,\n * and that the command is unaffected — instead of a full x402 challenge JSON\n * dump. Exported so tests pin the exact line.\n */\nexport const ANNOUNCE_402_INFO =\n 'rig: skipped the optional identity self-announce — the payment peer ' +\n 'charges for announces and this identity has not paid for one (expected ' +\n 'on a fresh or unfunded identity); harmless, the command continues.\\n';\n\n/**\n * Reframe the embedded client's scary-but-harmless bootstrap announce noise\n * (#280). The core's bootstrap tries a PAID self-announce and `console.warn`s\n * the refusal — `[Bootstrap] Announce failed …: … (402 Payment Required):\n * {…x402…}` — straight to stderr, which rig's io seam cannot reach. A\n * first-run user reads that as their (succeeding!) push having failed.\n *\n * This process-level guard patches `process.stderr.write`:\n *\n * - an announce-402 line becomes {@link ANNOUNCE_402_INFO} once per\n * process (repeats are dropped — one calm line, not one per peer);\n * - announce failures that are NOT the expected 402 (network errors, peer\n * misconfig) pass through untouched — those ARE signal;\n * - everything else passes through untouched.\n *\n * Installed unconditionally in ./rig.ts before dispatch. Composes with\n * {@link redirectStdoutToStderr}: that guard forwards to `process.stderr.write`\n * via a dynamic property lookup, so rerouted stdout noise is calmed too.\n */\nexport function calmBootstrapNoise(): StderrCalmer {\n const original = process.stderr.write;\n let reframed = false;\n const patched = ((\n chunk: Uint8Array | string,\n encodingOrCb?: BufferEncoding | ((err?: Error | null) => void),\n cb?: (err?: Error | null) => void\n ): boolean => {\n let text = chunk;\n if (typeof chunk === 'string' && ANNOUNCE_FAILED_RE.test(chunk)) {\n if (ANNOUNCE_402_RE.test(chunk)) {\n text = reframed ? '' : ANNOUNCE_402_INFO;\n reframed = true;\n }\n }\n return typeof encodingOrCb === 'function'\n ? original.call(process.stderr, text, encodingOrCb)\n : original.call(process.stderr, text, encodingOrCb, cb);\n }) as typeof process.stderr.write;\n process.stderr.write = patched;\n return {\n restore: () => {\n if (process.stderr.write === patched) process.stderr.write = original;\n },\n };\n}\n\nexport function redirectStdoutToStderr(\n realWrite?: (text: string) => void\n): StdoutGuard {\n const original = process.stdout.write;\n const real = realWrite ?? original.bind(process.stdout);\n const patched = ((\n chunk: Uint8Array | string,\n encodingOrCb?: BufferEncoding | ((err?: Error | null) => void),\n cb?: (err?: Error | null) => void\n ): boolean =>\n typeof encodingOrCb === 'function'\n ? process.stderr.write(chunk, encodingOrCb)\n : process.stderr.write(\n chunk,\n encodingOrCb,\n cb\n )) as typeof process.stdout.write;\n process.stdout.write = patched;\n return {\n write: (text) => {\n real(text);\n },\n restore: () => {\n if (process.stdout.write === patched) process.stdout.write = original;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAS,uBAAuB;;;ACHhC,SAAS,qBAAqB;;;ACR9B,SAAS,aAAAA,kBAAiB;;;AC4EnB,SAAS,cAAc,KAAgC;AAC5D,QAAM,MAAM,IAAI,uBAAuB;AACvC,QAAM,SAAS,MAAM,OAAO,GAAG,IAAI;AACnC,QAAM,OACJ,OAAO,SAAS,MAAM,KAAK,SAAS,IAAI,SAAS,kBAAkB;AACrE,SAAO,oBAAoB,IAAI;AACjC;AAOA,eAAsB,YACpB,KACA,WACA,YAAY,M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AA,IACA,eAAe,QAAQ,QAAQ,MAAM,SAAS,QAAQ,OAAO,KAAK;AAAA,IAClE,SAAS,OAAO,aAAa;AAC3B,YAAM,KAAK,gBAAgB;AAAA,QACzB,OAAO,QAAQ;AAAA,QACf,QAAQ,QAAQ;AAAA,MAClB,CAAC;AACD,UAAI;AACF,cAAM,UAAU,MAAM,GAAG,SAAS,QAAQ,GAAG,KAAK,EAAE,YAAY;AAChE,eAAO,WAAW,OAAO,WAAW;AAAA,MACtC,UAAE;AACA,WAAG,MAAM;AAAA,MACX;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAYA,SAAS,gBAAgB,MAAoB;AAC3C,UAAQ,WAAW;AACnB,MAAI,UAAU;AACd,QAAM,OAAO,MAAY;AACvB,eAAW;AACX,QAAI,YAAY,EAAG,SAAQ,KAAK,IAAI;AAAA,EACtC;AACA,UAAQ,OAAO,MAAM,IAAI,IAAI;AAC7B,UAAQ,OAAO,MAAM,IAAI,IAAI;AAC/B;AAEA,IAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,IAAM,KAAK,OAAO,iBAAiB,IAAI,CAAC;AAExC,SAAS,MAAM;AAAA,EACb;AAAA,EACA,KAAK,QAAQ;AAAA,EACb,KAAK,QAAQ,IAAI;AACnB,CAAC,EAAE;AAAA,EACD,CAAC,SAAS;AACR,OAAG,oBAAoB,IAAI;AAC3B,oBAAgB,IAAI;AAAA,EACtB;AAAA,EACA,CAAC,QAAiB;AAChB,YAAQ,OAAO;AAAA,MACb,0BAA0B,eAAe,QAAS,IAAI,SAAS,IAAI,UAAW,OAAO,GAAG,CAAC;AAAA;AAAA,IAC3F;AACA,OAAG,oBAAoB,CAAC;AACxB,oBAAgB,CAAC;AAAA,EACnB;AACF;","names":["parseArgs","io","parseArgs","io","parseArgs","io","io","parseArgs","parseArgs","io","parseArgs","result","parseArgs","parseArgs","io","parseArgs","REPOSITORY_ANNOUNCEMENT_KIND","STATUS_APPLIED_KIND","STATUS_CLOSED_KIND","STATUS_DRAFT_KIND","STATUS_OPEN_KIND","parseArgs","WS_URL_RE","repoATag","io","parseArgs","HEX64_RE","io","parseArgs","STATUS_OPEN_KIND","STATUS_APPLIED_KIND","STATUS_CLOSED_KIND","STATUS_DRAFT_KIND","REPOSITORY_ANNOUNCEMENT_KIND","args","parseArgs","WS_URL_RE","io","parseArgs","join","parseArgs","join","io","parseArgs","argv","resolve","basename","parseArgs","parseArgs","io","basename","parseArgs","HEX64_RE","WS_URL_RE","io","runList","parseArgs","require","argv","io","argv"]}
|