@toon-protocol/rig 2.0.0 → 2.1.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 +10 -3
- package/dist/chunk-3EKP7PMM.js +727 -0
- package/dist/chunk-3EKP7PMM.js.map +1 -0
- package/dist/{chunk-QD437XAW.js → chunk-CW4HJNMU.js} +2 -8
- package/dist/chunk-CW4HJNMU.js.map +1 -0
- package/dist/chunk-O6TXHKWG.js +217 -0
- package/dist/chunk-O6TXHKWG.js.map +1 -0
- package/dist/{chunk-G4W4MH6G.js → chunk-PLKZAUTG.js} +2 -1
- package/dist/chunk-PLKZAUTG.js.map +1 -0
- package/dist/cli/rig.js +1286 -398
- package/dist/cli/rig.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{publisher-CClD9OIZ.d.ts → publisher-Cdr1H1hg.d.ts} +1 -1
- package/dist/standalone/index.d.ts +404 -3
- package/dist/standalone/index.js +16 -2
- package/dist/standalone-mode-FCKTQ33Y.js +595 -0
- package/dist/standalone-mode-FCKTQ33Y.js.map +1 -0
- package/package.json +3 -11
- package/dist/chunk-G4W4MH6G.js.map +0 -1
- package/dist/chunk-QD437XAW.js.map +0 -1
- package/dist/chunk-XRRU6YBQ.js +0 -402
- package/dist/chunk-XRRU6YBQ.js.map +0 -1
- package/dist/standalone-mode-CAYWOURK.js +0 -111
- package/dist/standalone-mode-CAYWOURK.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/events.ts","../../src/cli/errors.ts","../../src/cli/git-config.ts","../../src/cli/push.ts","../../src/cli/render.ts","../../src/cli/remote.ts","../../src/cli/git-passthrough.ts","../../src/cli/init.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 *\n * Everything else is `git <argv...>` verbatim: `rig status` runs git status.\n */\n\nimport { createInterface } from 'node:readline/promises';\nimport { dispatch } from './dispatch.js';\nimport type { CliIo } from './push.js';\n\n/** Real terminal I/O: stdout lines, stderr lines, readline y/N confirm. */\nfunction makeIo(): CliIo {\n return {\n out: (line) => process.stdout.write(`${line}\\n`),\n err: (line) => process.stderr.write(`${line}\\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\ndispatch(process.argv.slice(2), {\n io: makeIo(),\n env: process.env,\n cwd: process.cwd(),\n}).then(\n (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 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, help/-h/--help,\n * and --version. EVERY other subcommand is executed as `git <argv...>`\n * verbatim (./git-passthrough.ts) — `rig status` IS `git status`, `rig add\n * -p`, `rig commit`, `rig rebase -i`, … all land in git with rig's stdio and\n * git's exit code. Owned verbs always win: `rig push` is the paid TOON push\n * and shadows `git push` (plain-git pushes stay available by calling `git\n * 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\nimport { createRequire } from 'node:module';\nimport { runComment, runIssue, runPr, type EventCommandDeps } from './events.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\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\\` and\n\\`rig remote\\` are free; the other rig commands are paid writes — permanent\nand non-refundable; each quotes its fee and asks for confirmation before\nspending (--yes skips, --json emits machine output).`;\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 '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 * 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 { describeError, 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 });\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.out(\n jsonOut({\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 })\n );\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.out(\n jsonOut({\n command,\n repoAddr: addr,\n identity,\n kind: result.kind,\n executed: true,\n feeEstimate: fee,\n result,\n })\n );\n } else {\n for (const line of renderEventReceipt(action, result)) io.out(line);\n }\n return 0;\n } catch (err) {\n const described = describeError(err, command);\n if (flags.json) {\n io.out(JSON.stringify({ command, ...described.json }, null, 2));\n } else {\n for (const line of described.lines) io.err(line);\n }\n return 1;\n } finally {\n if (standaloneCtx) {\n try {\n await standaloneCtx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n\nfunction jsonOut(output: EventJsonOutput): string {\n return JSON.stringify(output, null, 2);\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 * 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 optional `@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';\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\n return {\n code: 'error',\n lines: [`rig ${command} failed: ${message}`],\n json: { error: 'error', detail: message },\n };\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 * `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 { describeError, 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/** Terminal I/O seam. */\nexport interface CliIo {\n /** Write one line to stdout. */\n out(line: string): void;\n /** Write one line to stderr. */\n err(line: string): 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\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 optional `@toon-protocol/client` peer\n * dependency) only loads 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 });\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.out(\n jsonOut({ command: 'push', repoId, identity, executed: false, upToDate: true, plan })\n );\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.out(\n jsonOut({\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 })\n );\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.out(\n jsonOut({ command: 'push', repoId, identity, executed: true, upToDate: false, plan, result })\n );\n } else {\n for (const line of renderResult(result)) io.out(line);\n }\n return 0;\n } catch (err) {\n const described = describeError(err);\n if (flags.json) {\n io.out(JSON.stringify({ command: 'push', ...described.json }, null, 2));\n } else {\n for (const line of described.lines) io.err(line);\n }\n return 1;\n } finally {\n if (standaloneCtx) {\n try {\n await standaloneCtx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n\nfunction jsonOut(output: PushJsonOutput): string {\n return JSON.stringify(output, null, 2);\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 * 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 describeError,\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 output (list)\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.out(JSON.stringify({ command: 'remote', remotes }, null, 2));\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 io.err(\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 );\n return 1;\n }\n await addGitRemote(repoRoot, name, url);\n io.out(`Added remote ${name} → ${url}`);\n if (name === 'origin') {\n io.out(\n '`rig push` and the event commands now publish here by default.'\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 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 io.err(\n `no remote named ${JSON.stringify(name)} — ` +\n '`rig remote list` shows configured remotes.'\n );\n return 1;\n }\n await removeGitRemote(repoRoot, name);\n io.out(`Removed remote ${name}`);\n return 0;\n }\n\n /* v8 ignore next 2 -- unreachable: validated above */\n default:\n return 2;\n }\n } catch (err) {\n const described = describeError(err, 'remote');\n if (json) {\n io.out(JSON.stringify({ command: 'remote', ...described.json }, null, 2));\n } else {\n for (const line of described.lines) io.err(line);\n }\n return 1;\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 { describeError, 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.out(JSON.stringify(output, null, 2));\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 const described = describeError(err, 'init');\n if (flags.json) {\n io.out(JSON.stringify({ command: 'init', ...described.json }, null, 2));\n } else {\n for (const line of described.lines) io.err(line);\n }\n return 1;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAS,uBAAuB;;;ACAhC,SAAS,qBAAqB;;;ACY9B,SAAS,gBAAgB;AACzB,SAAS,aAAAA,kBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACDA,IAAM,+BAAN,cAA2C,MAAM;AAAA,EACtD,YAEkB,SAChB;AACA;AAAA,MACE,MAAM,OAAO,iMAGH,Y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,QAAQ,OAAO,MAAM,GAAG,IAAI;AAAA,CAAI;AAAA,IAC/C,KAAK,CAAC,SAAS,QAAQ,OAAO,MAAM,GAAG,IAAI;AAAA,CAAI;AAAA,IAC/C,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;AACF;AAEA,SAAS,QAAQ,KAAK,MAAM,CAAC,GAAG;AAAA,EAC9B,IAAI,OAAO;AAAA,EACX,KAAK,QAAQ;AAAA,EACb,KAAK,QAAQ,IAAI;AACnB,CAAC,EAAE;AAAA,EACD,CAAC,SAAS;AACR,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,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["parseArgs","parseArgs","parseArgs","jsonOut","parseArgs","parseArgs","parseArgs","require"]}
|
|
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,q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F,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"]}
|