@toon-protocol/rig 4.7.0 → 5.0.1
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 +31 -25
- package/dist/{chunk-J6Y3U645.js → chunk-2TG4YHEC.js} +59 -41
- package/dist/chunk-2TG4YHEC.js.map +1 -0
- package/dist/{chunk-3IVO2MSZ.js → chunk-4WVH2ITA.js} +3 -3
- package/dist/{chunk-U5A7MHBP.js → chunk-7VIVQHRG.js} +1 -1
- package/dist/chunk-7VIVQHRG.js.map +1 -0
- package/dist/{chunk-XQ2AWNHQ.js → chunk-CHVOXCDV.js} +0 -0
- package/dist/{chunk-XCLUB2CY.js → chunk-LMZSAFAB.js} +44 -15
- package/dist/chunk-LMZSAFAB.js.map +1 -0
- package/dist/{chunk-S3KKQ4IC.js → chunk-QKL53YZS.js} +2 -2
- package/dist/{chunk-UE5TAFEU.js → chunk-ZQGXFFBP.js} +4 -4
- package/dist/chunk-ZQGXFFBP.js.map +1 -0
- package/dist/{ci-serve-T33FCQVT.js → ci-serve-BU7NDT7O.js} +7 -7
- package/dist/cli/rig.js +6 -6
- package/dist/index.js +3 -3
- package/dist/standalone/index.d.ts +109 -74
- package/dist/standalone/index.js +13 -3
- package/dist/{standalone-mode-FY3XVQQK.js → standalone-mode-AT4S5EZG.js} +135 -49
- package/dist/standalone-mode-AT4S5EZG.js.map +1 -0
- package/package.json +2 -2
- package/dist/chunk-J6Y3U645.js.map +0 -1
- package/dist/chunk-U5A7MHBP.js.map +0 -1
- package/dist/chunk-UE5TAFEU.js.map +0 -1
- package/dist/chunk-XCLUB2CY.js.map +0 -1
- package/dist/standalone-mode-FY3XVQQK.js.map +0 -1
- /package/dist/{chunk-3IVO2MSZ.js.map → chunk-4WVH2ITA.js.map} +0 -0
- /package/dist/{chunk-XQ2AWNHQ.js.map → chunk-CHVOXCDV.js.map} +0 -0
- /package/dist/{chunk-S3KKQ4IC.js.map → chunk-QKL53YZS.js.map} +0 -0
- /package/dist/{ci-serve-T33FCQVT.js.map → ci-serve-BU7NDT7O.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/render.ts","../src/cli/push.ts","../src/rig-pointer.ts","../src/cli/rig-pointer-record.ts","../src/cli/repo-command.ts","../src/cli/dispatch.ts","../src/cli/balance.ts","../src/cli/chain.ts","../src/cli/channel.ts","../src/cli/ci.ts","../src/cli/clone.ts","../src/cli/events.ts","../src/cli/tracker.ts","../src/cli/entry.ts","../src/cli/fetch.ts","../src/cli/fund.ts","../src/cli/git-passthrough.ts","../src/cli/identity-cmd.ts","../src/cli/init.ts","../src/cli/git-author.ts","../src/cli/maintainers.ts","../src/cli/refresh.ts","../src/cli/name.ts","../src/cli/payout.ts","../src/cli/site.ts","../src/arweave-manifest.ts","../src/cli/site-record.ts"],"sourcesContent":["/**\n * Human-facing rendering for `rig push` and the kind:30617 republishes: the\n * pre-push confirm table, the post-push receipts, and the tag diff a paid\n * announcement republish shows before it asks. Machine consumers use `--json`\n * instead (the raw wire shapes from ../routes.ts) — nothing here is meant to\n * be parsed.\n */\n\nimport type { AnnouncementDiff } from '../repo-announcement.js';\nimport type {\n GitEstimateResponse,\n GitEventResponse,\n GitPushResponse,\n GitRefUpdate,\n GitRepoAddr,\n} from '../routes.js';\n\n/**\n * One indented line per changed tag of a kind:30617 republish — `-` for what\n * goes, `+` for what arrives (#158). This is what the owner reads before\n * confirming the fee, so it shows whole tags, values included.\n */\nexport function describeAnnouncementDiff(diff: AnnouncementDiff): string[] {\n return [\n ...diff.removed.map((tag) => ` - ${tag.join(' ')}`),\n ...diff.added.map((tag) => ` + ${tag.join(' ')}`),\n ];\n}\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 const emptySkipped = est.skippedEmptyCount ?? 0;\n lines.push(\n `Objects: ${est.objectCount} to upload` +\n ` (${formatNumber(est.totalObjectBytes)} bytes)` +\n (skipped > 0 ? `; ${skipped} already on Arweave (free)` : '') +\n (emptySkipped > 0\n ? `; ${emptySkipped} empty blob${emptySkipped === 1 ? '' : 's'} skipped ` +\n '(reconstructed on clone)'\n : '')\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 const emptySkipped = result.estimate.skippedEmptyCount ?? 0;\n if (emptySkipped > 0) {\n lines.push(\n `Empty blobs: ${emptySkipped} skipped (zero-byte, not uploaded — ` +\n 'reconstructed on clone).'\n );\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 * `rig push [remote] [refspecs...]` — estimate → confirm → execute (#229,\n * standalone since #248, git-like remote resolution since #249,\n * daemon-as-accelerator since #279).\n *\n * STANDALONE is the default and the guarantee: plan locally (`planPush`) and\n * execute through the embedded, nonce-guarded StandalonePublisher (loaded\n * via dynamic import so runs that fail earlier never need\n * `@toon-protocol/client`). The identity comes from the RIG_MNEMONIC\n * precedence chain (./identity.ts).\n *\n * DAEMON FAST PATH (#279, ./daemon-session.ts): when a running toon-clientd\n * holds the SAME identity, the whole estimate→push pipeline is delegated to\n * its loopback `/git/estimate` + `/git/push` routes instead of refusing —\n * the daemon already owns the channel watermark and its bootstrap is warm,\n * so the command finishes in seconds. A daemon on a different identity, or\n * no daemon, runs standalone. The chosen path prints to stderr and lands in\n * the `--json` envelope as `path`.\n *\n * Repo addressing comes from the `toon.*` git config keys `rig init` writes\n * (`--repo-id` overrides); an unconfigured repo is a hard \"run `rig init`\n * first\" error — nothing is written as a side effect of pushing.\n *\n * The relay comes from the repo's git remotes (#249): when the first\n * positional matches a configured remote name it is the push target,\n * otherwise it is a refspec and the remote defaults to `origin`. `--relay`\n * is an ad-hoc override that bypasses remotes (all positionals are then\n * refspecs); the deprecated v0.1 `git config toon.relay` still works with a\n * migration nudge. See ./remote.ts for the full resolution order.\n *\n * Money is only spent after the confirm gate: `--yes`, or an interactive\n * y/N prompt (a non-TTY session without `--yes` refuses). `--json` emits the\n * wire-shaped plan/receipts for agent consumers; without `--yes` it becomes\n * a pure estimate (plan JSON, nothing executed, exit 0).\n */\n\nimport { createHash } from 'node:crypto';\nimport { parseArgs } from 'node:util';\nimport {\n DEFAULT_RIG_WEB_BUNDLE,\n DEFAULT_RIG_WEB_GATEWAY,\n DEFAULT_RIG_WEB_URL,\n RIG_WEB_ENTRY_CSS_ENV,\n RIG_WEB_GATEWAY_ENV,\n RIG_WEB_ENTRY_JS_ENV,\n RIG_WEB_TX_ENV,\n RIG_WEB_URL_ENV,\n generateRigPointerHtml,\n repoWebUrl,\n} from '../rig-pointer.js';\nimport { PREFERRED_GATEWAY, mirrorGatewaysFor } from '../gateway-preference.js';\nimport { hexToNpub } from '../npub.js';\nimport { planPush, executePush } from '../push.js';\nimport { GitRepoReader } from '../repo-reader.js';\nimport {\n readRigPointerRecord,\n writeRigPointerRecord,\n} from './rig-pointer-record.js';\nimport { renderIdentityLine, renderPlan, renderResult } from './render.js';\nimport {\n serializePushPlan,\n serializePushResult,\n type GitEstimateResponse,\n type GitPushResponse,\n} from '../routes.js';\nimport { uploadChargeFor, type FeeRates } from '../publisher.js';\nimport {\n resolvePaidSession,\n type PaidSession,\n type ProbeDaemon,\n type SessionPath,\n} from './daemon-session.js';\nimport { RIG_STANDALONE_ENV } from '../standalone/nonce-guard.js';\nimport { emitCliError, UnconfiguredRepoAddressError } from './errors.js';\nimport {\n listGitRemotes,\n readToonConfig,\n resolveRepoRoot,\n} from './git-config.js';\nimport type { IdentitySourceKind } from './identity.js';\nimport { resolveRelays, singleRelayRefusal } from './remote.js';\nimport type {\n LoadStandalone,\n StandaloneContext,\n} from './standalone-context.js';\n\n// ---------------------------------------------------------------------------\n// Dependency seam (real wiring in rig.ts; tests inject fakes)\n// ---------------------------------------------------------------------------\n\n/**\n * Terminal I/O seam — lives in ./output.ts since #265 (the strict `--json`\n * stdout layer); re-exported here because every command module historically\n * imports it from push.ts.\n */\nexport type { CliIo } from './output.js';\nimport type { CliIo } from './output.js';\n\nexport interface PushDeps {\n io: CliIo;\n env: NodeJS.ProcessEnv;\n cwd: string;\n /** Standalone factory; defaults to the real dynamic-import loader. */\n loadStandalone?: LoadStandalone;\n /** Fetch for the daemon probe + delegated `/git/*` requests (tests). */\n fetchImpl?: typeof fetch;\n /** Daemon `/status` probe override (tests fake the loopback daemon). */\n probeDaemon?: ProbeDaemon;\n}\n\n/**\n * Return deps with the force-standalone override switched on — the\n * `--standalone` / `--no-daemon` per-command flag, equivalent to running with\n * `RIG_STANDALONE=1` in the environment. Every paid path reads the override\n * from `env` ({@link standaloneForced}), so injecting it here makes the flag\n * bypass the daemon for both session resolution and the embedded publisher's\n * guard. Generic so the event commands keep their extra deps.\n */\nexport function withForcedStandalone<D extends PushDeps>(deps: D): D {\n return { ...deps, env: { ...deps.env, [RIG_STANDALONE_ENV]: '1' } };\n}\n\n/**\n * Resolve the paid session for a command from its deps (#279): probe for a\n * same-identity toon-clientd (→ delegate) before falling back to the\n * standalone loader. Shared by push and the single-event commands.\n */\nexport function loadPaidSession(\n deps: PushDeps,\n relayUrl: string | undefined\n): Promise<PaidSession> {\n return resolvePaidSession({\n env: deps.env,\n cwd: deps.cwd,\n warn: (line) => deps.io.err(line),\n loadStandalone: deps.loadStandalone ?? defaultLoadStandalone,\n ...(relayUrl !== undefined ? { relayUrl } : {}),\n ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),\n ...(deps.probeDaemon ? { probeDaemon: deps.probeDaemon } : {}),\n });\n}\n\n/**\n * Default standalone factory (shared by every paid command). Dynamic import:\n * `standalone-mode` (and its `@toon-protocol/client` dependency) only loads\n * once a command actually needs to sign or pay.\n */\nexport const defaultLoadStandalone: LoadStandalone = async (options) => {\n const mod = await import('./standalone-mode.js');\n return mod.createStandaloneContext(options);\n};\n\n/** Identity report shared by every paid command's `--json` envelope. */\nexport interface IdentityReport {\n /** Derived Nostr pubkey (hex) of the active identity. */\n pubkey: string;\n /** Which tier of the RIG_MNEMONIC precedence chain supplied it. */\n source: IdentitySourceKind;\n /** Human-facing source label, e.g. `RIG_MNEMONIC env` or a file path. */\n sourceLabel: string;\n}\n\n/** Build the identity report of a loaded standalone context. */\nexport function identityReport(ctx: StandaloneContext): IdentityReport {\n return {\n pubkey: ctx.ownerPubkey,\n source: ctx.identitySource,\n sourceLabel: ctx.identitySourceLabel,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Usage\n// ---------------------------------------------------------------------------\n\nexport const PUSH_USAGE = `Usage: rig push [remote] [refspecs...] [options]\n\nPush local git refs to TOON: uploads the object delta to Arweave (paid) and\npublishes the NIP-34 refs event (kind:30618; kind:30617 announce on first\npush). Writes are permanent and non-refundable.\n\nThe repo must be set up once with \\`rig init\\` (writes toon.repoid/toon.owner\nto the local git config); the identity comes from RIG_MNEMONIC (env or a\nproject .env), or the ~/.toon-client keystore/config.\n\nThe relay is a git remote: \\`rig push\\` publishes via \"origin\" (set up with\n\\`rig remote add origin <relay-url>\\`); \\`rig push <remote> [refspecs...]\\`\npublishes via a named remote. When the first positional matches a configured\nremote name it is the remote; otherwise it is a refspec and the remote\ndefaults to origin. Refspecs are branch/tag names or full refnames; default\nis the current branch.\n\nEvery push also keeps the repo's RIG PAGE current: a permanent Arweave\npage that RENDERS this repo in place — it boots the FULL Rig (rig-web)\nfrom its Arweave deployment with this repo pinned, everything served from\nArweave + the relay. The pointer is content-addressed, so it is paid for\nonce and reused for free until the relay or Rig deployment changes.\n--no-rig-page skips it.\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 --no-rig-page skip the Rig-page pointer upload for this push\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 --standalone always run embedded, bypassing a running toon-clientd\n (alias: --no-daemon). Same as RIG_STANDALONE=1 — set that\n env var to make it the durable default\n -h, --help show this help`;\n\n// ---------------------------------------------------------------------------\n// Refspec selection\n// ---------------------------------------------------------------------------\n\n/**\n * Build the \"no such local ref\" error: name the missing ref, then point at the\n * current branch (with a `did you mean` using the real branch name) or, when\n * HEAD is detached/unborn, list the local branches. This is deliberately NOT\n * the ref-deletion guard — a branch that simply doesn't exist is the common\n * case (e.g. the docs say `main` but the repo is on `master`), and mentioning\n * \"ref deletion\" there is a confusing red herring.\n */\nfunction noSuchRefMessage(\n spec: string,\n head: string | undefined,\n refs: readonly { refname: string }[],\n remoteName: string\n): string {\n const branches = refs\n .filter((r) => r.refname.startsWith('refs/heads/'))\n .map((r) => r.refname.slice('refs/heads/'.length));\n const current =\n head && head.startsWith('refs/heads/')\n ? head.slice('refs/heads/'.length)\n : undefined;\n let msg = `no local branch or tag ${JSON.stringify(spec)}`;\n if (current) {\n msg +=\n ` — your current branch is ${JSON.stringify(current)} ` +\n `(did you mean \\`rig push ${remoteName} ${current}\\`?)`;\n } else if (branches.length > 0) {\n msg += ` — local branches: ${branches.join(', ')}`;\n } else {\n msg += ' — this repository has no branches yet (make a commit first)';\n }\n return msg;\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 * `remoteName` (default `origin`) only shapes the `did you mean` hint on a\n * missing ref.\n */\nexport async function selectRefspecs(\n reader: GitRepoReader,\n positionals: string[],\n all: boolean,\n tags: boolean,\n remoteName = 'origin'\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 if (spec.startsWith(':')) {\n // git deletion syntax (`rig push origin :branch`) — the one case where\n // \"out of scope in v1\" genuinely applies.\n throw new Error(\n `deleting remote refs (${JSON.stringify(spec)}) is out of scope in v1`\n );\n } else {\n throw new Error(noSuchRefMessage(spec, head, refs, remoteName));\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 /** Deploy/refresh the per-repo Rig page (default; --no-rig-page skips). */\n rigPage: boolean;\n yes: boolean;\n json: boolean;\n relay: string[];\n repoId?: string;\n /** Force embedded standalone, bypassing the daemon (--standalone/--no-daemon). */\n standalone: boolean;\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 'no-rig-page': { 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 standalone: { type: 'boolean', default: false },\n 'no-daemon': { type: 'boolean', default: false },\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 rigPage: !(values['no-rig-page'] ?? false),\n yes: values.yes ?? false,\n json: values.json ?? false,\n relay: values.relay ?? [],\n standalone: (values.standalone ?? false) || (values['no-daemon'] ?? false),\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// ---------------------------------------------------------------------------\n// Rig pointer (per-repo Rig page — see ../rig-pointer.ts)\n// ---------------------------------------------------------------------------\n\n/** The Rig-pointer step resolved for THIS push, before the confirm gate. */\ninterface RigPointerPlan {\n /** 'upload' pays for a (new/changed) pointer; 'unchanged' reuses for free. */\n action: 'upload' | 'unchanged';\n html: string;\n contentHash: string;\n bytes: number;\n /** Fee for the upload action, base units (0n when unchanged). */\n fee: bigint;\n /** Recorded txId (unchanged action only). */\n recordedTxId?: string;\n}\n\n/** Rig-page report in receipts / the `--json` envelope. */\nexport interface RigPageReport {\n /** What happened: fresh upload, free reuse, or skipped (flag/daemon path). */\n status: 'published' | 'unchanged' | 'skipped';\n txId?: string;\n /** Permanent pointer URL on the preferred ar.io gateway. */\n url?: string;\n feePaid?: string;\n detail?: string;\n}\n\n/**\n * Gateway for printed Rig-page URLs: the shared list's first MAINNET gateway\n * ({@link PREFERRED_GATEWAY} — never ar.io's testnet), `RIG_ARWEAVE_GATEWAY`\n * overriding, same as `rig site`. Distinct from the BUNDLE gateway embedded in\n * the pointer HTML ({@link DEFAULT_RIG_WEB_GATEWAY}), which tracks where the\n * rig-web deploy lives.\n */\nfunction pointerGateway(env: NodeJS.ProcessEnv): string {\n return (env['RIG_ARWEAVE_GATEWAY'] ?? PREFERRED_GATEWAY).replace(/\\/+$/, '');\n}\n\n/**\n * Every OTHER gateway from the shared list, printed under the primary.\n *\n * All of them, not just one: a gateway can be flat DOWN, not merely behind.\n * Observed 2026-08-15 — `ar-io.dev` answered `503` on its own root while the\n * page was live and byte-identical on both other gateways, and a single\n * printed alternate is one outage away from leaving the reader with no\n * working link and the impression their push failed.\n */\nfunction mirrorGateways(primary: string): string[] {\n return mirrorGatewaysFor(primary);\n}\n\n/** Build the Rig-pointer plan: deterministic pointer + content-addressed skip. */\nfunction planRigPointer(args: {\n env: NodeJS.ProcessEnv;\n ownerPubkey: string;\n repoId: string;\n relay: string;\n /** The store route's terms; the pointer's upload is priced by its size. */\n feeRates: FeeRates;\n}): RigPointerPlan {\n const html = generateRigPointerHtml({\n bundle: {\n manifestTx: args.env[RIG_WEB_TX_ENV] ?? DEFAULT_RIG_WEB_BUNDLE.manifestTx,\n entryJs: args.env[RIG_WEB_ENTRY_JS_ENV] ?? DEFAULT_RIG_WEB_BUNDLE.entryJs,\n entryCss:\n args.env[RIG_WEB_ENTRY_CSS_ENV] ?? DEFAULT_RIG_WEB_BUNDLE.entryCss,\n },\n gateway: (args.env[RIG_WEB_GATEWAY_ENV] ?? DEFAULT_RIG_WEB_GATEWAY).replace(\n /\\/+$/,\n ''\n ),\n rigWebUrl: args.env[RIG_WEB_URL_ENV] ?? DEFAULT_RIG_WEB_URL,\n relay: args.relay,\n ownerNpub: hexToNpub(args.ownerPubkey),\n repoId: args.repoId,\n });\n const contentHash = createHash('sha256').update(html).digest('hex');\n const bytes = Buffer.byteLength(html);\n const record = readRigPointerRecord(args.env, args.repoId);\n if (\n record &&\n record.contentHash === contentHash &&\n record.owner === args.ownerPubkey\n ) {\n return {\n action: 'unchanged',\n html,\n contentHash,\n bytes,\n fee: 0n,\n recordedTxId: record.pointerTxId,\n };\n }\n return {\n action: 'upload',\n html,\n contentHash,\n bytes,\n fee: uploadChargeFor(args.feeRates, bytes),\n };\n}\n\n/** JSON envelope emitted by `--json` runs (agents consume this). */\ninterface PushJsonOutput {\n command: 'push';\n repoId: string;\n /** Which transport paid: delegated daemon or embedded standalone (#279). */\n path: SessionPath;\n /** Active identity: source tier + derived pubkey (never the phrase). */\n identity: IdentityReport;\n /** True when the paid execute step ran. */\n executed: boolean;\n /** True when every selected ref already matched the remote (no-op). */\n upToDate: boolean;\n plan: GitEstimateResponse;\n result?: GitPushResponse;\n /** Per-repo Rig-page outcome (absent on estimates / early exits). */\n rigPage?: RigPageReport;\n hint?: string;\n}\n\n/** Run `rig push`; returns the process exit code. */\nexport async function runPush(args: string[], deps: PushDeps): Promise<number> {\n const { io } = deps;\n\n let flags: PushFlags;\n try {\n flags = parsePushArgs(args);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(PUSH_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(PUSH_USAGE);\n return 0;\n }\n // --standalone/--no-daemon: force embedded, bypassing any running daemon\n // (same as RIG_STANDALONE=1 for this one invocation).\n if (flags.standalone) deps = withForcedStandalone(deps);\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 remoteName ?? 'origin'\n );\n\n // ── Relay resolution (#249: --relay > named remote > origin > toon.relay)\n const resolved = await resolveRelays({\n relayFlags: flags.relay,\n remoteName,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n if (resolved.nudge !== undefined) io.err(resolved.nudge);\n const relaysUsed = resolved.relays;\n // StandalonePublisher publishes to exactly one relay (its publishEvent\n // throws on >1). Multiple relays can arrive here without explicit intent\n // (repeated --relay flags, an old multi-valued git config `toon.relay`).\n // Refuse up front, before anything is fetched, uploaded, or paid.\n if (relaysUsed.length > 1) {\n io.err(singleRelayRefusal(resolved, 'Nothing was uploaded or paid.'));\n return 1;\n }\n\n // ── Paid session (#279): same-identity daemon → delegate; else the\n // standalone context (identity chain + nonce guard).\n const session = await loadPaidSession(deps, relaysUsed[0]);\n const path = session.path;\n let identity: IdentityReport;\n if (session.path === 'standalone') {\n standaloneCtx = session.ctx;\n identity = identityReport(standaloneCtx);\n } else {\n identity = session.identity;\n }\n\n if (toonConfig.owner && toonConfig.owner !== identity.pubkey) {\n io.err(\n `warning: git config toon.owner (${toonConfig.owner.slice(0, 8)}…) differs from ` +\n `the active identity (${identity.pubkey.slice(0, 8)}…) — this push publishes ` +\n \"under the ACTIVE identity's repo namespace, not the configured owner's. \" +\n 'Re-run `rig init` to adopt the active identity.'\n );\n }\n\n // #158: a FIRST announcement links to the repo's rig-web viewer — the SAME\n // URL the Rig pointer falls back to, under the ACTIVE identity, which is\n // the pubkey the announcement is addressed by on both paths. It needs a\n // relay, so a push with none resolved announces without a `web` tag.\n const announcement =\n relaysUsed[0] === undefined\n ? undefined\n : {\n web: repoWebUrl({\n env: deps.env,\n relay: relaysUsed[0],\n ownerPubkey: identity.pubkey,\n repoId,\n }),\n };\n\n // ── Estimate ────────────────────────────────────────────────────────────\n // Standalone plans locally; the daemon path delegates the plan to\n // `POST /git/estimate` (same wire shape — ../routes.ts).\n let plan: GitEstimateResponse;\n let execute: () => Promise<GitPushResponse>;\n let pointerPlan: RigPointerPlan | undefined;\n let rigPageSkipDetail: string | undefined;\n if (session.path === 'standalone') {\n const ctx = session.ctx;\n const remoteState = await ctx.fetchRemote({\n ownerPubkey: ctx.ownerPubkey,\n repoId,\n relayUrls: relaysUsed,\n });\n const feeRates = await ctx.publisher.getFeeRates();\n const pushPlan = await planPush({\n repoReader: reader,\n remoteState,\n feeRates,\n repoId,\n refs: refspecs,\n force: flags.force,\n ...(announcement ? { announcement } : {}),\n });\n plan = serializePushPlan(pushPlan);\n execute = async () =>\n serializePushResult(\n pushPlan,\n await executePush({\n plan: pushPlan,\n publisher: ctx.publisher,\n remoteState,\n repoReader: reader,\n relayUrls: relaysUsed,\n })\n );\n // ── Rig page (the repo's rig-web page) — planned BEFORE the\n // confirm gate so its fee is part of what the user approves.\n if (!flags.rigPage) {\n rigPageSkipDetail = 'skipped (--no-rig-page)';\n } else if (relaysUsed[0] === undefined) {\n rigPageSkipDetail = 'skipped (no relay resolved for the pointer)';\n } else if (!ctx.publisher.uploadBlob) {\n rigPageSkipDetail =\n 'skipped (the active publisher cannot upload raw blobs)';\n } else {\n pointerPlan = planRigPointer({\n env: deps.env,\n ownerPubkey: ctx.ownerPubkey,\n repoId,\n relay: relaysUsed[0],\n feeRates,\n });\n }\n } else {\n const client = session.client;\n plan = await client.gitEstimate({\n repoPath: repoRoot,\n repoId,\n refspecs,\n force: flags.force,\n relayUrls: relaysUsed,\n ...(announcement ? { announcement } : {}),\n });\n execute = () =>\n client.gitPush({\n repoPath: repoRoot,\n repoId,\n refspecs,\n force: flags.force,\n relayUrls: relaysUsed,\n confirm: true,\n ...(announcement ? { announcement } : {}),\n });\n // The delegated daemon owns the paid pipeline but exposes no raw-blob\n // upload route yet — the pointer refreshes on the next standalone push.\n rigPageSkipDetail =\n 'skipped on the daemon path (refreshes on the next standalone push)';\n }\n\n // ── Rig-page pointer publish (shared by the normal path and the\n // up-to-date refresh below; never fails a succeeded push) ────────────────\n const gateway = pointerGateway(deps.env);\n const publishPointer = async (\n pointer: RigPointerPlan\n ): Promise<RigPageReport> => {\n try {\n // Guarded at plan time: a plan only exists when uploadBlob is available.\n const ctx = standaloneCtx as StandaloneContext;\n const receipt = await (\n ctx.publisher.uploadBlob as NonNullable<\n typeof ctx.publisher.uploadBlob\n >\n )({\n body: Buffer.from(pointer.html, 'utf8'),\n contentType: 'text/html',\n repoId,\n });\n writeRigPointerRecord(deps.env, {\n repoId,\n owner: identity.pubkey,\n pointerTxId: receipt.txId,\n contentHash: pointer.contentHash,\n updatedAt: Date.now(),\n });\n return {\n status: 'published',\n txId: receipt.txId,\n url: `${gateway}/${receipt.txId}`,\n feePaid: receipt.feePaid.toString(),\n };\n } catch (err) {\n // The record was not updated, so the next push retries the upload.\n return {\n status: 'skipped',\n detail: `pointer upload failed (push itself succeeded; the next push retries): ${\n err instanceof Error ? err.message : String(err)\n }`,\n };\n }\n };\n const printRigPage = (rigPage: RigPageReport): void => {\n if (rigPage.url) {\n io.out(\n `Rig page: ${rigPage.url}` +\n (rigPage.status === 'published'\n ? ` paid ${rigPage.feePaid}`\n : '') +\n ' (renders this repo from Arweave)'\n );\n const mirrors = rigPage.txId ? mirrorGateways(gateway) : [];\n if (mirrors.length > 0 && rigPage.txId) {\n const txId = rigPage.txId;\n io.out(\n ' also: (same page — try these if the address above does ' +\n 'not load; gateways index fresh uploads at different speeds, ' +\n 'and any one of them can be down)'\n );\n for (const mirror of mirrors) {\n io.out(` ${mirror}/${txId}`);\n }\n }\n } else if (rigPage.detail) {\n io.err(`rig page: ${rigPage.detail}`);\n }\n };\n\n // ── Up-to-date short-circuit (never publish a no-op refs event) ─────────\n // A STALE Rig page still refreshes here: the pointer changes when the Rig\n // build / relay / gateway changes, not the refs — requiring a dummy\n // commit to roll it forward would be absurd.\n const upToDate = plan.refUpdates.every((u) => u.kind === 'up-to-date');\n if (upToDate) {\n if (pointerPlan?.action !== 'upload') {\n if (flags.json) {\n io.emitJson({\n command: 'push',\n repoId,\n path,\n identity,\n executed: false,\n upToDate: true,\n plan,\n } satisfies PushJsonOutput);\n } else {\n io.out('Everything up-to-date — nothing to push (and nothing paid).');\n }\n return 0;\n }\n\n if (!flags.json) {\n io.out(\n 'Everything up-to-date — refs unchanged, but the Rig page is stale ' +\n '(new Rig build, relay, or gateway):'\n );\n io.out(` rig page ${pointerPlan.bytes} bytes ${pointerPlan.fee}`);\n io.out(renderIdentityLine(identity));\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n command: 'push',\n repoId,\n path,\n identity,\n executed: false,\n upToDate: true,\n plan,\n hint: 'refs up-to-date; the Rig page is stale — re-run with --yes to refresh it (or --no-rig-page to skip)',\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 --no-rig-page to skip the refresh)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Refresh the Rig page (total ${pointerPlan.fee} base units)? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was uploaded or published.');\n return 1;\n }\n }\n const rigPage = await publishPointer(pointerPlan);\n if (flags.json) {\n io.emitJson({\n command: 'push',\n repoId,\n path,\n identity,\n executed: false,\n upToDate: true,\n plan,\n rigPage,\n } satisfies PushJsonOutput);\n } else {\n printRigPage(rigPage);\n }\n return 0;\n }\n\n // ── Confirm gate ────────────────────────────────────────────────────────\n // The confirmed total covers the push plan PLUS a (new/changed) Rig\n // pointer; an unchanged pointer is free and printed as such.\n const confirmTotal =\n BigInt(plan.estimate.totalFee) + (pointerPlan?.fee ?? 0n);\n if (!flags.json) {\n for (const line of renderPlan(plan)) io.out(line);\n if (pointerPlan?.action === 'upload') {\n io.out(\n ` rig page ${pointerPlan.bytes} bytes ${pointerPlan.fee}` +\n ` (repo page — paid once, reused until relay/rig-web changes)`\n );\n io.out(` total with rig page ${confirmTotal}`);\n }\n io.out(renderIdentityLine(identity));\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n command: 'push',\n repoId,\n path,\n identity,\n executed: false,\n upToDate: false,\n plan,\n hint: 'estimate only — re-run with --yes to upload and publish (permanent, non-refundable)',\n } satisfies PushJsonOutput);\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n 'refusing to spend channel funds without confirmation in a non-interactive ' +\n 'session — re-run with --yes (or use --json for an estimate)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Proceed with paid push (total ${confirmTotal} base units)? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was uploaded or published.');\n return 1;\n }\n }\n\n // ── Execute ─────────────────────────────────────────────────────────────\n const result = await execute();\n\n // ── Rig-page pointer (after the push succeeded; never fails it) ─────────\n let rigPage: RigPageReport;\n if (!pointerPlan) {\n rigPage = {\n status: 'skipped',\n ...(rigPageSkipDetail ? { detail: rigPageSkipDetail } : {}),\n };\n } else if (pointerPlan.action === 'unchanged') {\n rigPage = {\n status: 'unchanged',\n txId: pointerPlan.recordedTxId as string,\n url: `${gateway}/${pointerPlan.recordedTxId}`,\n };\n } else {\n rigPage = await publishPointer(pointerPlan);\n }\n\n // ── Receipts ────────────────────────────────────────────────────────────\n if (flags.json) {\n io.emitJson({\n command: 'push',\n repoId,\n path,\n identity,\n executed: true,\n upToDate: false,\n plan,\n result,\n rigPage,\n } satisfies PushJsonOutput);\n } else {\n for (const line of renderResult(result)) io.out(line);\n printRigPage(rigPage);\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 * Per-repo Rig pointer — the permanent Arweave page that RENDERS a pushed\n * repo in place, deployed by `rig push` the way GitHub Pages tracks a repo.\n * User-facing name: the repo's \"Rig page\".\n *\n * The pointer boots the FULL React Rig from its Arweave deployment: it pins\n * `window.__RIG_CONFIG__ = {relay, owner, repo}`, presets the HashRouter\n * route in its own URL fragment, and loads rig-web's entry css/js from the\n * deployment's path manifest (`rig-web/scripts/deploy-arweave.mjs` — every\n * build output uploaded GZIPPED under ArDrive Turbo's free tier with a\n * `Content-Encoding` tag the gateways serve as a header, so the whole app\n * fits without a funded wallet). Module-relative imports resolve against the\n * MODULE's URL, so the entire chunk graph loads from the manifest while the\n * address bar stays on the pointer.\n *\n * A `<noscript>`/delayed fallback links to the Pages deployment\n * ({@link DEFAULT_RIG_WEB_URL}). The earlier single-file rig-lite build\n * (`rig-web/lite/rig-lite.js`) remains in-tree as the ultra-light option.\n *\n * The generated HTML is DETERMINISTIC for a given (bundle, gateway,\n * rigWebUrl, relay, owner, repoId) so `rig push` can content-address it:\n * the pointer uploads once and every later push skips the fee until one of\n * those inputs changes (../cli/rig-pointer-record.ts).\n */\n\nimport { hexToNpub } from './npub.js';\n\n/** One released Arweave deployment of rig-web (manifest + entry assets). */\nexport interface RigWebBundle {\n /** The ar.io path-manifest txId (`https://<gateway>/<tx>/` serves the app). */\n manifestTx: string;\n /** Entry module path inside the manifest (hashed per build). */\n entryJs: string;\n /** Entry stylesheet path inside the manifest (hashed per build). */\n entryCss: string;\n}\n\n/**\n * The current rig-web deployment on Arweave (deployed 2026-07-17 via\n * `deploy-arweave.mjs`, 122 files, free tier). Override per-field with\n * `RIG_WEB_TX` / `RIG_WEB_ENTRY_JS` / `RIG_WEB_ENTRY_CSS`.\n */\nexport const DEFAULT_RIG_WEB_BUNDLE: RigWebBundle = {\n manifestTx: 'Iy8sHYVnoevSpwDC2lqUoIg8BWdes9NmMbgmPd81UpU',\n entryJs: 'assets/index-BuKzYubR.js',\n entryCss: 'assets/index-H5D6cmfa.css',\n};\n\n/** Env vars overriding the bundle (e.g. a newer deploy before release). */\nexport const RIG_WEB_TX_ENV = 'RIG_WEB_TX';\nexport const RIG_WEB_ENTRY_JS_ENV = 'RIG_WEB_ENTRY_JS';\nexport const RIG_WEB_ENTRY_CSS_ENV = 'RIG_WEB_ENTRY_CSS';\n\n/**\n * Gateway the pointer loads the rig-web BUNDLE from. Tied to where the\n * bundle deploy lives (mainnet, via Turbo), NOT to where `rig push`\n * uploads repo data: the assets are stored GZIPPED with a\n * `Content-Encoding` tag that `arweave.net` serves as a real header —\n * `ar-io.dev` drops it and ships raw gzip bytes, which the browser then\n * fails to parse (\"Invalid or unexpected token\", blank page). Override\n * with `RIG_WEB_GATEWAY` alongside a bundle override.\n */\nexport const DEFAULT_RIG_WEB_GATEWAY = 'https://arweave.net';\n\n/** Env var overriding the bundle gateway. */\nexport const RIG_WEB_GATEWAY_ENV = 'RIG_WEB_GATEWAY';\n\n/** Pages deployment for the no-JS / delayed fallback link (tracks main). */\nexport const DEFAULT_RIG_WEB_URL = 'https://toon-protocol.github.io/rig';\n\n/** Env var overriding the fallback URL. */\nexport const RIG_WEB_URL_ENV = 'RIG_WEB_URL';\n\nexport interface RigPointerOptions {\n /** The Arweave rig-web deployment the pointer boots. */\n bundle: RigWebBundle;\n /** Gateway base the app loads from (no trailing /). */\n gateway: string;\n /** Fallback rig-web deployment for the no-JS link (no trailing /). */\n rigWebUrl: string;\n /** Relay the Rig should read the repo from (`wss://…`). */\n relay: string;\n /** Repo owner as npub (rig-web routes are `#/<npub>/<repo>`). */\n ownerNpub: string;\n /** Repository id (NIP-34 d-tag). */\n repoId: string;\n}\n\n/** The repo's HashRouter fragment, with the relay threaded through. */\nexport function repoHashRoute(\n options: Pick<RigPointerOptions, 'relay' | 'ownerNpub' | 'repoId'>\n): string {\n const { relay, ownerNpub, repoId } = options;\n // Route + query INSIDE the fragment — rig-web's relay resolution reads\n // `[?&]relay=` from the fragment (rig-web/README.md \"Relay resolution\n // order\"), so this works on any static host with no rewrites.\n return `#/${encodeURIComponent(ownerNpub)}/${encodeURIComponent(repoId)}?relay=${encodeURIComponent(relay)}`;\n}\n\n/** The full-Rig fallback URL for a repo (Pages deployment). */\nexport function rigWebRoute(\n options: Pick<RigPointerOptions, 'rigWebUrl' | 'relay' | 'ownerNpub' | 'repoId'>\n): string {\n return `${options.rigWebUrl.replace(/\\/+$/, '')}/${repoHashRoute(options)}`;\n}\n\n/**\n * The repo's rig-web viewer URL for the kind:30617 `web` tag (#158).\n *\n * THE SAME base URL and route shape the Rig pointer bakes into its no-JS\n * fallback link ({@link rigWebRoute}) — so ADR-0001's URL-permanence rules\n * govern the `web` tag too, and a reader following either link lands in the\n * same place. Re-deriving the shape here instead of reusing it is how the two\n * drift apart.\n *\n * @param env - Process env; `RIG_WEB_URL` overrides {@link DEFAULT_RIG_WEB_URL}.\n * @param relay - The relay the repo's events are published to.\n * @param ownerPubkey - Repo owner, 64-char hex (encoded to npub for the route).\n * @param repoId - Repository id (NIP-34 `d` tag).\n */\nexport function repoWebUrl(options: {\n env: NodeJS.ProcessEnv;\n relay: string;\n ownerPubkey: string;\n repoId: string;\n}): string {\n return rigWebRoute({\n rigWebUrl: options.env[RIG_WEB_URL_ENV] ?? DEFAULT_RIG_WEB_URL,\n relay: options.relay,\n ownerNpub: hexToNpub(options.ownerPubkey),\n repoId: options.repoId,\n });\n}\n\n/** Escape a string for safe embedding in an HTML attribute/text position. */\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n\n/**\n * Generate the pointer HTML: the full-Rig boot-in-place shell. Loads only\n * the immutable Arweave deployment it exists to boot; degrades to a\n * fallback link with JS disabled.\n */\nexport function generateRigPointerHtml(options: RigPointerOptions): string {\n const gateway = options.gateway.replace(/\\/+$/, '');\n const base = `${gateway}/${options.bundle.manifestTx}`;\n const cssHref = `${base}/${options.bundle.entryCss}`;\n const jsSrc = `${base}/${options.bundle.entryJs}`;\n const fallback = rigWebRoute(options);\n const safeFallback = escapeHtml(fallback);\n const title = escapeHtml(`${options.repoId} — Rig`);\n\n // Escape `<` so hostile config values can never break out of the script.\n const config = JSON.stringify({\n relay: options.relay,\n owner: options.ownerNpub,\n repo: options.repoId,\n }).replace(/</g, '\\\\u003c');\n const hashRoute = JSON.stringify(repoHashRoute(options)).replace(\n /</g,\n '\\\\u003c'\n );\n\n return `<!DOCTYPE html>\n<html lang=\"en\"><head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <meta name=\"description\" content=\"Decentralized Git on Nostr & TOON Protocol\">\n <title>${title}</title>\n <link rel=\"icon\" href=\"data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚒</text></svg>\">\n <script>window.__RIG_CONFIG__=${config};if(!location.hash||location.hash===\"#\")location.replace(${hashRoute})</script>\n <link rel=\"stylesheet\" href=\"${escapeHtml(cssHref)}\">\n <script type=\"module\" crossorigin src=\"${escapeHtml(jsSrc)}\"></script>\n</head><body>\n <div id=\"app\"></div>\n <noscript><p>JavaScript is off — open <a href=\"${safeFallback}\">${title}</a> in the hosted Rig.</p></noscript>\n <p hidden data-fallback>If nothing loads, open <a href=\"${safeFallback}\">${title}</a> in the hosted Rig.</p>\n <script>setTimeout(function(){var p=document.querySelector(\"[data-fallback]\");var app=document.getElementById(\"app\");if(p&&(!app||!app.childElementCount))p.hidden=false},8000)</script>\n</body></html>\n`;\n}\n","/**\n * Local record of the last-published Rig pointer per repo — what lets\n * `rig push` keep the per-repo Rig page (../rig-pointer.ts) current like\n * GitHub Pages WITHOUT re-paying on every push.\n *\n * The pointer HTML is deterministic for (rigWebUrl, relay, owner, repoId),\n * so its sha-256 is recorded alongside the uploaded txId: while the hash\n * matches, later pushes reuse the recorded URL for free; when any input\n * changes (relay moved, rig-web base flipped to the Arweave bundle), the\n * next push uploads a fresh pointer and the record rolls forward.\n *\n * Same storage conventions as ./site-record.ts: a JSON file under\n * `TOON_CLIENT_HOME` (default `~/.toon-client`), keyed by repoId (local,\n * single-user scope); corrupt/missing files are treated as empty for reads\n * and overwritten on write.\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nexport const RIG_POINTER_FILENAME = 'rig-pointers.json';\n\n/** One recorded Rig-pointer publish. */\nexport interface RigPointerRecord {\n repoId: string;\n /** Owner pubkey (hex) the pointer was published under. */\n owner: string;\n /** The pointer transaction id (43-char base64url). */\n pointerTxId: string;\n /** sha-256 (hex) of the pointer HTML that was uploaded. */\n contentHash: string;\n /** Unix milliseconds of the publish. */\n updatedAt: number;\n}\n\ntype RigPointerFile = Record<string, RigPointerRecord>;\n\nfunction storeDir(env: NodeJS.ProcessEnv): string {\n return env['TOON_CLIENT_HOME'] ?? join(homedir(), '.toon-client');\n}\n\nfunction storePath(env: NodeJS.ProcessEnv): string {\n return join(storeDir(env), RIG_POINTER_FILENAME);\n}\n\nfunction readAll(env: NodeJS.ProcessEnv): RigPointerFile {\n try {\n const parsed = JSON.parse(readFileSync(storePath(env), 'utf8')) as unknown;\n if (parsed && typeof parsed === 'object') return parsed as RigPointerFile;\n return {};\n } catch {\n // Missing or corrupt → empty (never fatal to a push).\n return {};\n }\n}\n\n/** The recorded pointer for a repo, if any. */\nexport function readRigPointerRecord(\n env: NodeJS.ProcessEnv,\n repoId: string\n): RigPointerRecord | undefined {\n return readAll(env)[repoId];\n}\n\n/** Record a pointer publish (overwrites the repo's previous record). */\nexport function writeRigPointerRecord(\n env: NodeJS.ProcessEnv,\n record: RigPointerRecord\n): void {\n const all = readAll(env);\n all[record.repoId] = record;\n mkdirSync(storeDir(env), { recursive: true });\n writeFileSync(storePath(env), `${JSON.stringify(all, null, 2)}\\n`);\n}\n","/**\n * Shared scaffolding for the rig-owned commands that read or republish a\n * repo's kind:30617 announcement (`rig maintainers`, `rig payout`,\n * `rig refresh`): the common flag set\n * (`--repo-id/--owner/--remote/--relay/--yes/--json`), the resolution of the\n * repo address + relays from those flags plus the repo's `toon.*` git config,\n * and the whole prologue a PAID republish must clear before it may spend\n * anything ({@link openAnnouncementRepublish}).\n *\n * These commands are deliberately identical at the edges — same flags, same\n * repo-address resolution, same relay rules, same owner-only and\n * unannounced-repo refusals — and differ only in WHICH tag of the\n * announcement they touch. Keeping the edges in one place is what makes that\n * sameness real rather than aspirational: a money-safety refusal fixed here is\n * fixed for every one of them, instead of in whichever copy someone\n * remembered.\n */\n\nimport { ownerToHex } from '../npub.js';\nimport {\n earliestUniqueCommit,\n type ConformanceFacts,\n} from '../repo-announcement.js';\nimport { GitRepoReader } from '../repo-reader.js';\nimport { repoWebUrl } from '../rig-pointer.js';\nimport { fetchRemoteState, type RemoteState } from '../remote-state.js';\nimport type { EventCommandDeps } from './events.js';\nimport { InvalidRelayUrlError, UnconfiguredRepoAddressError } from './errors.js';\nimport { readToonConfig, resolveRepoRoot } from './git-config.js';\nimport {\n defaultLoadStandalone,\n identityReport,\n type IdentityReport,\n} from './push.js';\nimport {\n resolveRelays,\n singleRelayRefusal,\n type ResolvedRelays,\n} from './remote.js';\nimport type { StandaloneContext } from './standalone-context.js';\n\n/** Relay URLs rig can actually talk to (reads and paid publishes alike). */\nexport const WS_URL_RE = /^wss?:\\/\\//i;\n\n/** The flags every kind:30617 command accepts. */\nexport interface RepoCommandFlags {\n json: boolean;\n yes: boolean;\n help: boolean;\n relay: string[];\n remote?: string;\n repoId?: string;\n owner?: string;\n}\n\n/** `parseArgs` option spec matching {@link RepoCommandFlags}. */\nexport const REPO_COMMAND_OPTIONS = {\n json: { type: 'boolean', default: false },\n yes: { type: 'boolean', default: false },\n relay: { type: 'string', multiple: true },\n remote: { type: 'string' },\n 'repo-id': { type: 'string' },\n owner: { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n} as const;\n\n/** Narrow `parseArgs` values into {@link RepoCommandFlags} (`--owner` → hex). */\nexport function pickRepoCommandFlags(\n values: Record<string, unknown>\n): RepoCommandFlags {\n const flags: RepoCommandFlags = {\n json: values['json'] === true,\n yes: values['yes'] === true,\n help: values['help'] === true,\n relay: Array.isArray(values['relay']) ? (values['relay'] as string[]) : [],\n };\n if (typeof values['remote'] === 'string') flags.remote = values['remote'];\n if (typeof values['repo-id'] === 'string') flags.repoId = values['repo-id'];\n if (typeof values['owner'] === 'string')\n flags.owner = ownerToHex(values['owner']);\n return flags;\n}\n\nexport interface RepoContext {\n repoId: string;\n owner: string;\n relays: string[];\n /** The full relay resolution (source/nudge) — for the single-relay refusal. */\n resolved: ResolvedRelays;\n repoRoot?: string;\n}\n\n/** Resolve repo address (repoId + owner) and relays from flags + git config. */\nexport async function resolveRepoContext(\n flags: RepoCommandFlags,\n deps: EventCommandDeps\n): Promise<RepoContext> {\n let repoRoot: string | undefined;\n let toonConfig: { repoId?: string; owner?: string; relays: string[] } = {\n relays: [],\n };\n try {\n repoRoot = await resolveRepoRoot(deps.cwd);\n toonConfig = await readToonConfig(repoRoot);\n } catch {\n // Not inside a git repo — flags must carry everything.\n }\n const repoId = flags.repoId ?? toonConfig.repoId;\n if (!repoId) throw new UnconfiguredRepoAddressError('repository id');\n const owner = flags.owner ?? toonConfig.owner;\n if (!owner) throw new UnconfiguredRepoAddressError('repository owner');\n\n const resolved = await resolveRelays({\n relayFlags: flags.relay,\n remoteName: flags.remote,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n if (resolved.nudge !== undefined) deps.io.err(resolved.nudge);\n return {\n repoId,\n owner,\n relays: resolved.relays,\n resolved,\n ...(repoRoot !== undefined ? { repoRoot } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Conformance tags (#158)\n// ---------------------------------------------------------------------------\n\n/**\n * The NIP-34 conformance facts (#158) for an owner-initiated republish:\n * the relay this publish goes to, the repo's rig-web viewer URL, and the\n * `euc` computed from the LOCAL repository.\n *\n * Every owner-initiated republish backfills these, so a repo announced before\n * #158 becomes conformant on the next `rig maintainers`, `rig payout` or\n * `rig refresh` with no special step. A command run OUTSIDE a git repo (all of\n * them accept `--repo-id`/`--owner`) still backfills `relays` and `web`; the\n * `euc` needs local history, and reporting none is honest — the announcement\n * keeps whatever it already declares.\n */\nexport async function conformanceFactsFor(options: {\n ctx: RepoContext;\n relayUrl: string;\n deps: EventCommandDeps;\n}): Promise<ConformanceFacts> {\n const { ctx, relayUrl, deps } = options;\n const repoRoot = ctx.repoRoot;\n const rootCommits =\n deps.rootCommits ??\n (repoRoot === undefined\n ? undefined\n : (rev?: string) => new GitRepoReader(repoRoot).rootCommits(rev));\n let euc: string | null = null;\n if (rootCommits !== undefined) {\n try {\n euc = await earliestUniqueCommit({ rootCommits });\n } catch {\n // An unreadable local repo is no reason to refuse an announcement edit.\n euc = null;\n }\n }\n let web: string | null = null;\n try {\n web = repoWebUrl({\n env: deps.env,\n relay: relayUrl,\n ownerPubkey: ctx.owner,\n repoId: ctx.repoId,\n });\n } catch {\n // An owner pubkey that will not encode to an npub means no viewer URL —\n // never a reason to refuse the announcement edit the user actually asked\n // for, the same rule the euc lookup follows above.\n web = null;\n }\n return { relays: [relayUrl], web, earliestUniqueCommit: euc };\n}\n\n// ---------------------------------------------------------------------------\n// The paid-republish prologue\n// ---------------------------------------------------------------------------\n\n/** A paid kind:30617 republish that has cleared every refusal and may proceed. */\nexport interface OpenedRepublish {\n ok: true;\n ctx: RepoContext;\n /** The single relay this republish reads from and publishes to. */\n relayUrl: string;\n /** The loaded standalone context — the caller MUST stop it when done. */\n standalone: StandaloneContext;\n identity: IdentityReport;\n /** The repo's current state, including the announcement being amended. */\n remote: RemoteState;\n /** The #158 conformance backfill for this republish. */\n facts: ConformanceFacts;\n}\n\n/** A republish that must not happen; the command returns `exitCode` as-is. */\nexport interface RefusedRepublish {\n ok: false;\n exitCode: number;\n /** Loaded before the refusal, when it was — the caller still stops it. */\n standalone?: StandaloneContext;\n}\n\n/**\n * Everything a paid kind:30617 republish must clear BEFORE it may spend\n * anything, in one place: exactly one ws/wss relay, the embedded standalone\n * publisher (the daemon has no announcement route), the owner-only check, the\n * current announcement read off the relay, and the refusal to republish a repo\n * that has never been announced.\n *\n * The last two are money-safety rules, not conveniences:\n *\n * - only the OWNER's kind:30617 is authoritative, so a non-owner republish\n * would pay to write that identity's own, ignored announcement;\n * - republishing an UNANNOUNCED repo would mint a phantom announcement with\n * a placeholder name for real money, and `rig push` only announces a repo\n * that is not already announced — so the placeholder would permanently\n * shadow the real name and description the first push intended.\n *\n * @param what - Verb phrase for the owner-only refusal, e.g. `change the\n * maintainer set`.\n * @param before - Verb phrase for the unannounced refusal, e.g. `before\n * managing maintainers`.\n * @returns The opened republish, or the exit code the command must return.\n * Either way, `standalone` (when present) is the caller's to stop.\n */\nexport async function openAnnouncementRepublish(options: {\n deps: EventCommandDeps;\n flags: RepoCommandFlags;\n what: string;\n before: string;\n}): Promise<OpenedRepublish | RefusedRepublish> {\n const { deps, flags, what, before } = options;\n const { io } = deps;\n\n const ctx = await resolveRepoContext(flags, deps);\n // A single relay for a paid publish (mirrors push/events guard).\n if (ctx.relays.length > 1) {\n io.err(singleRelayRefusal(ctx.resolved, 'Nothing was published or paid.'));\n return { ok: false, exitCode: 1 };\n }\n const relayUrl = ctx.relays[0];\n if (relayUrl === undefined || !WS_URL_RE.test(relayUrl)) {\n throw new InvalidRelayUrlError(\n relayUrl ?? '',\n 'a paid publish needs a ws:// or wss:// relay'\n );\n }\n\n // Standalone only: the daemon has no announcement route.\n const load = deps.loadStandalone ?? defaultLoadStandalone;\n const standalone = await load({\n env: deps.env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n relayUrl,\n });\n const identity = identityReport(standalone);\n\n if (identity.pubkey.toLowerCase() !== ctx.owner.toLowerCase()) {\n io.err(\n `rig: only the repo owner (${ctx.owner.slice(0, 8)}…) can ${what} — the ` +\n `active identity is ${identity.pubkey.slice(0, 8)}…. ` +\n 'A non-owner republish would write your own (ignored) announcement. ' +\n 'Nothing was published or paid.'\n );\n return { ok: false, exitCode: 1, standalone };\n }\n\n const remote = await fetchRemoteState({\n relayUrls: [relayUrl],\n ownerPubkey: ctx.owner,\n repoId: ctx.repoId,\n ...(deps.webSocketFactory\n ? { webSocketFactory: deps.webSocketFactory }\n : {}),\n });\n if (!remote.announced) {\n io.err(\n `rig: 30617:${ctx.owner.slice(0, 8)}…:${ctx.repoId} has no announcement ` +\n 'yet — run `rig push` to publish the repo (with its real ' +\n `name/description) ${before}. Nothing was published or paid.`\n );\n return { ok: false, exitCode: 1, standalone };\n }\n\n return {\n ok: true,\n ctx,\n relayUrl,\n standalone,\n identity,\n remote,\n facts: await conformanceFactsFor({ ctx, relayUrl, deps }),\n };\n}\n","/**\n * `rig` subcommand dispatch (#250): rig-owned verbs first, git for the rest.\n *\n * rig owns exactly: init, identity, remote, clone, fetch, push, site, issue,\n * comment, pr, maintainers, payout, refresh, channel (+ the `channels` list\n * shorthand), fund,\n * balance, chain, entry, name, ci, help/-h/--help, and --version. EVERY other\n * subcommand is executed as `git <argv...>` verbatim (./git-passthrough.ts)\n * — `rig status` IS `git status`, `rig add -p`, `rig commit`, `rig rebase\n * -i`, … all land in git with rig's stdio and git's exit code. Owned verbs\n * always win: `rig push` is the paid TOON push and shadows `git push`, and\n * `rig clone`/`rig fetch` (#278) are the free TOON transports shadowing\n * their git counterparts (plain-git clone/fetch/push stay available by\n * calling git directly).\n *\n * The NIP-34 status publish that used to be `rig status` lives at\n * `rig pr status` since #250 (BREAKING) — bare `rig status` is git's.\n *\n * `--json` (#265) follows the same ownership boundary: it is a flag OF the\n * owned subcommands, never a global rig flag. `rig --json status` starts\n * with a verb rig does not own (`--json`), so the WHOLE argv passes through\n * to git verbatim — rig neither consumes the flag nor applies the strict\n * stdout contract to git's inherited stdio. The owned-verb list is pinned to\n * ./output.ts's RIG_OWNED_VERBS (strict-json.test.ts keeps them in sync).\n */\n\nimport { createRequire } from 'node:module';\nimport { runBalance } from './balance.js';\nimport { runChain } from './chain.js';\nimport { runChannel } from './channel.js';\nimport { runCi } from './ci.js';\nimport { runClone } from './clone.js';\nimport {\n runComment,\n runIssue,\n runPr,\n type EventCommandDeps,\n} from './events.js';\nimport { runEntry } from './entry.js';\nimport { runFetch } from './fetch.js';\nimport { runFund } from './fund.js';\nimport { runGitPassthrough, type GitRunner } from './git-passthrough.js';\nimport { runIdentity } from './identity-cmd.js';\nimport { runInit } from './init.js';\nimport { runMaintainers } from './maintainers.js';\nimport { runRefresh } from './refresh.js';\nimport { runName, type LoadArns } from './name.js';\nimport { runPayout } from './payout.js';\nimport { runPush, PUSH_USAGE } from './push.js';\nimport { runRemote } from './remote.js';\nimport { runSite } from './site.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 identity create generate a fresh identity (BIP-39) into the\n encrypted keystore — the phrase is shown ONCE;\n back it up. This is your first step on a new box\n identity show the active identity's source + derived pubkey\n (never the phrase)\n identity import write an EXISTING phrase (read from stdin) to the\n encrypted keystore\n init set up this repo: resolve your identity (or offer\n to generate one) and write the toon.* git config\n remote add <name> <url> add a relay as a REAL git remote (\"origin\" is\n remote remove <name> the default publish target); remove/list manage\n remote list them — \\`git remote -v\\` shows the same data\n clone <relay-url> <owner>/<repo-id> [dir]\n clone a TOON repo (free): relay state + Arweave\n objects (SHA-1 verified) → a real git repository,\n push/pull-capable out of the box\n fetch [remote] fetch remote refs + missing objects (free) and\n update refs/remotes/<remote>/*; no merge. Shadows\n git fetch (plain \\`git fetch\\` stays available)\n push [remote] [refspecs...] plan, price, confirm, and execute a paid push\n to TOON (defaults to the \"origin\" remote). rig\n push is the TOON transport and shadows git push;\n plain-git pushes remain available by running\n \\`git push\\` directly\n site publish [ref] deploy a pushed repo as a permaweb site: build the\n ar.io path manifest (paths → Arweave txids) and\n upload it as one paid store write; prints the URL\n site url [ref] print the last-published site URL for a ref (free)\n issue create file an issue (kind:1621) against a repo\n issue list | show <id> read the repo's issues + comments (free)\n pr list | show <id> read the repo's patches; show prints the full\n patch text (free)\n comment <target-event-id> comment (NIP-22 kind:1111) on an issue or patch,\n or reply to an existing kind:1111 comment\n pr create publish a patch (kind:1617) with real\n \\`git format-patch\\` content\n pr status <event-id> <state> set an issue/patch status (kind:1630-1633):\n open | applied | closed | draft\n maintainers list show the repo's declared maintainers (free); add/\n maintainers add <pubkey> remove republish the kind:30617 to change who may\n maintainers remove <pubkey> author authoritative issue/PR status (owner is\n always an implicit maintainer)\n refresh republish the kind:30617 with no field edit to\n refresh its NIP-34 tags (relays, web, the euc fork\n identity) — PAID, and free when nothing changes\n payout show show the repo's declared payout pointer (free);\n payout set <address> set/clear republish the kind:30617 — no pointer\n payout clear means the serving node keeps 100% of\n repo-scoped write fees (v1: evm addresses only)\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 chain [set <c>|unset] choose which chain/USDC settles paid writes\n (evm|sol); free — reads/writes local config\n entry <url> | entry clear choose the connector that prices and settles paid\n writes — one URL is the whole configuration, since\n its GET /ilp describes it; --relay <wss-url>\n records the free-read relay beside it; free —\n writes local config\n name buy <name> ArNS naming (#367): buy points a human name at an\n name set <name> <txId> Arweave txId, owned + paid by this identity's\n name status <name> Solana key. buy spends mARIO on Solana via the\n ar.io registry (NOT ILP); status is free. Needs\n the optional \\`@ar.io/sdk\\` dependency\n channel list show the payment channels paid commands hold\n (free — reads local state; \\`rig channels\\` is a\n shorthand for \\`rig channel list\\`)\n channel open explicitly open (or resume) the channel for a\n peer; --deposit adds collateral (on-chain)\n channel deploy-zkapp pre-deploy this identity's dedicated Mina\n PaymentChannel zkApp (on-chain; the Mina open\n path otherwise does this automatically)\n channel close <channelId> start the settlement challenge window (on-chain)\n channel settle <channelId> release collateral after the window (on-chain)\n ci request <coordinator> authorize a CI coordinator to run this repo's\n ci stop <coordinator> workflows (kind:9843) / revoke it (kind:9844)\n ci trigger <coordinator> --workflow <path> [--commit <sha>]\n run one exact workflow on one commit (kind:9840)\n ci secret set|remove <coordinator> NAME[=value]\n CI secrets, NIP-44 encrypted to the coordinator's\n advertised key (kind:29846) — the relay never\n sees names or values\n ci status <commit> every CI run + job for a commit with NIP-C1 trust\n levels (free); exits non-zero unless green — the\n one-command merge gate (--require-ci-trust)\n ci serve --relay <url> --repo <owner>/<id>\n run a coordinator: watch the relay, run workflows\n with act on Docker, publish results as paid writes\n\nAny other command is passed through to git verbatim: \\`rig status\\` runs\n\\`git status\\`, and \\`rig add -p\\`, \\`rig commit\\`, \\`rig log --oneline\\`,\n\\`rig rebase -i\\`, … behave exactly like git (same output, same exit code).\n\nRun \\`rig <command> --help\\` for a rig command's flags. \\`rig init\\`,\n\\`rig remote\\`, \\`rig clone\\`, \\`rig fetch\\`, \\`rig issue list/show\\`,\n\\`rig pr list/show\\`, \\`rig fund\\`, \\`rig balance\\`, and \\`rig channel list\\`\nare free; push/issue create/comment/pr create/pr status are paid writes —\npermanent and non-refundable —\nand channel open/close/settle are on-chain wallet transactions; each states\nwhat it will spend and asks for confirmation before doing so (--yes skips,\n--json emits machine output).\n\nWith --json, stdout carries exactly ONE JSON document (everything human-facing\ngoes to stderr), so \\`rig <command> --json | jq\\` always parses. --json is a\nper-subcommand flag on the commands rig owns, NOT a global rig flag: it does\nnot apply to the git passthrough (\\`rig status --json\\` runs\n\\`git status --json\\`), and flags placed before the subcommand\n(\\`rig --json status\\`) pass through to git untouched.\n\nSTANDALONE MODE: by default rig delegates paid commands to a running\ntoon-clientd that holds the same identity (it owns the payment channel and its\nbootstrap is warm). To bypass the daemon and always sign for yourself, set\nRIG_STANDALONE=1 in your environment (the durable, applies-to-everything\nswitch) or pass --standalone / --no-daemon to a paid command. rig then runs\nfully embedded; a per-identity lockfile still stops two rig processes from\nracing the channel. If a daemon is ALSO actively writing on this identity,\nstop it (its pid is in ~/.toon-client/daemon.pid) to avoid a claim race.`;\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 * `rig name` ArNS SDK loader seam (#367): defaults to the lazy `@ar.io/sdk`\n * import; tests inject a stub so no real ar.io registry call is ever made.\n */\n loadArns?: LoadArns;\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 [\n '../package.json',\n '../../package.json',\n '../../../package.json',\n ]) {\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 'identity':\n return runIdentity(rest, deps);\n case 'remote':\n return runRemote(rest, deps);\n // The #278 read path — FREE (relay + Arweave gateway reads, no payment).\n case 'clone':\n return runClone(rest, deps);\n case 'fetch':\n return runFetch(rest, deps);\n case 'push':\n return runPush(rest, deps);\n case 'site':\n return runSite(rest, deps);\n case 'issue':\n return runIssue(rest, deps);\n case 'comment':\n return runComment(rest, deps);\n case 'pr':\n return runPr(rest, deps);\n case 'maintainers':\n return runMaintainers(rest, deps);\n case 'payout':\n return runPayout(rest, deps);\n case 'refresh':\n return runRefresh(rest, deps);\n case 'channel':\n return runChannel(rest, deps);\n case 'channels':\n // Alias (#demo): bare `rig channels` (plus flags) is `rig channel list`;\n // a subcommand word still routes normally (`rig channels open` works).\n return runChannel(\n rest[0] !== undefined && !rest[0].startsWith('-')\n ? rest\n : ['list', ...rest],\n deps\n );\n case 'fund':\n return runFund(rest, deps);\n case 'balance':\n return runBalance(rest, deps);\n case 'chain':\n return runChain(rest, deps);\n case 'entry':\n return runEntry(rest, deps);\n case 'name':\n return runName(rest, deps);\n case 'ci':\n // Relay-native CI (#125): request/stop/trigger/secret are paid NIP-C1\n // publishes, status is a free read, serve runs the coordinator.\n return runCi(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 full multi-chain reader (`ToonClient.getWalletBalances()`\n * on the UNSTARTED embedded client, #299): for every configured chain it shows\n * the native coin (ETH / SOL / MINA) AND USDC. The Solana/Mina addresses are\n * derived from the mnemonic on demand — the same keys `start()` registers and\n * `rig fund` prints — so all chains appear even before a start. The EVM chain\n * key is the settlement chain (it wins over the network preset's primary), so a\n * devnet identity funded on `evm:anvil:31337` shows that chain's balances, not\n * the preset chain's zero (the #260-era getBalances mismatch). Each chain reads\n * independently; an unreachable RPC degrades to a per-chain notice.\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 {\n WalletChainBalanceInfo,\n WalletTokenAmountInfo,\n} 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: the full on-chain wallet view — native coin\nplus USDC on every configured chain (EVM / Solana / Mina) — and recorded\npayment-channel holdings (deposited / claimed / available). Free — reads chain\nRPCs and local state only; nothing is signed or paid. An unreachable chain RPC\ndegrades to a per-chain notice without failing the others.\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 * cumulativeClaimed − depositTotal, when both are known (floored at 0).\n * Non-zero means the cumulative signed claims exceed the recorded on-chain\n * collateral: the peer accepted (and may keep accepting) claims it cannot\n * fully redeem on-chain until the deposit is topped up — the on-chain\n * TokenNetwork caps redemption at the deposit. `available 0` alone cannot\n * distinguish \"exactly spent\" from \"overdrawn\", hence this field.\n */\n overdrawn: string | null;\n}\n\n/** `--json` envelope. */\ninterface BalanceJson {\n command: 'balance';\n identity: IdentityReport;\n wallet: WalletChainBalanceInfo[];\n channels: ChannelBalanceJson[];\n}\n\n/**\n * Format a base-unit integer string as a human decimal using `decimals`.\n * No decimals known → the base-unit string verbatim. Trims trailing zeros but\n * keeps at least one fractional digit only when non-integer.\n */\nexport function formatUnits(amount: string, decimals?: number): string {\n if (decimals === undefined || decimals <= 0) return amount;\n const neg = amount.startsWith('-');\n const digits = (neg ? amount.slice(1) : amount).padStart(decimals + 1, '0');\n const whole = digits.slice(0, digits.length - decimals);\n const frac = digits.slice(digits.length - decimals).replace(/0+$/, '');\n return (neg ? '-' : '') + (frac ? `${whole}.${frac}` : whole);\n}\n\n/** `SYMBOL amount` for one asset, formatted with its decimals. */\nfunction renderAmount(a: WalletTokenAmountInfo): string {\n return `${a.symbol ?? 'token'} ${formatUnits(a.amount, a.decimals)}`;\n}\n\n/** Env override for the wallet-read timeout; `0` opts out (wait forever). */\nconst WALLET_READ_TIMEOUT_ENV = 'RIG_BALANCE_WALLET_TIMEOUT_MS';\n/** Default cap on the wallet read — generous, only trips a genuine hang. */\nconst DEFAULT_WALLET_READ_TIMEOUT_MS = 20_000;\n\n/** Resolve the wallet-read timeout (ms): valid non-negative env override, else default. */\nexport function walletReadTimeoutMs(env: NodeJS.ProcessEnv): number {\n const raw = env[WALLET_READ_TIMEOUT_ENV];\n if (raw === undefined || raw === '') return DEFAULT_WALLET_READ_TIMEOUT_MS;\n const n = Number(raw);\n return Number.isFinite(n) && n >= 0 ? n : DEFAULT_WALLET_READ_TIMEOUT_MS;\n}\n\n/**\n * The wallet read exceeded {@link walletReadTimeoutMs}. This is the guard that\n * turns the silent-exit bug into a loud, actionable failure: on the Mina\n * settlement path a wallet read can neither resolve nor keep a live handle\n * open (a hung GraphQL endpoint, a nonexistent on-chain account, o1js-adjacent\n * work), so awaiting it UNBOUNDED lets Node's event loop drain and the one-shot\n * CLI exits 0 with no output at all. The bounded read's live timer prevents\n * that drain and forces a decision instead.\n */\nexport class WalletReadTimeoutError extends Error {\n constructor(public readonly timeoutMs: number) {\n super(\n `wallet balance read timed out after ${timeoutMs}ms — the chain ` +\n 'RPC/GraphQL endpoint is unreachable or hanging. (A nonexistent Mina ' +\n 'account reads as 0, so a hang points at the endpoint, not an empty ' +\n 'balance.) Recorded channels are unaffected; retry, or set ' +\n `${WALLET_READ_TIMEOUT_ENV}=0 to wait indefinitely.`\n );\n this.name = 'WalletReadTimeoutError';\n }\n}\n\n/**\n * Read the multi-chain wallet view under a hard time bound. The `setTimeout`\n * is deliberately NOT `unref()`ed: its live handle is exactly what keeps the\n * one-shot CLI's event loop from draining to a silent exit-0 while the read\n * hangs. A late rejection from the losing promise is swallowed so it never\n * surfaces as an unhandled rejection after the race is decided.\n */\nexport async function readWalletBounded(\n read: () => Promise<WalletChainBalanceInfo[]>,\n timeoutMs: number\n): Promise<WalletChainBalanceInfo[]> {\n const settled = read();\n // A `0` (or negative) timeout opts out of the bound entirely (wait forever).\n if (timeoutMs <= 0) return settled;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const guard = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new WalletReadTimeoutError(timeoutMs)), timeoutMs);\n });\n // Don't let the loser reject into an unhandled rejection post-race.\n settled.catch(() => undefined);\n try {\n return await Promise.race([settled, guard]);\n } finally {\n if (timer) clearTimeout(timer);\n }\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 // ── Channels: #262 map ⋈ claim watermark, THIS identity only ────────────\n // Read FIRST: a purely local read that is always available (a corrupt map\n // is still a clear error via the outer catch), so the report can show\n // recorded channels even when the on-chain wallet read below fails.\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 let overdrawn: string | null = null;\n if (deposited !== undefined && claimed !== undefined) {\n const remaining = BigInt(deposited) - BigInt(claimed);\n available = (remaining > 0n ? remaining : 0n).toString();\n overdrawn = (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 overdrawn,\n };\n });\n\n // ── Wallet: the client's full multi-chain view (#299) — native + USDC ───\n // BOUNDED. An unbounded await here is the silent-exit bug: on the Mina path\n // the read can neither resolve nor keep the event loop alive, so the CLI\n // drains and exits 0 with no output. The bound turns any such hang into a\n // loud, non-zero failure that STILL prints the identity + channels.\n let wallet: WalletChainBalanceInfo[] = [];\n let walletError: Error | undefined;\n if (ctx.money) {\n const money = ctx.money;\n try {\n wallet = await readWalletBounded(\n () => money.walletChainBalances(),\n walletReadTimeoutMs(env)\n );\n } catch (err) {\n walletError = err instanceof Error ? err : new Error(String(err));\n }\n }\n\n if (json) {\n // A wallet-read failure is a hard error in the machine contract: emit the\n // single error envelope (never a partial + a silent 0).\n if (walletError) return emitCliError(io, json, 'balance', walletError);\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 (walletError) {\n // Loud, actionable — never a silent gap. The channels below still print.\n io.out(` wallet balances unavailable — ${walletError.message}`);\n } else if (wallet.length === 0) {\n io.out(' (no chain configured for this identity — nothing to read)');\n }\n for (const chain of wallet) {\n io.out(` ${chain.chainKey.padEnd(11)} ${chain.address}`);\n if (chain.unreadable) {\n io.out(\n ` unreadable (RPC unreachable)` +\n (chain.error ? ` — ${chain.error}` : '')\n );\n continue;\n }\n const assets = [...(chain.native ? [chain.native] : []), ...chain.tokens];\n if (assets.length === 0) {\n io.out(' (no balance readable)');\n continue;\n }\n io.out(` ${assets.map(renderAmount).join(' ')}`);\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 if (c.overdrawn !== null && BigInt(c.overdrawn) > 0n) {\n io.out(\n ` OVERDRAWN by ${c.overdrawn}: cumulative claims exceed the ` +\n `recorded deposit — the peer accepted claims only partially ` +\n `covered by on-chain collateral. Top up with ` +\n `\\`rig channel open --deposit <amount>\\`.`\n );\n }\n }\n // Non-zero when the wallet read failed — the report is printed, but the\n // command reports failure (never a silent success on a broken read).\n return walletError ? 1 : 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 * `rig chain` — choose which chain (and therefore which USDC token) settles\n * paid `rig` writes.\n *\n * Each supported chain has its own USDC: EVM (Base Sepolia) and Solana devnet.\n * (Mina was removed in 4.0.0 with the Mina client.) \"Which USDC is spent\" ==\n * \"which settlement chain rig picks\", and\n * that is a session/config-level choice — there is no per-`rig push` flag. This\n * command persists the choice to the shared client config's `chain` field\n * (`~/.toon-client/config.json`) — the exact knob `resolveNetworkTopology`\n * reads (env `TOON_CLIENT_CHAIN` ?? config `chain`), so the next paid command\n * settles on the named chain.\n *\n * rig chain show the current preference (and what USDC it maps to)\n * rig chain set <chain> pin the settlement chain: evm | sol (or a\n * full id like evm:base:84532)\n * rig chain unset clear the pin — revert to automatic selection\n *\n * A FREE command: it only reads/writes the local config file, never the relay\n * or a chain. When nothing is pinned, rig auto-selects (most-recent open\n * channel → first announced chain your wallet holds USDC on → first announced\n * EVM chain); `rig chain` reports that state.\n *\n * Precedence caveats surfaced to the user: the `TOON_CLIENT_CHAIN` env var\n * overrides the config field, and a `supportedChains` array (if set) takes\n * precedence over `chain` — writing `chain` while either is set warns that the\n * pin may not take effect until they are cleared/changed.\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { emitCliError } from './errors.js';\nimport type { CliIo } from './output.js';\n\n/** Canonical settlement families and the USDC each one spends. */\nconst FAMILY_USDC: Record<string, string> = {\n evm: 'EVM USDC (Base Sepolia on devnet)',\n solana: 'Solana USDC',\n};\n\n/**\n * Families rig used to settle on, mapped to why they are gone. 4.0.0 dropped\n * Mina with the client (`rig channel deploy-zkapp` went with it), and the\n * 4.0.0 changelog states `rig chain set mina` is refused — but nothing\n * refused it: `set mina` returned 0 and wrote `\"chain\": \"mina\"` to the config,\n * pinning a settlement chain no paid command can use. Refusing it BY NAME\n * (rather than letting it fall through to \"unknown chain\") is what tells a\n * user with mina already pinned what actually happened to it.\n */\nconst REMOVED_FAMILIES: Record<string, string> = {\n mina: 'Mina settlement was removed in rig 4.0.0 along with the Mina client and `rig channel deploy-zkapp`',\n};\n\n/**\n * Accepted `set` values → the canonical string written to config. Short aliases\n * mirror `rig fund` (`sol`, `eth`). A full chain id (with a `:`) is stored\n * verbatim; a bare family is stored as the canonical family, which the resolver\n * matches against the first announced chain of that family.\n */\nconst FAMILY_ALIASES: Record<string, string> = {\n evm: 'evm',\n eth: 'evm',\n sol: 'solana',\n solana: 'solana',\n};\n\n/** Human list of accepted `set` arguments (for usage/errors). */\nconst CHAIN_ARG_LIST = 'evm | sol | solana (or a full id like evm:base:84532)';\n\nexport const CHAIN_USAGE = `Usage: rig chain [set <chain> | unset]\n\nChoose which chain — and therefore which USDC token — settles paid \\`rig\\`\nwrites. The choice is saved to the client config's \\`chain\\` field and applies to\nevery subsequent paid command (there is no per-command chain flag). Free: only\nthe local config file is touched.\n\n rig chain show the current settlement-chain preference\n rig chain set <chain> pin the settlement chain / USDC:\n evm → EVM USDC (Base Sepolia on devnet)\n sol → Solana USDC\n (a full id like evm:base:84532 or solana:devnet also\n works; \\`solana\\` is accepted for \\`sol\\`, \\`eth\\` for \\`evm\\`)\n rig chain unset clear the pin — revert to automatic selection\n\nWhen nothing is pinned, rig auto-selects: your most-recently-used open channel's\nchain, else the first announced chain your wallet holds USDC on, else the first\nannounced EVM chain.\n\nOptions:\n --json machine-readable envelope\n -h, --help show this help`;\n\n/** What `rig chain` needs from the command environment. */\nexport interface ChainDeps {\n io: CliIo;\n env: NodeJS.ProcessEnv;\n}\n\n/** The slice of the shared client config `rig chain` reads/writes. */\ninterface ChainConfigFile {\n chain?: string;\n supportedChains?: string[];\n [key: string]: unknown;\n}\n\n/** `--json` envelope. */\ninterface ChainJson {\n command: 'chain';\n /** The effective settlement-chain preference, or null when unset (auto). */\n chain: string | null;\n /** Where the effective value came from. */\n source: 'env' | 'config' | 'supportedChains' | 'auto';\n /** The USDC token family the effective chain spends (null when auto). */\n usdc: string | null;\n /** The value written to the config `chain` field (set/unset only). */\n wrote?: string | null;\n configPath: string;\n /** Precedence warnings that may keep the pin from taking effect. */\n warnings?: string[];\n}\n\n/** Resolve the client config directory + path (mirrors readFundConfig). */\nfunction configPathFor(env: NodeJS.ProcessEnv): string {\n const dir = env['TOON_CLIENT_HOME'] ?? join(homedir(), '.toon-client');\n return join(dir, 'config.json');\n}\n\nfunction readChainConfig(configPath: string): ChainConfigFile {\n try {\n return JSON.parse(readFileSync(configPath, 'utf8')) as ChainConfigFile;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw new Error(\n `failed to read client config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n}\n\n/** Read-merge-write: preserve every other field, only touch `chain`. */\nfunction writeChainConfig(configPath: string, file: ChainConfigFile): void {\n mkdirSync(dirname(configPath), { recursive: true });\n writeFileSync(configPath, `${JSON.stringify(file, null, 2)}\\n`, 'utf8');\n}\n\n/**\n * Normalize a `set` argument to the string stored in config. A value with a\n * `:` is a full chain id (family must be evm/solana); otherwise it is a family\n * alias. Throws a usage error on anything else, and a REMOVED-family error by\n * name for a family rig no longer settles on (#4.0 dropped mina).\n */\nfunction normalizeChain(raw: string): string {\n if (raw.includes(':')) {\n const family = raw.split(':')[0]?.toLowerCase() ?? '';\n const removed = REMOVED_FAMILIES[family];\n if (removed) {\n throw new Error(`${removed}; settle on evm or solana instead`);\n }\n if (!(family in FAMILY_USDC)) {\n throw new Error(\n `unknown chain family in ${JSON.stringify(raw)} — must start with evm: or solana:`\n );\n }\n return raw;\n }\n const lowered = raw.toLowerCase();\n const removed = REMOVED_FAMILIES[lowered];\n if (removed) {\n throw new Error(`${removed}; settle on evm or solana instead`);\n }\n const canonical = FAMILY_ALIASES[lowered];\n if (!canonical) {\n throw new Error(\n `chain must be one of ${CHAIN_ARG_LIST}, got ${JSON.stringify(raw)}`\n );\n }\n return canonical;\n}\n\n/** The USDC family label for a stored chain value (family or full id). */\nfunction usdcFor(chain: string): string {\n const family = (\n chain.includes(':') ? (chain.split(':')[0] ?? chain) : chain\n ).toLowerCase();\n return FAMILY_USDC[family] ?? `${family} USDC`;\n}\n\n/** Run `rig chain`; returns the process exit code. */\nexport async function runChain(\n args: string[],\n deps: ChainDeps\n): Promise<number> {\n const { io, env } = deps;\n\n let positionals: string[];\n let json = false;\n try {\n const parsed = parseArgs({\n args,\n allowPositionals: true,\n options: {\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (parsed.values.help) {\n io.out(CHAIN_USAGE);\n return 0;\n }\n positionals = parsed.positionals;\n json = parsed.values.json ?? false;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CHAIN_USAGE);\n return 2;\n }\n\n const [sub, ...subRest] = positionals;\n if (sub !== undefined && sub !== 'set' && sub !== 'unset') {\n io.err(\n `unknown subcommand ${JSON.stringify(sub)} — expected \\`set\\`, \\`unset\\`, or no argument`\n );\n io.err(CHAIN_USAGE);\n return 2;\n }\n if (sub === 'set' && subRest.length !== 1) {\n io.err(\n subRest.length === 0\n ? `rig chain set needs a chain: ${CHAIN_ARG_LIST}`\n : `rig chain set takes exactly one chain, got ${subRest.length}: ${subRest.join(' ')}`\n );\n io.err(CHAIN_USAGE);\n return 2;\n }\n if (sub === 'unset' && subRest.length !== 0) {\n io.err(`rig chain unset takes no arguments, got: ${subRest.join(' ')}`);\n io.err(CHAIN_USAGE);\n return 2;\n }\n // Normalize the `set` value here (not inside the emitCliError-wrapped block)\n // so an unknown chain is a USAGE error (exit 2), not a runtime error.\n let setValue: string | undefined;\n if (sub === 'set') {\n try {\n setValue = normalizeChain(subRest[0] as string);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CHAIN_USAGE);\n return 2;\n }\n }\n\n try {\n const configPath = configPathFor(env);\n const file = readChainConfig(configPath);\n const envChain = env['TOON_CLIENT_CHAIN'];\n const supported0 = file.supportedChains?.[0];\n\n // Precedence warnings shared by set/unset: env overrides config, and a\n // supportedChains array overrides the plain `chain` field.\n const precedenceWarnings = (targetField: 'chain' | null): string[] => {\n const w: string[] = [];\n if (envChain !== undefined) {\n w.push(\n `TOON_CLIENT_CHAIN=${envChain} is set in the environment and overrides the config ` +\n `${targetField === 'chain' ? 'value you just wrote' : 'file'} — unset it for the config to take effect.`\n );\n }\n if (supported0 !== undefined) {\n w.push(\n `config \\`supportedChains\\` is set (first entry ${JSON.stringify(supported0)}) and takes ` +\n 'precedence over `chain` — clear or reorder it for this pin to take effect.'\n );\n }\n return w;\n };\n\n // ── set ────────────────────────────────────────────────────────────────\n if (sub === 'set') {\n const value = setValue as string;\n file.chain = value;\n writeChainConfig(configPath, file);\n const warnings = precedenceWarnings('chain');\n if (json) {\n io.emitJson({\n command: 'chain',\n chain: envChain ?? value,\n source: envChain !== undefined ? 'env' : 'config',\n usdc: usdcFor(envChain ?? value),\n wrote: value,\n configPath,\n ...(warnings.length ? { warnings } : {}),\n } satisfies ChainJson);\n return 0;\n }\n io.out(`Settlement chain set to ${value} → spends ${usdcFor(value)}.`);\n io.out(\n `Saved to ${configPath}. Applies to the next paid command (e.g. \\`rig push\\`).`\n );\n for (const w of warnings) io.err(`warning: ${w}`);\n return 0;\n }\n\n // ── unset ──────────────────────────────────────────────────────────────\n if (sub === 'unset') {\n const had = file.chain;\n delete file.chain;\n writeChainConfig(configPath, file);\n // After unset, what still pins the chain (env / supportedChains), if any.\n const stillPinned = envChain ?? supported0;\n if (json) {\n io.emitJson({\n command: 'chain',\n chain: stillPinned ?? null,\n source:\n envChain !== undefined\n ? 'env'\n : supported0 !== undefined\n ? 'supportedChains'\n : 'auto',\n usdc: stillPinned ? usdcFor(stillPinned) : null,\n wrote: null,\n configPath,\n ...(precedenceWarnings(null).length\n ? { warnings: precedenceWarnings(null) }\n : {}),\n } satisfies ChainJson);\n return 0;\n }\n io.out(\n had !== undefined\n ? `Cleared the settlement-chain pin (was ${had}).`\n : 'No settlement-chain pin was set.'\n );\n if (stillPinned !== undefined) {\n io.out(\n `Still pinned to ${stillPinned} by ${envChain !== undefined ? 'TOON_CLIENT_CHAIN' : 'config supportedChains'} → ${usdcFor(stillPinned)}.`\n );\n } else {\n io.out(\n 'Reverted to automatic selection (most-recent channel → first funded announced chain → first EVM).'\n );\n }\n return 0;\n }\n\n // ── show (no subcommand) ────────────────────────────────────────────────\n const effective = envChain ?? file.chain ?? supported0;\n const source: ChainJson['source'] =\n envChain !== undefined\n ? 'env'\n : file.chain !== undefined\n ? 'config'\n : supported0 !== undefined\n ? 'supportedChains'\n : 'auto';\n if (json) {\n io.emitJson({\n command: 'chain',\n chain: effective ?? null,\n source,\n usdc: effective ? usdcFor(effective) : null,\n configPath,\n } satisfies ChainJson);\n return 0;\n }\n if (effective !== undefined) {\n const via =\n source === 'env'\n ? 'TOON_CLIENT_CHAIN env'\n : source === 'config'\n ? `config \\`chain\\` (${configPath})`\n : `config \\`supportedChains[0]\\``;\n io.out(\n `Settlement chain: ${effective} → spends ${usdcFor(effective)} (from ${via}).`\n );\n io.out(\n 'Change it with `rig chain set <evm|sol>`, or `rig chain unset` for auto.'\n );\n } else {\n io.out('Settlement chain: (auto) — no pin set.');\n io.out(\n 'rig picks your most-recent open channel, else the first announced chain your'\n );\n io.out('wallet holds USDC on, else the first announced EVM chain.');\n io.out('Pin one with `rig chain set <evm|sol>`.');\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'chain', err);\n }\n}\n","/**\n * `rig channel` — the payment channels paid rig commands hold (#262), plus\n * the explicit money lifecycle (#263): open / close / settle.\n *\n * Paid commands open a channel lazily on first use and RECORD it in the\n * peer→channel map under `TOON_CLIENT_HOME` (default `~/.toon-client`,\n * `rig-channels.json`), so later invocations resume the same channel instead\n * of opening (and funding) a new one per run. `rig channel list` reads that\n * map plus the client's nonce-watermark store (`channels.json`) and shows\n * current holdings — a FREE command: local files only, no client start, no\n * network, no payment (and therefore no `@toon-protocol/client` import).\n *\n * The lifecycle subcommands are ON-CHAIN wallet operations (gas + collateral\n * movement, not relay claims), so they follow the push confirm idiom: print\n * what will happen, then require `--yes` (mandatory in a non-TTY session) or\n * an interactive y/N confirm; `--json` without `--yes` is a pure plan.\n *\n * open the SAME resume-or-open path lazy paid writes use (factored, not\n * forked): resumes the recorded channel when one is live, else\n * opens + records a fresh one; `--deposit` adds collateral on top.\n * close starts the settlement challenge window for a recorded channel —\n * the channel stops paying immediately; collateral is released by\n * `settle` once the window elapses.\n * settle releases the remaining collateral after the challenge window\n * (the client refuses a too-early settle BEFORE spending gas).\n *\n * close/settle recover deposits stranded by pre-#262 one-channel-per-run\n * behaviour: any channel present in the map can be driven to settled.\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n channelStatus,\n ChannelMapStore,\n resolveChannelPaths,\n type ChannelMapRecord,\n type WatermarkEntry,\n} from '../standalone/channel-map.js';\nimport { emitCliError } from './errors.js';\nimport {\n defaultLoadStandalone,\n identityReport,\n type CliIo,\n type IdentityReport,\n type PushDeps,\n} from './push.js';\nimport { renderIdentityLine } from './render.js';\nimport type { StandaloneContext } from './standalone-context.js';\nimport type { StandaloneMoneyOps } from '../standalone/money.js';\n\nexport const CHANNEL_USAGE = `Usage: rig channel <subcommand>\n\nManage the payment channels paid rig commands hold with relay/store peers.\nPaid commands open a channel lazily on first use and record it under\nTOON_CLIENT_HOME (default ~/.toon-client, rig-channels.json), so later\ninvocations resume the same channel instead of opening a new one per run.\n\nSubcommands:\n list [--json] show recorded channels — peer, chain, channel id, deposit,\n cumulative claimed, status. Free: reads local state only.\n\n open [--peer <ilp-destination>] [--deposit <base-units>]\n explicitly open the payment channel for a peer — the SAME\n path paid commands use lazily: resumes the recorded live\n channel if one exists (no on-chain spend), else opens and\n records a fresh one (locks the peer-negotiated initial\n deposit on-chain). --peer is the ILP destination to anchor\n to (default: the configured destination, e.g. the devnet\n apex); --deposit adds that much extra collateral after the\n open/resume. On-chain: asks for confirmation (--yes skips).\n\n close <channelId>\n close a recorded channel — an on-chain tx that starts the\n settlement challenge window (the peer's settlementTimeout).\n The channel stops paying immediately; the remaining\n collateral stays locked until \\`rig channel settle\\` after\n the window elapses. Asks for confirmation (--yes skips).\n\n settle <channelId>\n settle a closed channel once its challenge window elapsed —\n an on-chain tx that releases the remaining collateral back\n to your wallet. Refused (without spending gas) while the\n window is still open. Asks for confirmation (--yes skips).\n\nCommon options: --json (machine-readable envelopes; without --yes lifecycle\ncommands emit a pure plan and execute nothing), --yes, -h/--help.`;\n\n/**\n * What `rig channel` needs from the command environment — the shared paid\n * command deps (io/env/cwd + injectable standalone loader): `list` uses only\n * io/env, the lifecycle subcommands load the standalone context.\n */\nexport type ChannelDeps = PushDeps;\n\n/** One channel in the `--json` envelope (unknowns are null, bigints strings). */\ninterface ChannelJson {\n channelId: string;\n peerId: string;\n identity: string;\n destination: string;\n chain: string;\n tokenNetwork: string;\n depositTotal: string | null;\n cumulativeClaimed: string | null;\n nonce: number | null;\n status: 'open' | 'closing' | 'settleable' | 'settled';\n openedAt: string;\n lastUsedAt: string;\n}\n\n/** Route one `rig channel …` invocation; returns the exit code. */\nexport async function runChannel(\n args: string[],\n deps: ChannelDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n switch (sub) {\n case 'list':\n return runChannelList(rest, deps);\n case 'open':\n return runChannelOpen(rest, deps);\n case 'close':\n return runChannelWithdrawStep(rest, deps, 'close');\n case 'settle':\n return runChannelWithdrawStep(rest, deps, 'settle');\n case 'help':\n case '--help':\n case '-h':\n io.out(CHANNEL_USAGE);\n return 0;\n case undefined:\n io.err(CHANNEL_USAGE);\n return 2;\n default:\n io.err(`rig channel: unknown subcommand ${JSON.stringify(sub)}`);\n io.err(CHANNEL_USAGE);\n return 2;\n }\n}\n\n// ---------------------------------------------------------------------------\n// list (#262)\n// ---------------------------------------------------------------------------\n\nfunction runChannelList(args: string[], deps: ChannelDeps): number {\n const { io, env } = deps;\n let json = false;\n try {\n const { values } = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (values.help) {\n io.out(CHANNEL_USAGE);\n return 0;\n }\n json = values.json ?? false;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CHANNEL_USAGE);\n return 2;\n }\n\n try {\n const paths = resolveChannelPaths(env);\n const store = new ChannelMapStore(paths);\n const records = store.list();\n const rows = records.map((record) => describeChannel(record, store));\n\n if (json) {\n io.emitJson({ command: 'channel list', channels: rows });\n return 0;\n }\n if (rows.length === 0) {\n io.out(\n 'No payment channels recorded — paid rig commands (push, issue, ' +\n 'comment, pr) record the channel they open on first use, and ' +\n '`rig channel open` records an explicit one.'\n );\n return 0;\n }\n io.out(\n `${rows.length} payment channel${rows.length === 1 ? '' : 's'} ` +\n `recorded in ${paths.mapPath}:`\n );\n for (const row of rows) {\n io.out('');\n for (const line of renderChannel(row)) io.out(line);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'channel list', err);\n }\n}\n\n/** Join one map record with its watermark state. */\nfunction describeChannel(\n record: ChannelMapRecord,\n store: ChannelMapStore\n): ChannelJson {\n const watermark: WatermarkEntry | undefined = store.readWatermark(\n record.channelId\n );\n return {\n channelId: record.channelId,\n peerId: record.peerId,\n identity: record.identity,\n destination: record.destination,\n chain: record.chain,\n tokenNetwork: record.tokenNetwork,\n depositTotal: record.depositTotal ?? null,\n cumulativeClaimed: watermark?.cumulativeAmount ?? null,\n nonce: watermark?.nonce ?? null,\n status: channelStatus(watermark),\n openedAt: record.openedAt,\n lastUsedAt: record.lastUsedAt,\n };\n}\n\nfunction renderChannel(row: ChannelJson): string[] {\n const claimed =\n row.cumulativeClaimed === null\n ? 'unknown (no local claim state)'\n : `${row.cumulativeClaimed} base units (nonce ${row.nonce})`;\n return [\n `channel ${row.channelId} [${row.status}]`,\n ` peer ${row.destination} (${row.peerId})`,\n ` identity ${row.identity.slice(0, 8)}…`,\n ` chain ${row.chain}` +\n (row.tokenNetwork ? ` token-network ${row.tokenNetwork}` : ''),\n ` deposited ${row.depositTotal ?? 'unrecorded'}` +\n (row.depositTotal ? ' base units' : ''),\n ` claimed ${claimed}`,\n ` opened ${row.openedAt} (last used ${row.lastUsedAt})`,\n ];\n}\n\n// ---------------------------------------------------------------------------\n// Shared money-command plumbing (#263)\n// ---------------------------------------------------------------------------\n\n/** Load the standalone context and require its money-ops surface. */\nasync function loadMoneyContext(\n deps: ChannelDeps,\n options?: { channelDestination?: string }\n): Promise<{ ctx: StandaloneContext; money: StandaloneMoneyOps }> {\n const ctx = await (deps.loadStandalone ?? defaultLoadStandalone)({\n env: deps.env,\n cwd: deps.cwd,\n warn: (line) => deps.io.err(line),\n ...(options?.channelDestination\n ? { channelDestination: options.channelDestination }\n : {}),\n });\n const money = ctx.money;\n if (!money) {\n await ctx.stop().catch(() => undefined);\n throw new Error(\n 'this standalone loader does not expose money operations — ' +\n 'channel open/close/settle need a loader with the money lifecycle'\n );\n }\n return { ctx, money };\n}\n\n/**\n * The push-idiom confirm gate for an ON-CHAIN money operation. Returns the\n * exit code to bail out with, or undefined to proceed. In `--json` mode\n * without `--yes` the caller emits its plan envelope (exit 0) — this gate\n * signals that with `'json-plan'`.\n */\nasync function confirmOnChain(\n io: CliIo,\n flags: { yes: boolean; json: boolean },\n question: string\n): Promise<'proceed' | 'json-plan' | number> {\n if (flags.yes) return 'proceed';\n if (flags.json) return 'json-plan';\n if (!io.isInteractive) {\n io.err(\n 'refusing to move on-chain funds without confirmation in a ' +\n 'non-interactive session — re-run with --yes (or use --json for a plan)'\n );\n return 1;\n }\n const proceed = await io.confirm(question);\n if (proceed) return 'proceed';\n io.err('aborted — no on-chain transaction was sent.');\n return 1;\n}\n\n/** Format a string-encoded unix-seconds timestamp for humans. */\nfunction formatUnixSeconds(value: string): string {\n const ms = Number(value) * 1000;\n return Number.isFinite(ms) ? new Date(ms).toISOString() : `t=${value}s`;\n}\n\n/** Whole seconds from now until a string-encoded unix-seconds timestamp. */\nfunction secondsUntil(value: string, nowSec: number): number {\n return Number(value) - nowSec;\n}\n\n// ---------------------------------------------------------------------------\n// open\n// ---------------------------------------------------------------------------\n\ninterface ChannelOpenJson {\n command: 'channel open';\n identity: IdentityReport;\n executed: boolean;\n plan: { destination: string | null; deposit: string | null };\n result?: {\n channelId: string;\n resumed: boolean;\n destination: string;\n chain: string | null;\n peerId: string | null;\n depositTotal: string | null;\n depositAdded: string | null;\n depositTxHash: string | null;\n };\n hint?: string;\n}\n\nasync function runChannelOpen(\n args: string[],\n deps: ChannelDeps\n): Promise<number> {\n const { io } = deps;\n let peer: string | undefined;\n let deposit: bigint | undefined;\n let yes = false;\n let json = false;\n try {\n const { values } = parseArgs({\n args,\n options: {\n peer: { type: 'string' },\n deposit: { type: 'string' },\n yes: { type: 'boolean', default: false },\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (values.help) {\n io.out(CHANNEL_USAGE);\n return 0;\n }\n peer = values.peer;\n yes = values.yes ?? false;\n json = values.json ?? false;\n if (values.deposit !== undefined) {\n if (!/^\\d+$/.test(values.deposit) || BigInt(values.deposit) <= 0n) {\n throw new Error(\n `--deposit must be a positive base-unit integer, got ${JSON.stringify(values.deposit)}`\n );\n }\n deposit = BigInt(values.deposit);\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CHANNEL_USAGE);\n return 2;\n }\n\n let ctx: StandaloneContext | undefined;\n try {\n const loaded = await loadMoneyContext(deps, {\n ...(peer ? { channelDestination: peer } : {}),\n });\n ctx = loaded.ctx;\n const identity = identityReport(ctx);\n const plan = {\n destination: peer ?? null,\n deposit: deposit?.toString() ?? null,\n };\n\n if (!json) {\n io.out('Channel open plan:');\n io.out(` peer (ILP) ${peer ?? '(configured default destination)'}`);\n io.out(\n ` deposit ${deposit !== undefined ? `+${deposit} base units of extra collateral after the open/resume` : 'none beyond the peer-negotiated initial deposit'}`\n );\n io.out(renderIdentityLine(identity));\n io.out(\n 'If a live channel is already recorded for this peer it is RESUMED ' +\n '(no on-chain spend); otherwise an on-chain channel open locks the ' +\n 'peer-negotiated initial deposit from your wallet (plus gas).'\n );\n }\n\n const gate = await confirmOnChain(\n io,\n { yes, json },\n 'Proceed with on-chain channel open? [y/N] '\n );\n if (gate === 'json-plan') {\n io.emitJson({\n command: 'channel open',\n identity,\n executed: false,\n plan,\n hint: 'plan only — re-run with --yes to open (on-chain: locks collateral and spends gas)',\n } satisfies ChannelOpenJson);\n return 0;\n }\n if (gate !== 'proceed') return gate;\n\n const outcome = await loaded.money.openChannel(\n deposit !== undefined ? { deposit } : undefined\n );\n\n if (json) {\n io.emitJson({\n command: 'channel open',\n identity,\n executed: true,\n plan,\n result: {\n channelId: outcome.channelId,\n resumed: outcome.resumed,\n destination: outcome.destination,\n chain: outcome.chain ?? null,\n peerId: outcome.peerId ?? null,\n depositTotal: outcome.depositTotal ?? null,\n depositAdded: outcome.depositAdded ?? null,\n depositTxHash: outcome.depositTxHash ?? null,\n },\n } satisfies ChannelOpenJson);\n return 0;\n }\n io.out(\n outcome.resumed\n ? `Resumed recorded channel ${outcome.channelId} — no on-chain open was needed.`\n : `Opened channel ${outcome.channelId}${outcome.chain ? ` on ${outcome.chain}` : ''} and recorded it for reuse.`\n );\n io.out(` peer ${outcome.destination}${outcome.peerId ? ` (${outcome.peerId})` : ''}`);\n if (outcome.depositAdded) {\n io.out(\n ` deposited +${outcome.depositAdded} base units` +\n (outcome.depositTxHash ? ` (tx ${outcome.depositTxHash})` : '')\n );\n }\n if (outcome.depositTotal) {\n io.out(` collateral ${outcome.depositTotal} base units total on-chain`);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'channel open', err);\n } finally {\n await stopQuietly(ctx);\n }\n}\n\n// ---------------------------------------------------------------------------\n// close / settle (the two halves of withdraw)\n// ---------------------------------------------------------------------------\n\ninterface WithdrawJson {\n command: 'channel close' | 'channel settle';\n identity: IdentityReport;\n executed: boolean;\n channelId: string;\n result?: {\n txHash: string | null;\n closedAt?: string;\n settleableAt?: string;\n };\n hint?: string;\n}\n\n/**\n * Fail-fast local pre-checks from the recorded watermark timers — before any\n * identity resolution or client start (chain state stays authoritative: the\n * client re-checks before spending gas).\n */\nfunction withdrawPrecheck(\n step: 'close' | 'settle',\n channelId: string,\n watermark: WatermarkEntry | undefined,\n nowSec: number\n): string | undefined {\n const status = channelStatus(watermark, nowSec);\n if (status === 'settled') {\n return `channel ${channelId} is already settled — nothing left to ${step}.`;\n }\n if (step === 'close') {\n if (status === 'closing' || status === 'settleable') {\n const at = watermark?.settleableAt;\n return (\n `channel ${channelId} is already closing — ` +\n (status === 'settleable'\n ? 'its challenge window has elapsed; run `rig channel settle` to release the collateral.'\n : `settleable at ${at ? formatUnixSeconds(at) : 'the end of its challenge window'} (run \\`rig channel settle\\` then).`)\n );\n }\n return undefined;\n }\n // settle\n if (status === 'open') {\n return (\n `channel ${channelId} is not closed — run \\`rig channel close ${channelId}\\` ` +\n 'first (settle only releases collateral after the challenge window of a closed channel).'\n );\n }\n if (status === 'closing' && watermark?.settleableAt !== undefined) {\n const remain = secondsUntil(watermark.settleableAt, nowSec);\n return (\n `channel ${channelId} is not settleable yet — the challenge window is ` +\n `still open (${remain}s remain, settleable at ${formatUnixSeconds(watermark.settleableAt)}). ` +\n 'Nothing was spent; re-run after that time.'\n );\n }\n return undefined;\n}\n\nasync function runChannelWithdrawStep(\n args: string[],\n deps: ChannelDeps,\n step: 'close' | 'settle'\n): Promise<number> {\n const { io, env } = deps;\n const command = `channel ${step}` as WithdrawJson['command'];\n let channelId: string | undefined;\n let yes = false;\n let json = false;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: {\n yes: { type: 'boolean', default: false },\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: true,\n });\n if (values.help) {\n io.out(CHANNEL_USAGE);\n return 0;\n }\n yes = values.yes ?? false;\n json = values.json ?? false;\n if (positionals.length !== 1) {\n throw new Error(\n `rig channel ${step} takes exactly one <channelId> (got ${positionals.length}) — \\`rig channel list\\` shows recorded channels`\n );\n }\n channelId = positionals[0] as string;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CHANNEL_USAGE);\n return 2;\n }\n\n let ctx: StandaloneContext | undefined;\n try {\n // ── Local state: the recorded channel + its watermark (free, fail-fast) ──\n const store = new ChannelMapStore(resolveChannelPaths(env));\n const record = store.list().find((r) => r.channelId === channelId);\n if (!record) {\n throw new Error(\n `no recorded channel ${JSON.stringify(channelId)} — \\`rig channel list\\` shows the channels this identity holds`\n );\n }\n const watermark = store.readWatermark(channelId);\n const nowSec = Math.floor(Date.now() / 1000);\n const refusal = withdrawPrecheck(step, channelId, watermark, nowSec);\n if (refusal) throw new Error(refusal);\n\n // ── Identity (must match the channel's opener — its claims/keys) ────────\n const loaded = await loadMoneyContext(deps);\n ctx = loaded.ctx;\n const identity = identityReport(ctx);\n if (record.identity !== identity.pubkey) {\n throw new Error(\n `channel ${channelId} was opened by identity ${record.identity.slice(0, 8)}… ` +\n `but the active identity is ${identity.pubkey.slice(0, 8)}… ` +\n `(from ${identity.sourceLabel}) — on-chain ${step} must be signed by ` +\n \"the opener's wallet key. Switch RIG_MNEMONIC (or the keystore) to that identity.\"\n );\n }\n\n // ── Plan + confirm gate ──────────────────────────────────────────────────\n if (!json) {\n const claimed = watermark?.cumulativeAmount;\n io.out(`Channel ${step} plan:`);\n io.out(` channel ${channelId} [${channelStatus(watermark, nowSec)}]`);\n io.out(` peer ${record.destination} (${record.peerId})`);\n io.out(` chain ${record.chain}`);\n io.out(\n ` deposited ${record.depositTotal ?? 'unrecorded'}` +\n (claimed !== undefined ? ` claimed ${claimed} base units` : '')\n );\n io.out(renderIdentityLine(identity));\n if (step === 'close') {\n io.out(\n 'Closing is an ON-CHAIN transaction (gas) that starts the settlement ' +\n 'challenge window: the channel stops paying immediately, and the ' +\n 'remaining collateral stays locked until `rig channel settle` ' +\n 'succeeds after the window elapses.'\n );\n } else {\n io.out(\n 'Settling is an ON-CHAIN transaction (gas) that releases the ' +\n \"remaining collateral back to your wallet. The chain's challenge \" +\n 'window is authoritative — a too-early settle is refused before ' +\n 'any gas is spent.'\n );\n }\n }\n const gate = await confirmOnChain(\n io,\n { yes, json },\n `Proceed with on-chain channel ${step}? [y/N] `\n );\n if (gate === 'json-plan') {\n io.emitJson({\n command,\n identity,\n executed: false,\n channelId,\n hint: `plan only — re-run with --yes to ${step} (on-chain transaction)`,\n } satisfies WithdrawJson);\n return 0;\n }\n if (gate !== 'proceed') return gate;\n\n // ── Execute ──────────────────────────────────────────────────────────────\n if (step === 'close') {\n const result = await loaded.money.closeChannel(record);\n if (json) {\n io.emitJson({\n command,\n identity,\n executed: true,\n channelId,\n result: {\n txHash: result.txHash ?? null,\n closedAt: result.closedAt,\n settleableAt: result.settleableAt,\n },\n } satisfies WithdrawJson);\n return 0;\n }\n io.out(\n `Channel ${channelId} is closing` +\n (result.txHash ? ` (tx ${result.txHash})` : '') +\n '.'\n );\n io.out(\n ` challenge window: settleable at ${formatUnixSeconds(result.settleableAt)} ` +\n `(~${Math.max(0, secondsUntil(result.settleableAt, nowSec))}s from now)`\n );\n io.out(\n ` run \\`rig channel settle ${channelId}\\` after that time to release the collateral.`\n );\n return 0;\n }\n\n const result = await loaded.money.settleChannel(record);\n if (json) {\n io.emitJson({\n command,\n identity,\n executed: true,\n channelId,\n result: { txHash: result.txHash ?? null },\n } satisfies WithdrawJson);\n return 0;\n }\n io.out(\n `Channel ${channelId} settled` +\n (result.txHash ? ` (tx ${result.txHash})` : '') +\n ' — the remaining collateral was released to your wallet.'\n );\n return 0;\n } catch (err) {\n return emitCliError(io, json, command, err);\n } finally {\n await stopQuietly(ctx);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Small shared helpers\n// ---------------------------------------------------------------------------\n\nasync function stopQuietly(ctx: StandaloneContext | undefined): Promise<void> {\n if (!ctx) return;\n try {\n await ctx.stop();\n } catch {\n // best-effort teardown\n }\n}\n","/**\n * `rig ci` — the maintainer side of relay-native CI (#125).\n *\n * The relay is the ONLY control plane: every verb here that changes a\n * coordinator's behaviour is a signed, paid NIP-C1 event published from the\n * maintainer's own identity, and every observation is a free relay read.\n * There is no HTTP between maintainer and coordinator.\n *\n * request <coordinator> kind:9843 Service Request — a standing\n * authorization for one coordinator to run this\n * repo's workflows (paid)\n * stop <coordinator> kind:9844 Service Stop (paid)\n * trigger <coordinator> kind:9840 Manual Trigger — run one exact workflow\n * file (by content SHA-256) on one commit (paid)\n * secret set|remove kind:29846 Repository Secret Update — NIP-44 v2\n * encrypted to the coordinator's ADVERTISED\n * secrets-key with a fresh sender key; the relay\n * sees who sent it and where, never the names or\n * values (paid)\n * status <commit> every run + job for a commit, with NIP-C1 trust\n * levels; a one-command merge gate (free — see\n * ./ci-status.ts)\n * serve the coordinator itself (./ci-serve.ts)\n *\n * The paid verbs mirror ./events.ts exactly — repo addressing from the\n * `toon.*` git config (`--repo-id`/`--owner` override), relay resolution via\n * `rig remote` (#249), the fee-quoting confirm gate (`--yes`; non-TTY\n * refuses; `--json` without `--yes` is a pure estimate), and the strict\n * `--json` contract (#265). They ALWAYS run embedded (standalone): the\n * toon-clientd daemon has no `/git/*` route for NIP-C1 kinds, so there is\n * nothing to delegate to.\n *\n * Coordinator identifiers accept npub or 64-char hex everywhere.\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n buildCiManualTrigger,\n buildCiSecretUpdate,\n buildCiServiceRequest,\n buildCiServiceStop,\n CI_ADVERTISEMENT_KIND,\n parseCiAdvertisement,\n repoAddress,\n type CiAdvertisement,\n} from '../ci/nip-c1-events.js';\nimport type { CanAfford } from '../ci/coordinator.js';\nimport type { Runner } from '../ci/runner.js';\nimport {\n encryptSecretUpdate,\n generateSecretsKey,\n RESERVED_SECRET_NAMES,\n SECRET_NAME_RE,\n serializeSecretUpdate,\n type SecretUpdatePlaintext,\n} from '../ci/secrets.js';\nimport { sha256Hex } from '../ci/workflows.js';\nimport { runGit } from '../materialize.js';\nimport type { UnsignedEvent } from '../nip34-events.js';\nimport { ownerToHex } from '../npub.js';\nimport {\n defaultWebSocketFactory,\n queryRelay,\n type NostrEvent,\n type WebSocketFactory,\n} from '../remote-state.js';\nimport {\n serializeEventReceipt,\n type GitEventResponse,\n type GitRepoAddr,\n} from '../routes.js';\nimport { emitCliError, UnconfiguredRepoAddressError } from './errors.js';\nimport type { EventCommandDeps } from './events.js';\nimport {\n readToonConfig,\n resolveRepoRoot,\n type ToonRepoConfig,\n} from './git-config.js';\nimport {\n identityReport,\n loadPaidSession,\n withForcedStandalone,\n type IdentityReport,\n} from './push.js';\nimport { resolveRelays, singleRelayRefusal } from './remote.js';\nimport { feeLabel, renderEventPlan, renderEventReceipt } from './render.js';\nimport type { StandaloneContext } from './standalone-context.js';\nimport { CI_STATUS_USAGE, runCiStatus } from './ci-status.js';\n\n// ---------------------------------------------------------------------------\n// Deps\n// ---------------------------------------------------------------------------\n\n/**\n * The event-command deps (paid session, read seams, stdin) plus the\n * coordinator's injectable seams (`rig ci serve`): the Runner, a clock, the\n * state directory, and an abort signal. Tests inject all of them.\n */\nexport interface CiDeps extends EventCommandDeps {\n /** Runner implementation for `serve` (default: the act/Docker runner). */\n runner?: Runner;\n /** Unix-seconds clock (default: `Date.now()/1000`). */\n clock?: () => number;\n /** Coordinator state directory override (cursor + secret inventory). */\n stateDir?: string;\n /** Stops a running coordinator (default: SIGINT/SIGTERM). */\n signal?: AbortSignal;\n /**\n * Affordability seam for `serve` (default: the recorded-channel / wallet\n * check in ./ci-serve.ts). Tests inject a scripted answer.\n */\n canAfford?: CanAfford;\n}\n\nconst defaultReadStdin = async (): Promise<string> => {\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\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, npub or 64-char hex (default:\n git config 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\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 --standalone accepted for symmetry with the other paid verbs; rig ci\n always runs embedded (alias: --no-daemon)\n -h, --help show this help`;\n\nexport const CI_REQUEST_USAGE = `Usage: rig ci request <coordinator> [options]\n\nPublish a Service Request (kind:9843): a standing authorization for\n<coordinator> (npub or hex) to run this repo's workflows — a paid publish;\nwrites are permanent and non-refundable. A coordinator serves a repo only\nwhile a Request from the repo owner or a declared maintainer is in force\n(until a Service Stop). Rig's coordinator, \\`rig ci serve\\`, is\nrequest-required: it never runs a repo nobody asked it to.\n\nOptions:\n${COMMON_FLAGS_USAGE}`;\n\nexport const CI_STOP_USAGE = `Usage: rig ci stop <coordinator> [options]\n\nPublish a Service Stop (kind:9844) so <coordinator> stops running this\nrepo's workflows — a paid publish; writes are permanent and non-refundable.\nA Stop from the owner or a declared maintainer closes every earlier Request\nfor the repo; a Stop from anyone else closes only their own Requests.\n\nOptions:\n${COMMON_FLAGS_USAGE}`;\n\nexport const CI_TRIGGER_USAGE = `Usage: rig ci trigger <coordinator> --workflow <path> [--commit <sha>] [--ref <refs/…>] [options]\n\nPublish a Manual Trigger (kind:9840): ask <coordinator> to run ONE exact\nworkflow file on ONE commit — a paid publish; writes are permanent and\nnon-refundable. The workflow is identified by its path AND its content\nSHA-256 at that commit (read from the LOCAL repository with\n\\`git show <commit>:<path>\\`), so the coordinator can prove which file ran.\nUse it to re-run a push workflow, or to run one outside push/PR events; a\nmanual replay does not need a standing Service Request, but the author must\nbe the repo owner or a declared maintainer.\n\nOptions:\n --workflow <path> workflow file path in the repo, e.g.\n .github/workflows/ci.yml [required]\n --commit <sha> commit to run (any local revision; default: HEAD)\n --ref <refname> optional \\`refs/heads/…\\` context for workflows that\n read it\n${COMMON_FLAGS_USAGE}`;\n\nexport const CI_SECRET_USAGE = `Usage: rig ci secret set <coordinator> NAME[=value] [NAME=value …] [options]\n rig ci secret remove <coordinator> NAME [NAME …] [options]\n\nSet or remove CI secrets for this repo on <coordinator> — a paid publish of\nONE Repository Secret Update (kind:29846); writes are permanent and\nnon-refundable. Values are NIP-44 v2 encrypted to the secrets-key the\ncoordinator advertises (kind:19843) with a FRESH sender key, so the relay\nsees who sent the update and which repo/coordinator it addresses, but never\nthe names or values. The coordinator injects secrets only into runs the repo\nowner or a declared maintainer caused (pushes, manual triggers) — never into\na stranger's pull request.\n\nValues: \\`NAME=value\\` on the command line, or a bare \\`NAME\\` to read the\nvalue from stdin (one bare name per invocation). Names must match\n[A-Z_][A-Z0-9_]*; values are never echoed anywhere. Per NIP-C1 the update\nis scoped to YOUR repository perspective (30617:<your-pubkey>:<repo-id>).\n\nOptions:\n${COMMON_FLAGS_USAGE}`;\n\nexport const CI_USAGE = `Usage: rig ci <request|stop|trigger|secret|status|serve> …\n\nRelay-native CI: the relay is the only control plane. A coordinator\n(\\`rig ci serve\\`) watches repos on the relay, runs their GitHub-Actions-syntax\nworkflows with act on Docker, and publishes NIP-C1 progress and results as\npaid writes from its own identity. Maintainers manage the relationship with\npaid events from theirs, and everyone reads outcomes for free.\n\nPaid (permanent, non-refundable):\n request <coordinator> authorize a coordinator (9843)\n stop <coordinator> revoke it (9844)\n trigger <coordinator> --workflow <path> run one workflow on a commit (9840)\n secret set|remove <coordinator> NAME[=v] encrypted CI secrets (29846)\n\nFree:\n status <commit> [--json] [--require-ci-trust <level>]\n runs + jobs for a commit; exits\n non-zero unless every run is green\n\nCoordinator:\n serve --relay <url> --repo <owner>/<id> run a coordinator\n\nRun \\`rig ci <verb> --help\\` for a verb's flags.`;\n\n// ---------------------------------------------------------------------------\n// Shared flag parsing (mirrors ./events.ts)\n// ---------------------------------------------------------------------------\n\nconst HEX64_RE = /^[0-9a-f]{64}$/;\n\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 standalone: { type: 'boolean', default: false },\n 'no-daemon': { type: 'boolean', default: false },\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 if (typeof values['remote'] === 'string') flags.remote = values['remote'];\n if (typeof values['repo-id'] === 'string') flags.repoId = values['repo-id'];\n if (typeof values['owner'] === 'string')\n flags.owner = ownerToHex(values['owner']);\n return flags;\n}\n\n/** `<coordinator>` positional: npub or hex → lowercase hex. */\nfunction parseCoordinator(positionals: string[]): string {\n const raw = positionals[0];\n if (raw === undefined)\n throw new Error('<coordinator> (npub or 64-char hex) is required');\n let hex: string;\n try {\n hex = ownerToHex(raw);\n } catch (err) {\n throw new Error(\n `<coordinator> must be an npub or a 64-char hex pubkey (got ${JSON.stringify(raw)}): ` +\n (err instanceof Error ? err.message : String(err))\n );\n }\n if (!HEX64_RE.test(hex)) {\n throw new Error(\n `<coordinator> must be an npub or a 64-char hex pubkey (got ${JSON.stringify(raw)})`\n );\n }\n return hex;\n}\n\n// ---------------------------------------------------------------------------\n// Shared paid pipeline (estimate → confirm → publish; standalone only)\n// ---------------------------------------------------------------------------\n\ntype CiCommand =\n | 'ci request'\n | 'ci stop'\n | 'ci trigger'\n | 'ci secret set'\n | 'ci secret remove';\n\n/** What `buildEvent` can see: the resolved address, identity, and relay. */\ninterface BuildContext {\n addr: GitRepoAddr;\n identity: IdentityReport;\n relayUrl: string;\n webSocketFactory: WebSocketFactory;\n /** Unix seconds — the event's `created_at`. */\n createdAt: number;\n}\n\ninterface RunCiEventOptions {\n command: CiCommand;\n flags: CommonFlags;\n deps: CiDeps;\n actionLabel: string;\n buildEvent: (ctx: BuildContext) => Promise<UnsignedEvent>;\n /** Extra fields for the JSON envelope (never secret values). */\n extra?: Record<string, unknown>;\n}\n\ninterface CiEventJsonOutput {\n command: CiCommand;\n repoAddr: GitRepoAddr;\n coordinator: string;\n path: 'standalone';\n identity: IdentityReport;\n kind: number;\n executed: boolean;\n feeEstimate: string | null;\n result?: GitEventResponse;\n hint?: string;\n [extra: string]: unknown;\n}\n\nasync function runCiEvent(\n opts: RunCiEventOptions & { coordinator: string }\n): Promise<number> {\n const { command, flags, actionLabel, coordinator } = opts;\n // Always embedded: no daemon route exists for NIP-C1 kinds.\n const deps = withForcedStandalone(opts.deps);\n const { io } = deps;\n\n let standaloneCtx: StandaloneContext | undefined;\n try {\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 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 if (relaysUsed.length > 1) {\n io.err(singleRelayRefusal(resolved, 'Nothing was published or paid.'));\n return 1;\n }\n const relayUrl = relaysUsed[0] as string;\n\n const session = await loadPaidSession(deps, relayUrl);\n if (session.path !== 'standalone') {\n // Unreachable with the forced override; guard the type.\n throw new Error('rig ci requires the standalone paid path');\n }\n standaloneCtx = session.ctx;\n const identity = identityReport(standaloneCtx);\n const fee = (\n await standaloneCtx.publisher.getFeeRates()\n ).eventFee.toString();\n\n const owner = flags.owner ?? toonConfig.owner ?? identity.pubkey;\n const addr: GitRepoAddr = { ownerPubkey: owner, repoId };\n const createdAt = (deps.clock ?? (() => Math.floor(Date.now() / 1000)))();\n\n const event = await opts.buildEvent({\n addr,\n identity,\n relayUrl,\n webSocketFactory: deps.webSocketFactory ?? defaultWebSocketFactory,\n createdAt,\n });\n const action = `kind:${event.kind} ${actionLabel}`;\n\n const base = {\n command,\n repoAddr: addr,\n coordinator,\n path: 'standalone' as const,\n identity,\n kind: event.kind,\n feeEstimate: fee,\n ...(opts.extra ?? {}),\n };\n\n if (!flags.json) {\n for (const line of renderEventPlan({ action, addr, identity, fee }))\n io.out(line);\n io.out(`Coordinator: ${coordinator}`);\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n ...base,\n executed: false,\n hint: 'estimate only — re-run with --yes to publish (permanent, non-refundable)',\n } satisfies CiEventJsonOutput);\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 const receipt = await standaloneCtx.publisher.publishEvent(\n event,\n relaysUsed\n );\n const result = serializeEventReceipt(event.kind, receipt);\n if (flags.json) {\n io.emitJson({\n ...base,\n executed: true,\n result,\n } satisfies CiEventJsonOutput);\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 ci request / stop\n// ---------------------------------------------------------------------------\n\nasync function runCiControl(\n kind: 'request' | 'stop',\n args: string[],\n deps: CiDeps\n): Promise<number> {\n const { io } = deps;\n const usage = kind === 'request' ? CI_REQUEST_USAGE : CI_STOP_USAGE;\n let flags: CommonFlags;\n let coordinator: string;\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(usage);\n return 0;\n }\n if (positionals.length > 1) {\n throw new Error(\n `expected exactly one <coordinator>, got ${positionals.length} positionals`\n );\n }\n coordinator = parseCoordinator(positionals);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(usage);\n return 2;\n }\n return runCiEvent({\n command: kind === 'request' ? 'ci request' : 'ci stop',\n flags,\n deps,\n coordinator,\n actionLabel: `CI service ${kind} → ${coordinator.slice(0, 8)}…`,\n buildEvent: async ({ addr, relayUrl, createdAt }) => {\n const a = repoAddress(addr.ownerPubkey, addr.repoId);\n return kind === 'request'\n ? buildCiServiceRequest(a, coordinator, relayUrl, createdAt)\n : buildCiServiceStop(a, coordinator, relayUrl, createdAt);\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// rig ci trigger\n// ---------------------------------------------------------------------------\n\nconst REF_RE = /^refs\\/(heads|tags)\\/[^\\s]+$/;\n\nasync function runCiTrigger(args: string[], deps: CiDeps): Promise<number> {\n const { io } = deps;\n let flags: CommonFlags;\n let coordinator: string;\n let workflowPath: string;\n let commitArg: string;\n let ref: string | undefined;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: {\n ...COMMON_OPTIONS,\n workflow: { type: 'string' },\n commit: { type: 'string' },\n ref: { type: 'string' },\n },\n allowPositionals: true,\n });\n flags = pickCommon(values);\n if (flags.help) {\n io.out(CI_TRIGGER_USAGE);\n return 0;\n }\n if (positionals.length > 1) {\n throw new Error(\n `expected exactly one <coordinator>, got ${positionals.length} positionals`\n );\n }\n coordinator = parseCoordinator(positionals);\n if (values.workflow === undefined || values.workflow === '') {\n throw new Error('--workflow <path> is required');\n }\n workflowPath = values.workflow.replace(/^\\.\\//, '');\n if (\n workflowPath.startsWith('/') ||\n workflowPath.split('/').includes('..')\n ) {\n throw new Error('--workflow must be a path relative to the repo root');\n }\n commitArg = values.commit ?? 'HEAD';\n ref = values.ref;\n if (ref !== undefined && !REF_RE.test(ref)) {\n throw new Error(\n `--ref must look like refs/heads/<name> or refs/tags/<name> (got ${JSON.stringify(ref)})`\n );\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CI_TRIGGER_USAGE);\n return 2;\n }\n\n // The workflow's content hash comes from the LOCAL repository: resolve it\n // before anything is paid so a typo in --workflow/--commit costs nothing.\n let commit: string;\n let sha256: string;\n try {\n const repoRoot = await resolveRepoRoot(deps.cwd);\n commit = (\n await runGit(repoRoot, ['rev-parse', '--verify', `${commitArg}^{commit}`])\n ).trim();\n const content = await gitShowBytes(repoRoot, commit, workflowPath);\n sha256 = sha256Hex(content);\n } catch (err) {\n return emitCliError(io, flags.json, 'ci trigger', err);\n }\n\n return runCiEvent({\n command: 'ci trigger',\n flags,\n deps,\n coordinator,\n actionLabel: `manual trigger ${workflowPath} @ ${commit.slice(0, 8)} → ${coordinator.slice(0, 8)}…`,\n extra: {\n commit,\n workflow: { path: workflowPath, sha256 },\n ...(ref !== undefined ? { ref } : {}),\n },\n buildEvent: async ({ addr, createdAt }) =>\n buildCiManualTrigger(\n coordinator,\n {\n repoAddr: repoAddress(addr.ownerPubkey, addr.repoId),\n commit,\n workflow: { path: workflowPath, sha256 },\n ...(ref !== undefined ? { ref } : {}),\n },\n createdAt\n ),\n });\n}\n\n/** `git show <commit>:<path>` as raw bytes (binary-safe). */\nasync function gitShowBytes(\n repoRoot: string,\n commit: string,\n path: string\n): Promise<Buffer> {\n const { execFile } = await import('node:child_process');\n return new Promise((resolve, reject) => {\n execFile(\n 'git',\n ['show', `${commit}:${path}`],\n { cwd: repoRoot, encoding: 'buffer', maxBuffer: 16 * 1024 * 1024 },\n (err, stdout, stderr) => {\n if (err) {\n reject(\n new Error(\n `cannot read ${path} at ${commit.slice(0, 12)} from the local repository: ` +\n `${stderr.toString('utf-8').trim() || err.message}`\n )\n );\n return;\n }\n resolve(stdout);\n }\n );\n });\n}\n\n// ---------------------------------------------------------------------------\n// rig ci secret set | remove\n// ---------------------------------------------------------------------------\n\n/**\n * Name grammar + the reserved name. Never echoes the argument: a mistyped\n * `rig ci secret set <c> hunter2` (no `NAME=`) would otherwise print the value.\n */\nfunction assertSecretName(name: string, position: number): void {\n if (!SECRET_NAME_RE.test(name)) {\n throw new Error(\n `invalid secret name in argument ${position} — NAME must match [A-Z_][A-Z0-9_]* (the argument is not shown)`\n );\n }\n if (RESERVED_SECRET_NAMES.includes(name)) {\n throw new Error(\n `secret name ${name} is reserved by NIP-C1 and cannot be set`\n );\n }\n}\n\nasync function runCiSecret(args: string[], deps: CiDeps): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n if (sub === '--help' || sub === '-h' || sub === 'help' || sub === undefined) {\n if (sub === undefined) {\n io.err('missing subcommand: rig ci secret <set|remove>');\n io.err(CI_SECRET_USAGE);\n return 2;\n }\n io.out(CI_SECRET_USAGE);\n return 0;\n }\n if (sub !== 'set' && sub !== 'remove') {\n io.err(`unknown rig ci secret subcommand: ${sub}`);\n io.err(CI_SECRET_USAGE);\n return 2;\n }\n\n let flags: CommonFlags;\n let coordinator: string;\n const set: Record<string, string> = {};\n const remove: string[] = [];\n let stdinName: string | undefined;\n try {\n const { values, positionals } = parseArgs({\n args: rest,\n options: COMMON_OPTIONS,\n allowPositionals: true,\n });\n flags = pickCommon(values);\n if (flags.help) {\n io.out(CI_SECRET_USAGE);\n return 0;\n }\n coordinator = parseCoordinator(positionals);\n const entries = positionals.slice(1);\n if (entries.length === 0) {\n throw new Error(\n sub === 'set'\n ? 'at least one NAME[=value] is required'\n : 'at least one NAME is required'\n );\n }\n const seen = new Set<string>();\n for (const [index, entry] of entries.entries()) {\n const position = index + 1;\n const eq = entry.indexOf('=');\n const name = eq === -1 ? entry : entry.slice(0, eq);\n assertSecretName(name, position);\n if (seen.has(name))\n throw new Error(`secret name ${name} given more than once`);\n seen.add(name);\n if (sub === 'remove') {\n if (eq !== -1)\n throw new Error(\n `rig ci secret remove takes bare names — argument ${position} is NAME=value`\n );\n remove.push(name);\n } else if (eq === -1) {\n if (stdinName !== undefined) {\n throw new Error(\n 'only one bare NAME can read its value from stdin per invocation'\n );\n }\n stdinName = name;\n } else {\n set[name] = entry.slice(eq + 1);\n }\n }\n if (stdinName !== undefined) {\n const value = io.isInteractive\n ? ''\n : await (deps.readStdin ?? defaultReadStdin)();\n // Trailing newline from `echo`/heredocs is never part of a secret.\n const trimmed = value.replace(/\\r?\\n$/, '');\n if (trimmed === '') {\n throw new Error(\n `secret ${stdinName}: no value on stdin (pipe the value, or pass ${stdinName}=<value>)`\n );\n }\n set[stdinName] = trimmed;\n }\n // Every NIP-C1 limit — empty or oversized values, too many names, the\n // whole-plaintext bound — before any relay or wallet is touched. The real\n // author and created_at are bound later; their serialized width is fixed.\n serializeSecretUpdate({\n author: '0'.repeat(64),\n created_at: 9_999_999_999,\n set,\n remove,\n });\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CI_SECRET_USAGE);\n return 2;\n }\n\n const names = [...Object.keys(set), ...remove];\n return runCiEvent({\n command: sub === 'set' ? 'ci secret set' : 'ci secret remove',\n flags,\n deps,\n coordinator,\n actionLabel: `secret ${sub} ${names.join(', ')} → ${coordinator.slice(0, 8)}…`,\n extra: { names, operation: sub },\n buildEvent: async ({\n addr,\n identity,\n relayUrl,\n webSocketFactory,\n createdAt,\n }) => {\n const advertisement = await fetchLiveAdvertisement(\n relayUrl,\n coordinator,\n webSocketFactory,\n createdAt\n );\n if (!advertisement.secretsKey) {\n throw new Error(\n `coordinator ${coordinator.slice(0, 12)}… advertises no secrets-key — it is not accepting secret updates`\n );\n }\n // NIP-C1: the plaintext binds to the signer + timestamp; the `a` tag's\n // pubkey MUST equal the signer, so the update is scoped to the\n // maintainer's OWN repository perspective.\n const plain: SecretUpdatePlaintext = {\n author: identity.pubkey,\n created_at: createdAt,\n set,\n remove,\n };\n const sender = generateSecretsKey();\n const ciphertext = encryptSecretUpdate(\n plain,\n sender.secretKey,\n advertisement.secretsKey.pubkey\n );\n sender.secretKey.fill(0);\n return buildCiSecretUpdate({\n repoAddr: repoAddress(identity.pubkey, addr.repoId),\n coordinatorPubkey: coordinator,\n advertisementId: advertisement.eventId,\n advertisementRelayHint: relayUrl,\n senderPubkey: sender.pubkey,\n recipientPubkey: advertisement.secretsKey.pubkey,\n ciphertext,\n createdAt,\n });\n },\n });\n}\n\n/**\n * The coordinator's CURRENT kind:19843 (latest by created_at, ties → lowest\n * id) — unexpired as of `now`. Throws with a clear remedy when absent.\n */\nasync function fetchLiveAdvertisement(\n relayUrl: string,\n coordinator: string,\n webSocketFactory: WebSocketFactory,\n now: number\n): Promise<CiAdvertisement> {\n const events = await queryRelay(\n relayUrl,\n { kinds: [CI_ADVERTISEMENT_KIND], authors: [coordinator] },\n 10_000,\n webSocketFactory\n );\n let latest: NostrEvent | null = null;\n for (const ev of events) {\n if (ev.pubkey.toLowerCase() !== coordinator) continue;\n if (\n latest === null ||\n ev.created_at > latest.created_at ||\n (ev.created_at === latest.created_at && ev.id < latest.id)\n ) {\n latest = ev;\n }\n }\n const parsed = latest ? parseCiAdvertisement(latest) : null;\n if (!parsed) {\n throw new Error(\n `no Coordinator Advertisement (kind:19843) from ${coordinator.slice(0, 12)}… on ${relayUrl} — ` +\n 'is the coordinator running (`rig ci serve`)?'\n );\n }\n if (parsed.expiresAt <= now) {\n throw new Error(\n `the Coordinator Advertisement from ${coordinator.slice(0, 12)}… expired at ${parsed.expiresAt} — ` +\n 'the coordinator is not live; secrets cannot be delivered'\n );\n }\n return parsed;\n}\n\n// ---------------------------------------------------------------------------\n// Dispatch\n// ---------------------------------------------------------------------------\n\n/** Run `rig ci …`; returns the process exit code. */\nexport async function runCi(args: string[], deps: CiDeps): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n switch (sub) {\n case 'request':\n return runCiControl('request', rest, deps);\n case 'stop':\n return runCiControl('stop', rest, deps);\n case 'trigger':\n return runCiTrigger(rest, deps);\n case 'secret':\n return runCiSecret(rest, deps);\n case 'status':\n return runCiStatus(rest, deps);\n case 'serve':\n return (await import('./ci-serve.js')).runCiServe(rest, deps);\n case '--help':\n case '-h':\n case 'help':\n io.out(CI_USAGE);\n io.out('');\n io.out(CI_STATUS_USAGE);\n return 0;\n default:\n io.err(\n sub === undefined\n ? 'missing subcommand: rig ci <request|stop|trigger|secret|status|serve>'\n : `unknown rig ci subcommand: ${sub}`\n );\n io.err(CI_USAGE);\n return 2;\n }\n}\n","/**\n * `rig clone` (#278) — bootstrap a repository from TOON, no payments anywhere:\n *\n * rig clone <relay-url> <owner-npub-or-hex>/<repo-id> [dir]\n *\n * Pipeline: fetch kind:30617/30618 from the relay (../remote-state.ts) →\n * download every object the refs need from Arweave gateways with SHA-1\n * verification (../read-pipeline.ts) → materialize a REAL git repository via\n * git plumbing (../materialize.ts): `git hash-object -w --stdin -t <type>`\n * per object (written SHA re-checked), `git update-ref` per ref, HEAD from\n * the 30618 symref, worktree checkout. The clone is immediately push/pull\n * capable: toon.repoid/toon.owner are configured and the relay is added as\n * the `origin` remote.\n *\n * ATOMICITY: everything lands in a temp dir next to the destination and is\n * renamed into place only on full success — a failed clone never leaves a\n * partial/corrupt repository. Missing objects (Arweave propagation lag) are\n * an honest error listing the SHAs; corrupt objects are an integrity error.\n */\n\nimport { mkdtemp, mkdir, readdir, rename, rm, rmdir } from 'node:fs/promises';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { readGateways } from '../gateway-preference.js';\nimport { shaResolverFor } from '../git-sha-resolver.js';\nimport {\n setHeadSymref,\n isSafeRefname,\n runGit,\n updateRef,\n writeGitObjects,\n} from '../materialize.js';\nimport { npubToHex, ownerToHex } from '../npub.js';\nimport {\n collectRepoObjects,\n missingObjectsMessage,\n type MissingObject,\n} from '../read-pipeline.js';\nimport { fetchRemoteState, type RemoteState } from '../remote-state.js';\nimport { emitCliError } from './errors.js';\nimport type { ReadCommandDeps } from './read-seams.js';\n\nexport const CLONE_USAGE = `Usage: rig clone <relay-url> <owner>/<repo-id> [dir] [options]\n\nClone a TOON repository — FREE (relay reads + Arweave gateway downloads; no\npayments, no channel, no identity needed). <relay-url> is a ws:// or wss://\nNIP-01 relay; <owner> is the repo owner's pubkey as npub1… or 64-char hex;\n[dir] defaults to <repo-id>.\n\nFetches the kind:30617/30618 repository state, downloads every git object\nthe refs need from Arweave gateways (SHA-1 verified — corrupt content is\nrejected), and materializes a real git repository: objects via git plumbing,\nrefs, HEAD, checked-out worktree, toon.* config, and the relay preconfigured\nas the \"origin\" remote — so \\`rig fetch\\`, \\`rig push\\`, and the issue/pr\ncommands work immediately.\n\nNote: recently pushed objects can take 10-20 minutes to become fetchable\nfrom Arweave gateways. A clone right after a push may report missing\nobjects — retry after propagation.\n\nOptions:\n --gateway <url> gateway to read objects through FIRST, on its raw-bytes\n route <url>/raw/<txId>, ahead of the public gateway\n list — name a private, local or air-gapped gateway to\n clone a repo the public ones do not carry\n (env RIG_ARWEAVE_GATEWAY also sets it)\n --concurrency <n> parallel gateway downloads (default 8)\n --json machine-readable result envelope\n -h, --help show this help`;\n\n/** Repo has no announcement AND no state on the relay. */\nexport class RepoNotFoundError extends Error {\n constructor(relay: string, owner: string, repoId: string) {\n super(\n `repository 30617:${owner}:${repoId} not found on ${relay} — ` +\n 'no kind:30617 announcement or kind:30618 state event exists there. ' +\n 'Check the relay URL, the owner pubkey (npub or hex), and the repo id.'\n );\n this.name = 'RepoNotFoundError';\n }\n}\n\n/** Reachable objects could not be downloaded (Arweave propagation lag). */\nexport class MissingRemoteObjectsError extends Error {\n constructor(\n public readonly missing: MissingObject[],\n context: string\n ) {\n super(missingObjectsMessage(missing, context));\n this.name = 'MissingRemoteObjectsError';\n }\n}\n\nconst WS_URL_RE = /^wss?:\\/\\//i;\n\ninterface CloneArgs {\n relayUrl: string;\n owner: string;\n repoId: string;\n dir: string | undefined;\n concurrency: number | undefined;\n /** `--gateway` as given; absent → RIG_ARWEAVE_GATEWAY, else no override. */\n gateway: string | undefined;\n json: boolean;\n}\n\nfunction parseCloneArgs(args: string[]): CloneArgs | { help: true } {\n const { values, positionals } = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n concurrency: { type: 'string' },\n gateway: { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: true,\n });\n if (values.help) return { help: true };\n if (positionals.length < 2 || positionals.length > 3) {\n throw new Error('expected: rig clone <relay-url> <owner>/<repo-id> [dir]');\n }\n const [relayUrl, addr, dir] = positionals as [string, string, string?];\n if (!WS_URL_RE.test(relayUrl)) {\n throw new Error(\n `<relay-url> must be ws:// or wss:// (got ${JSON.stringify(relayUrl)})`\n );\n }\n const slash = addr.indexOf('/');\n if (slash <= 0 || slash === addr.length - 1) {\n throw new Error(\n `expected <owner>/<repo-id> (npub or 64-char hex owner), got ${JSON.stringify(addr)}`\n );\n }\n const owner = ownerToHex(addr.slice(0, slash));\n const repoId = addr.slice(slash + 1);\n let concurrency: number | undefined;\n if (values.concurrency !== undefined) {\n concurrency = Number.parseInt(values.concurrency, 10);\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) {\n throw new Error(`--concurrency must be a positive integer`);\n }\n }\n return {\n relayUrl,\n owner,\n repoId,\n dir,\n concurrency,\n gateway: values.gateway,\n json: values.json === true,\n };\n}\n\n/** True when `dir` does not exist or is an empty directory. */\nasync function isUsableDestination(dir: string): Promise<boolean> {\n try {\n const entries = await readdir(dir);\n return entries.length === 0;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'ENOENT';\n }\n}\n\n/** Pick the branch `git init --initial-branch` should use. */\nfunction initialBranch(headSymref: string | null): string {\n if (headSymref?.startsWith('refs/heads/')) {\n const name = headSymref.slice('refs/heads/'.length);\n if (name && isSafeRefname(headSymref)) return name;\n }\n return 'main';\n}\n\n/** Run `rig clone …`; returns the process exit code. */\nexport async function runClone(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let parsed: CloneArgs;\n try {\n const result = parseCloneArgs(args);\n if ('help' in result) {\n io.out(CLONE_USAGE);\n return 0;\n }\n parsed = result;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(CLONE_USAGE);\n return 2;\n }\n\n const { relayUrl, owner, repoId, json } = parsed;\n const dest = resolve(deps.cwd, parsed.dir ?? repoId);\n let tempDir: string | undefined;\n\n try {\n if (!(await isUsableDestination(dest))) {\n throw new Error(\n `destination path ${JSON.stringify(dest)} already exists and is not an empty directory`\n );\n }\n\n if (!json) io.out(`Cloning into '${basename(dest)}'...`);\n\n // ── Remote state (kind:30617 + 30618) ───────────────────────────────────\n const remoteState: RemoteState = await fetchRemoteState({\n relayUrls: [relayUrl],\n ownerPubkey: owner,\n repoId,\n ...(deps.webSocketFactory\n ? { webSocketFactory: deps.webSocketFactory }\n : {}),\n // The GraphQL fallback for SHAs the map does not cover asks the SAME\n // permaweb the objects are read from (#183).\n resolveSha: deps.resolveSha ?? shaResolverFor(parsed.gateway, deps.env),\n });\n if (!remoteState.announced && remoteState.refsEvent === null) {\n throw new RepoNotFoundError(relayUrl, owner, repoId);\n }\n\n // Refs from the 30618, filtered through the hostile-relay refname gate.\n const refs = new Map<string, string>();\n for (const [refname, sha] of remoteState.refs) {\n if (!isSafeRefname(refname)) {\n io.err(\n `warning: skipping unsafe ref name from relay: ${JSON.stringify(refname)}`\n );\n continue;\n }\n refs.set(refname, sha);\n }\n if (refs.size === 0) {\n io.err(\n 'warning: the repository has no refs yet (announced but never pushed) — ' +\n 'cloning an empty repository'\n );\n }\n\n // ── Download + verify the object closure (FREE) ─────────────────────────\n const tips = [...new Set(refs.values())];\n const collected = await collectRepoObjects({\n tips,\n shaToTxId: remoteState.shaToTxId,\n resolveMissing: (shas) => remoteState.resolveMissing(shas),\n // `--gateway` / RIG_ARWEAVE_GATEWAY first, public list behind it (#176).\n gateways: readGateways(parsed.gateway, deps.env),\n ...(deps.fetchFn ? { fetchFn: deps.fetchFn } : {}),\n ...(parsed.concurrency !== undefined\n ? { concurrency: parsed.concurrency }\n : {}),\n });\n if (collected.missing.length > 0) {\n throw new MissingRemoteObjectsError(\n collected.missing,\n `cannot clone ${owner.slice(0, 8)}…/${repoId}`\n );\n }\n for (const { sha, txId } of collected.skippedUnavailable) {\n io.err(\n `warning: unreachable object ${sha} (tx ${txId}) could not be downloaded — ` +\n 'not needed by any ref, continuing'\n );\n }\n\n // ── Materialize into a temp dir, move into place on success ────────────\n const parent = dirname(dest);\n await mkdir(parent, { recursive: true });\n tempDir = await mkdtemp(join(parent, `.${basename(dest)}.rig-clone-`));\n\n await runGit(tempDir, [\n 'init',\n '--quiet',\n `--initial-branch=${initialBranch(remoteState.headSymref)}`,\n ]);\n const written = await writeGitObjects(tempDir, collected.objects.values());\n for (const [refname, sha] of refs) {\n await updateRef(tempDir, refname, sha);\n // Remote-tracking refs, exactly like `git clone` — so `rig fetch`\n // reports honest deltas and `rig merge origin/<branch>` works.\n if (refname.startsWith('refs/heads/')) {\n const branch = refname.slice('refs/heads/'.length);\n await updateRef(tempDir, `refs/remotes/origin/${branch}`, sha);\n }\n }\n const head =\n remoteState.headSymref !== null &&\n isSafeRefname(remoteState.headSymref) &&\n refs.has(remoteState.headSymref)\n ? remoteState.headSymref\n : ([...refs.keys()].find((r) => r.startsWith('refs/heads/')) ?? null);\n if (head !== null) {\n await setHeadSymref(tempDir, head);\n await runGit(tempDir, ['reset', '--hard', '--quiet']);\n }\n\n // toon.* config + origin remote: immediately push/pull-capable.\n await runGit(tempDir, ['config', 'toon.repoid', repoId]);\n await runGit(tempDir, ['config', 'toon.owner', owner]);\n await runGit(tempDir, ['remote', 'add', 'origin', relayUrl]);\n if (head !== null) {\n // Upstream config for the checked-out branch, like `git clone`.\n const branch = head.slice('refs/heads/'.length);\n await runGit(tempDir, ['config', `branch.${branch}.remote`, 'origin']);\n await runGit(tempDir, ['config', `branch.${branch}.merge`, head]);\n }\n\n // Atomic move into place (destination may exist as an empty directory).\n try {\n await rmdir(dest);\n } catch {\n // ENOENT — the destination does not exist yet; rename creates it.\n }\n await rename(tempDir, dest);\n tempDir = undefined;\n\n // ── Report ──────────────────────────────────────────────────────────────\n if (json) {\n io.emitJson({\n command: 'clone',\n repoAddr: { ownerPubkey: owner, repoId },\n relay: relayUrl,\n directory: dest,\n head,\n refs: Object.fromEntries(refs),\n name: remoteState.name,\n objectsDownloaded: written,\n executed: true,\n });\n } else {\n io.out(`Downloaded ${written} object(s) from Arweave (SHA-1 verified).`);\n for (const [refname, sha] of refs) {\n io.out(` ${sha.slice(0, 7)} ${refname}`);\n }\n if (head !== null) io.out(`HEAD is now at ${head}`);\n io.out(\n `Configured toon.repoid=${repoId}, toon.owner=${owner.slice(0, 8)}…, ` +\n `origin → ${relayUrl}`\n );\n io.out('Done.');\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'clone', err);\n } finally {\n if (tempDir !== undefined) {\n await rm(tempDir, { recursive: true, force: true }).catch(\n () => undefined\n );\n }\n }\n}\n\n// Re-exported for the acceptance flow + tests (owner column rendering).\nexport { npubToHex };\n","/**\n * The single-event `rig` subcommands (#231): issue / comment / pr, where\n * `pr` nests `create` and `status` (#250 moved the NIP-34 status publish\n * from top-level `rig status` to `rig pr status` — bare `rig status` now\n * passes through to `git status`).\n *\n * One shared pipeline behind four thin arg-parsers, mirroring `rig push`\n * (./push.ts) exactly: repo addressing from the `toon.*` git config keys\n * `rig init` writes (`--repo-id`/`--owner` override; actionable \"run\n * `rig init`\" error when unconfigured), a fee-quoting confirm gate (`--yes`\n * skips; a non-TTY session without it refuses; `--json` without `--yes` is a\n * pure estimate), and two transports (#279, ./daemon-session.ts):\n *\n * standalone (default + guarantee) — build the NIP-34 event locally\n * (../nip34-events.ts — the same builders the toon-clientd daemon uses)\n * and pay-to-publish through the embedded, nonce-guarded\n * StandalonePublisher;\n * daemon (automatic fast path) — when a running toon-clientd holds the\n * SAME identity, delegate to its loopback POST\n * /git/issue|comment|patch|status route instead: the daemon builds,\n * signs, and pays from its warm bootstrap, and it owns the channel\n * watermark (the safety goal the old refusal protected). NOTE: the\n * single-event daemon routes publish via the daemon's own configured\n * relay route — a resolved relay that differs from it draws a warning.\n *\n * The relay resolves like `rig push` (#249): `--remote <name>`\n * (default: the `origin` git remote), `--relay <url>` as an ad-hoc override\n * that bypasses remotes, deprecated `git config toon.relay` as a nudged\n * fallback. Publishes go to a SINGLE relay; multiple configured relays and\n * multi-URL remotes are refused before anything is paid (same guard as push).\n *\n * `rig pr create --range` runs REAL `git format-patch --stdout <range>` in\n * the local repository and publishes its output as the kind:1617 content —\n * one event for the whole series (cover-letter threading is out of scope in\n * v1; see the usage text).\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { parseArgs } from 'node:util';\nimport {\n STATUS_APPLIED_KIND,\n STATUS_CLOSED_KIND,\n STATUS_DRAFT_KIND,\n STATUS_OPEN_KIND,\n} from '@toon-protocol/core/nip34';\nimport {\n COMMENT_KIND,\n LEGACY_COMMENT_KIND,\n authorizedStatusAuthors,\n buildComment,\n buildIssue,\n buildPatch,\n buildStatus,\n firstTagValue,\n type CommentParent,\n type CommentRoot,\n type StatusKind,\n type UnsignedEvent,\n} from '../nip34-events.js';\nimport {\n defaultWebSocketFactory,\n fetchRemoteState,\n queryRelay,\n} from '../remote-state.js';\nimport { GitRepoReader } from '../repo-reader.js';\nimport {\n serializeEventReceipt,\n type GitEventResponse,\n type GitRepoAddr,\n type GitStatusValue,\n} from '../routes.js';\nimport {\n type DaemonGitClient,\n type SessionPath,\n} from './daemon-session.js';\nimport { emitCliError, UnconfiguredRepoAddressError } from './errors.js';\nimport { readToonConfig, resolveRepoRoot, type ToonRepoConfig } from './git-config.js';\nimport {\n identityReport,\n loadPaidSession,\n withForcedStandalone,\n type IdentityReport,\n type PushDeps,\n} from './push.js';\nimport type { ReadSeams } from './read-seams.js';\nimport { resolveRelays, singleRelayRefusal } from './remote.js';\nimport { feeLabel, renderEventPlan, renderEventReceipt } from './render.js';\nimport type { StandaloneContext } from './standalone-context.js';\nimport {\n ISSUE_LIST_USAGE,\n ISSUE_SHOW_USAGE,\n PR_LIST_USAGE,\n PR_SHOW_USAGE,\n runIssueList,\n runIssueShow,\n runPrList,\n runPrShow,\n} from './tracker.js';\n\n// ---------------------------------------------------------------------------\n// Deps\n// ---------------------------------------------------------------------------\n\n/**\n * Push deps plus a stdin reader (issue-body fallback) and the #278 read-path\n * seams (relay WebSocket / gateway fetch / SHA resolver — used by the FREE\n * `issue list|show` and `pr list|show` subcommands); tests inject all.\n */\nexport interface EventCommandDeps extends PushDeps, ReadSeams {\n /** Read all of stdin as UTF-8 (default: the real process stdin). */\n readStdin?: () => Promise<string>;\n /**\n * Local root-commit lookup for the announcement's `euc` tag (#158) —\n * defaults to the resolved repo root's `GitRepoReader.rootCommits`, and is\n * absent when the command runs outside a git repo. Injectable so\n * announcement tests need no fixture repository.\n */\n rootCommits?: (rev?: string) => 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 --standalone always run embedded, bypassing a running toon-clientd\n (alias: --no-daemon; same as RIG_STANDALONE=1)\n -h, --help show this help`;\n\nexport const ISSUE_USAGE = `Usage: rig issue create --title <title> [options]\n\nFile an issue (kind:1621) against a TOON repo — a paid publish; writes are\npermanent and non-refundable. The repo address (30617:<owner>:<repoId>) comes\nfrom the toon.* git config keys \\`rig init\\` writes.\n\nBody source (exactly one): --body, --body-file, or piped stdin.\n\nOptions:\n --title <title> issue title (subject tag) [required]\n --body <text> issue body (Markdown)\n --body-file <path> read the issue body from a file\n --label <label> label (t tag); repeatable\n${COMMON_FLAGS_USAGE}\n\nRelated (FREE reads — no payment):\n rig issue list [--state open|closed|all] list the repo's issues\n rig issue show <event-id> one issue + its comments`;\n\nexport const COMMENT_USAGE = `Usage: rig comment <target-event-id> --body <text> [options]\n\nComment (NIP-22 kind:1111) on an issue or patch — a paid publish; writes are\npermanent and non-refundable. <target-event-id> is the 64-char hex id of\neither:\n\n the kind:1621 issue / kind:1617 patch being commented on → a top-level\n comment, whose NIP-22 root scope (E/K/P) and parent (e/k/p) both name it;\n an existing kind:1111 comment → a REPLY: the comment becomes the lowercase\n parent (k=1111) while the uppercase root stays the issue/patch it hangs\n off.\n\nThe target is read from the resolved relay first (a FREE read) so the root's\nkind and author are taken from the wire rather than guessed. The repo\ncoordinate rides along as an \\`a\\` tag for subscription filtering.\n\nOlder rig releases read only the legacy kind:1622 dialect and will NOT see\ncomments published by this version.\n\nOptions:\n --body <text> comment body (Markdown) [required]\n${COMMON_FLAGS_USAGE}`;\n\nexport const PR_CREATE_USAGE = `Usage: rig pr create --title <title> (--range <range> | --patch-file <path>) [options]\n\nPublish a patch (kind:1617) whose content is REAL \\`git format-patch\\` output —\na paid publish; writes are permanent and non-refundable. --range runs\n\\`git format-patch --stdout <range>\\` in the local repository and derives the\ncommit/parent-commit tags; --patch-file publishes a pre-generated patch\nverbatim. A multi-commit range publishes ONE kind:1617 event carrying the\nfull series text — cover-letter threading (one event per commit) is out of\nscope in v1.\n\nThe PR body (--body/--body-file) is carried in a dedicated \\`description\\`\ntag, not in the event content — the content stays pure format-patch output so\n\\`rig pr show … | git am\\` keeps working.\n\nOptions:\n --title <title> patch/PR title (subject tag) [required]\n --range <range> revision range for format-patch: <rev>, <rev>..<rev>,\n or <rev>...<rev> (mutually exclusive with --patch-file)\n --patch-file <path> literal patch text to publish\n --body <text> PR description (Markdown; description tag)\n --body-file <path> read the PR description from a file\n --branch <name> branch name (branch-name tag)\n${COMMON_FLAGS_USAGE}`;\n\nexport const PR_STATUS_USAGE = `Usage: rig pr status <target-event-id> <open|applied|closed|draft> [options]\n\nSet the status of an issue or patch — a paid publish; writes are permanent\nand non-refundable. Publishes kind:1630 (open), 1631 (applied), 1632\n(closed), or 1633 (draft) against the 64-char hex id of the target event,\nwith the repo a-tag attached so readers can scope a status stream to the\nrepository. (This command was \\`rig status\\` before v2 — bare \\`rig status\\`\nnow passes through to \\`git status\\`.)\n\nOptions:\n${COMMON_FLAGS_USAGE}`;\n\nexport const PR_USAGE = `${PR_CREATE_USAGE}\n\n${PR_STATUS_USAGE}\n\n${PR_LIST_USAGE}\n\n${PR_SHOW_USAGE}`;\n\n// ---------------------------------------------------------------------------\n// Shared flag parsing\n// ---------------------------------------------------------------------------\n\nconst HEX64_RE = /^[0-9a-f]{64}$/;\n\nfunction assertHex64(value: string, what: string): void {\n if (!HEX64_RE.test(value)) {\n throw new Error(\n `${what} must be a 64-char lowercase hex id (got ${JSON.stringify(value)})`\n );\n }\n}\n\n/** parseArgs options every subcommand accepts (mirrors `rig push`). */\nconst COMMON_OPTIONS = {\n yes: { type: 'boolean', default: false },\n json: { type: 'boolean', default: false },\n relay: { type: 'string', multiple: true },\n remote: { type: 'string' },\n 'repo-id': { type: 'string' },\n owner: { type: 'string' },\n standalone: { type: 'boolean', default: false },\n 'no-daemon': { type: 'boolean', default: false },\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 /** Force embedded standalone, bypassing the daemon (--standalone/--no-daemon). */\n standalone: boolean;\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 standalone: values['standalone'] === true || values['no-daemon'] === true,\n help: values['help'] === true,\n };\n const remote = values['remote'];\n if (typeof remote === 'string') flags.remote = remote;\n const repoId = values['repo-id'];\n if (typeof repoId === 'string') flags.repoId = repoId;\n const owner = values['owner'];\n if (typeof owner === 'string') {\n assertHex64(owner, '--owner');\n flags.owner = owner;\n }\n return flags;\n}\n\n// ---------------------------------------------------------------------------\n// Shared publish pipeline\n// ---------------------------------------------------------------------------\n\ntype EventCommand = 'issue' | 'comment' | 'pr' | 'pr status';\n\ninterface RunEventOptions {\n command: EventCommand;\n flags: CommonFlags;\n deps: EventCommandDeps;\n /** Human action label WITHOUT the kind, e.g. `issue \"Fix the flux\"`. */\n actionLabel: string;\n /**\n * Build the unsigned NIP-34 event for the resolved repo address — the\n * publish payload, and the source of truth for the kind. May do real work\n * (pr runs format-patch here), so failures land in the normal error path.\n * ALWAYS called (both paths) — the kind drives rendering, and the daemon\n * path reuses locally-derived values (e.g. the format-patch output, or\n * `rig comment`'s relay-resolved NIP-22 root). `relayUrl` is the single\n * resolved relay, `undefined` when none resolved.\n */\n buildEvent: (\n addr: GitRepoAddr,\n relayUrl: string | undefined\n ) => Promise<UnsignedEvent>;\n /**\n * Drive the matching daemon `/git/*` route (#279 delegated fast path).\n * Called only after the same-identity check and the confirm gate.\n */\n sendDaemon: (\n client: DaemonGitClient,\n addr: GitRepoAddr\n ) => Promise<GitEventResponse>;\n /**\n * Optional pre-confirm hook (#287): runs AFTER the identity + repo address\n * are resolved and the event is built, but BEFORE the plan is rendered and\n * the confirm gate. Used by `pr status` to WARN when the active identity is\n * not an authorized maintainer of the target repo (the write is still\n * allowed — the relay is permissionless — but clients honoring repo\n * authority will ignore it). Failures here must be non-fatal: emit a soft\n * note and proceed. The warning prints to stderr so the existing confirm\n * gate (or --yes) still governs whether money moves.\n */\n preConfirm?: (args: {\n identity: IdentityReport;\n addr: GitRepoAddr;\n relayUrl: string | undefined;\n }) => Promise<void>;\n}\n\n/** JSON envelope emitted by `--json` runs (agents consume this). */\ninterface EventJsonOutput {\n command: EventCommand;\n repoAddr: GitRepoAddr;\n /** Which transport paid: delegated daemon or embedded standalone (#279). */\n path: SessionPath;\n /** Active identity: source tier + derived pubkey (never the phrase). */\n identity: IdentityReport;\n /** NIP-34 kind this command publishes. */\n kind: number;\n /** True when the paid publish ran. */\n executed: boolean;\n /** Per-event fee (base units, decimal string). */\n feeEstimate: string | null;\n result?: GitEventResponse;\n hint?: string;\n}\n\n/**\n * The estimate → confirm → execute flow shared by all four subcommands.\n * Money moves only after the confirm gate and the single-relay guard.\n */\nasync function runEvent(opts: RunEventOptions): Promise<number> {\n const { command, flags, actionLabel } = opts;\n // --standalone/--no-daemon: force embedded for this invocation (same as\n // RIG_STANDALONE=1). Every paid path reads the override from `env`.\n const deps = flags.standalone\n ? withForcedStandalone(opts.deps)\n : opts.deps;\n const { io } = deps;\n\n let standaloneCtx: StandaloneContext | undefined;\n try {\n // ── Repo addressing (best-effort git config; flags can stand alone) ─────\n let repoRoot: string | undefined;\n let toonConfig: ToonRepoConfig = { relays: [] };\n try {\n repoRoot = await resolveRepoRoot(deps.cwd);\n toonConfig = await readToonConfig(repoRoot);\n } catch {\n // Not inside a git repository — --repo-id/--owner must carry the address.\n }\n const repoId = flags.repoId ?? toonConfig.repoId;\n if (!repoId) throw new UnconfiguredRepoAddressError('repository id');\n\n // ── Relay resolution (#249: --relay > --remote > origin > toon.relay) ───\n const resolved = await resolveRelays({\n relayFlags: flags.relay,\n remoteName: flags.remote,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n if (resolved.nudge !== undefined) io.err(resolved.nudge);\n const relaysUsed = resolved.relays;\n // Same pre-pay guard as push: StandalonePublisher publishes to exactly\n // one relay, and multiple can arrive without explicit intent (repeated\n // --relay flags, an old multi-valued git config `toon.relay`). Refuse\n // before anything is paid.\n if (relaysUsed.length > 1) {\n io.err(singleRelayRefusal(resolved, 'Nothing was published or paid.'));\n return 1;\n }\n\n // ── Paid session (#279): same-identity daemon → delegate; else the\n // standalone context (identity chain + nonce guard) + per-event fee.\n const session = await loadPaidSession(deps, relaysUsed[0]);\n const path = session.path;\n let identity: IdentityReport;\n let fee: string | undefined;\n if (session.path === 'standalone') {\n standaloneCtx = session.ctx;\n identity = identityReport(standaloneCtx);\n fee = (await standaloneCtx.publisher.getFeeRates()).eventFee.toString();\n } else {\n identity = session.identity;\n fee = session.feePerEvent;\n // The single-event /git/* routes publish via the daemon's own\n // configured relay route (no relayUrls field on the wire) — surface a\n // mismatch instead of silently ignoring the resolved relay.\n const resolvedRelay = relaysUsed[0];\n if (\n resolvedRelay !== undefined &&\n session.daemonRelayUrl !== undefined &&\n session.daemonRelayUrl !== resolvedRelay\n ) {\n io.err(\n `rig: the daemon publishes via its configured relay ` +\n `(${session.daemonRelayUrl}), not the resolved relay ` +\n `(${resolvedRelay}) — stop the daemon to force the standalone ` +\n 'path if that matters'\n );\n }\n }\n\n const owner = flags.owner ?? toonConfig.owner ?? identity.pubkey;\n const addr: GitRepoAddr = { ownerPubkey: owner, repoId };\n\n // Built once: the publish payload AND the kind for rendering.\n const event = await opts.buildEvent(addr, relaysUsed[0]);\n const action = `kind:${event.kind} ${actionLabel}`;\n\n // ── Authority pre-check (#287) — warn (do not block) before the gate ────\n if (opts.preConfirm) {\n await opts.preConfirm({ identity, addr, relayUrl: relaysUsed[0] });\n }\n\n // ── Confirm gate (identical semantics to `rig push`) ────────────────────\n if (!flags.json) {\n for (const line of renderEventPlan({\n action,\n addr,\n identity,\n ...(fee !== undefined ? { fee } : {}),\n })) {\n io.out(line);\n }\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: addr,\n path,\n identity,\n kind: event.kind,\n executed: false,\n feeEstimate: fee ?? null,\n hint: 'estimate only — re-run with --yes to publish (permanent, non-refundable)',\n } satisfies EventJsonOutput);\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n 'refusing to spend channel funds without confirmation in a non-interactive ' +\n 'session — re-run with --yes (or use --json for an estimate)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Proceed with paid publish (${feeLabel(fee)})? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was published.');\n return 1;\n }\n }\n\n // ── Execute ─────────────────────────────────────────────────────────────\n let result: GitEventResponse;\n if (session.path === 'standalone') {\n const receipt = await session.ctx.publisher.publishEvent(\n event,\n relaysUsed\n );\n result = serializeEventReceipt(event.kind, receipt);\n } else {\n result = await opts.sendDaemon(session.client, addr);\n }\n\n // ── Receipts ────────────────────────────────────────────────────────────\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: addr,\n path,\n identity,\n kind: result.kind,\n executed: true,\n feeEstimate: fee ?? null,\n result,\n } satisfies EventJsonOutput);\n } else {\n for (const line of renderEventReceipt(action, result)) io.out(line);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, command, err);\n } finally {\n if (standaloneCtx) {\n try {\n await standaloneCtx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// rig issue create\n// ---------------------------------------------------------------------------\n\n/** Run `rig issue …`; returns the process exit code. */\nexport async function runIssue(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n if (sub === '--help' || sub === '-h' || sub === 'help') {\n io.out(ISSUE_USAGE);\n io.out('');\n io.out(ISSUE_LIST_USAGE);\n io.out('');\n io.out(ISSUE_SHOW_USAGE);\n return 0;\n }\n // FREE read subcommands (#278): relay queries only, no payment path.\n if (sub === 'list') return runIssueList(rest, deps);\n if (sub === 'show') return runIssueShow(rest, deps);\n if (sub !== 'create') {\n io.err(\n sub === undefined\n ? 'missing subcommand: rig issue <create|list|show>'\n : `unknown rig issue subcommand: ${sub}`\n );\n io.err(ISSUE_USAGE);\n return 2;\n }\n\n let flags: CommonFlags;\n let title: string;\n let bodyFlag: string | undefined;\n let bodyFile: string | undefined;\n let labels: string[];\n try {\n const { values } = parseArgs({\n args: rest,\n options: {\n ...COMMON_OPTIONS,\n title: { type: 'string' },\n body: { type: 'string' },\n 'body-file': { type: 'string' },\n label: { type: 'string', multiple: true },\n },\n allowPositionals: false,\n });\n flags = pickCommon(values);\n if (!flags.help && (values.title === undefined || values.title === '')) {\n throw new Error('--title is required');\n }\n if (values.body !== undefined && values['body-file'] !== undefined) {\n throw new Error('--body and --body-file are mutually exclusive');\n }\n title = values.title ?? '';\n bodyFlag = values.body;\n bodyFile = values['body-file'];\n labels = values.label ?? [];\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(ISSUE_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(ISSUE_USAGE);\n return 0;\n }\n\n // Body source: --body → --body-file → piped stdin.\n let body: string;\n if (bodyFlag !== undefined) {\n body = bodyFlag;\n } else if (bodyFile !== undefined) {\n try {\n body = await readFile(bodyFile, 'utf-8');\n } catch (err) {\n io.err(\n `cannot read --body-file ${bodyFile}: ${err instanceof Error ? err.message : String(err)}`\n );\n return 2;\n }\n } else if (!io.isInteractive) {\n body = await (deps.readStdin ?? defaultReadStdin)();\n } else {\n io.err('an issue body is required: pass --body/--body-file or pipe stdin');\n io.err(ISSUE_USAGE);\n return 2;\n }\n if (body.trim() === '') {\n io.err('the issue body is empty — nothing to publish');\n return 2;\n }\n\n return runEvent({\n command: 'issue',\n flags,\n deps,\n actionLabel: `issue ${JSON.stringify(title)}`,\n buildEvent: async (addr) =>\n buildIssue(addr.ownerPubkey, addr.repoId, title, body, labels),\n sendDaemon: (client, addr) =>\n client.gitIssue({\n repoAddr: addr,\n title,\n body,\n ...(labels.length > 0 ? { labels } : {}),\n }),\n });\n}\n\n// ---------------------------------------------------------------------------\n// rig comment\n// ---------------------------------------------------------------------------\n\n/** How long to wait for the relay when resolving a comment's target (#159). */\nconst TARGET_LOOKUP_TIMEOUT_MS = 10_000;\n\n/**\n * Read the event a `rig comment` targets off the relay and derive the NIP-22\n * threading it implies (#159).\n *\n * The root's KIND and AUTHOR are wire facts (`K`/`P`), not something the\n * caller should have to type or the CLI should guess — so the target is\n * fetched before anything is paid. Targeting a kind:1111 comment makes the\n * new comment a reply: that comment becomes the lowercase parent, while the\n * uppercase root is carried over from the parent's own `E`/`K`/`P`.\n */\nasync function resolveCommentTarget(\n deps: EventCommandDeps,\n targetEventId: string,\n relayUrl: string | undefined\n): Promise<{ root: CommentRoot; parent?: CommentParent }> {\n if (relayUrl === undefined) {\n throw new Error(\n 'no relay resolved — a comment needs the target event to derive its ' +\n 'NIP-22 root; pass --relay <url> or configure a remote'\n );\n }\n const found = await queryRelay(\n relayUrl,\n { ids: [targetEventId] },\n TARGET_LOOKUP_TIMEOUT_MS,\n deps.webSocketFactory ?? defaultWebSocketFactory\n );\n const target = found.find((e) => e.id === targetEventId);\n if (!target) {\n throw new Error(\n `event ${targetEventId} not found on ${relayUrl} — nothing was published or paid`\n );\n }\n\n if (target.kind === LEGACY_COMMENT_KIND) {\n throw new Error(\n `event ${targetEventId} is a legacy kind:1622 comment — replies to it ` +\n 'are not representable in NIP-22; comment on the issue or patch instead'\n );\n }\n\n if (target.kind === COMMENT_KIND) {\n // The root scope is carried over VERBATIM from the parent comment, so a\n // reply lands in the same thread. The relay is permissionless: validate\n // before copying a stranger's tags into an event we are about to pay for.\n const rootEventId = firstTagValue(target.tags, 'E');\n const rootKind = Number(firstTagValue(target.tags, 'K'));\n const rootAuthor = firstTagValue(target.tags, 'P');\n if (\n rootEventId === undefined ||\n !HEX64_RE.test(rootEventId) ||\n !Number.isSafeInteger(rootKind) ||\n rootAuthor === undefined ||\n !HEX64_RE.test(rootAuthor)\n ) {\n throw new Error(\n `kind:1111 comment ${targetEventId} carries no usable NIP-22 root ` +\n 'scope (E/K/P tags) — cannot derive the thread root to reply into'\n );\n }\n return {\n root: { eventId: rootEventId, kind: rootKind, authorPubkey: rootAuthor },\n parent: { eventId: target.id, authorPubkey: target.pubkey },\n };\n }\n\n return {\n root: {\n eventId: target.id,\n kind: target.kind,\n authorPubkey: target.pubkey,\n },\n };\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 targetEventId: string;\n let body: string;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: {\n ...COMMON_OPTIONS,\n body: { type: 'string' },\n // Retired by #159 — parsed only to explain the migration.\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 (values.marker !== undefined || values['parent-author'] !== undefined) {\n throw new Error(\n '--marker and --parent-author were removed with the move to NIP-22 ' +\n 'kind:1111 (#159): pass the comment you are replying to as ' +\n '<target-event-id> instead — its author and the thread root are ' +\n 'read from the relay'\n );\n }\n if (positionals.length !== 1) {\n throw new Error(\n positionals.length === 0\n ? '<target-event-id> is required'\n : `expected exactly one <target-event-id>, got ${positionals.length} positionals`\n );\n }\n targetEventId = positionals[0] as string;\n assertHex64(targetEventId, '<target-event-id>');\n if (values.body === undefined || values.body === '') {\n throw new Error('--body is required');\n }\n body = values.body;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(COMMENT_USAGE);\n return 2;\n }\n\n // Resolved once in buildEvent (always called, both transports) and reused\n // by the daemon request, so the CLI is the single place that reads the wire.\n let threading: { root: CommentRoot; parent?: CommentParent } | undefined;\n\n return runEvent({\n command: 'comment',\n flags,\n deps,\n actionLabel: `comment on ${targetEventId.slice(0, 8)}…`,\n buildEvent: async (addr, relayUrl) => {\n threading = await resolveCommentTarget(deps, targetEventId, relayUrl);\n return buildComment(\n addr.ownerPubkey,\n addr.repoId,\n threading.root,\n body,\n threading.parent\n );\n },\n sendDaemon: (client, addr) => {\n // runEvent always builds the event first, on both transports.\n if (threading === undefined) {\n throw new Error(\n 'internal: the comment target was not resolved before the publish'\n );\n }\n const { root, parent } = threading;\n return client.gitComment({\n repoAddr: addr,\n body,\n rootEventId: root.eventId,\n rootKind: root.kind,\n rootAuthorPubkey: root.authorPubkey,\n ...(parent !== undefined ? { parentComment: parent } : {}),\n });\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// rig pr create\n// ---------------------------------------------------------------------------\n\n/** `From <sha> <date>` separator lines of `git format-patch --stdout` output. */\nconst PATCH_FROM_RE = /^From ([0-9a-f]{40}) /gm;\n\n/** Commit SHAs of a format-patch series, in patch (oldest-first) order. */\nexport function extractPatchShas(patchText: string): string[] {\n return [...patchText.matchAll(PATCH_FROM_RE)].map((m) => m[1] as string);\n}\n\n/** Run `rig pr …` (nested dispatch: create | status); returns the exit code. */\nexport async function runPr(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n switch (sub) {\n case 'create':\n return runPrCreate(rest, deps);\n case 'status':\n return runPrStatus(rest, deps);\n // FREE read subcommands (#278): relay queries only, no payment path.\n case 'list':\n return runPrList(rest, deps);\n case 'show':\n return runPrShow(rest, deps);\n case '--help':\n case '-h':\n case 'help':\n io.out(PR_USAGE);\n return 0;\n default:\n io.err(\n sub === undefined\n ? 'missing subcommand: rig pr <create|status|list|show>'\n : `unknown rig pr subcommand: ${sub}`\n );\n io.err(PR_USAGE);\n return 2;\n }\n}\n\n/** `rig pr create` — kind:1617 patch publish. */\nasync function runPrCreate(\n rest: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let flags: CommonFlags;\n let title: string;\n let range: string | undefined;\n let patchFile: string | undefined;\n let branch: string | undefined;\n let bodyFlag: string | undefined;\n let bodyFile: string | undefined;\n try {\n const { values } = parseArgs({\n args: rest,\n options: {\n ...COMMON_OPTIONS,\n title: { type: 'string' },\n range: { type: 'string' },\n 'patch-file': { type: 'string' },\n body: { type: 'string' },\n 'body-file': { type: 'string' },\n branch: { type: 'string' },\n },\n allowPositionals: false,\n });\n flags = pickCommon(values);\n if (flags.help) {\n io.out(PR_CREATE_USAGE);\n return 0;\n }\n if (values.title === undefined || values.title === '') {\n throw new Error('--title is required');\n }\n if ((values.range === undefined) === (values['patch-file'] === undefined)) {\n throw new Error('exactly one of --range or --patch-file is required');\n }\n if (values.body !== undefined && values['body-file'] !== undefined) {\n throw new Error('--body and --body-file are mutually exclusive');\n }\n title = values.title;\n range = values.range;\n patchFile = values['patch-file'];\n branch = values.branch;\n bodyFlag = values.body;\n bodyFile = values['body-file'];\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(PR_CREATE_USAGE);\n return 2;\n }\n\n // PR description (optional): --body → --body-file. Carried in the event's\n // `description` tag — NEVER prepended to the content, which must stay pure\n // `git format-patch` output for `git am` (leading prose hard-fails git's\n // patch-format detection).\n let body: string | undefined;\n if (bodyFlag !== undefined) {\n body = bodyFlag;\n } else if (bodyFile !== undefined) {\n try {\n body = await readFile(bodyFile, 'utf-8');\n } catch (err) {\n io.err(\n `cannot read --body-file ${bodyFile}: ${err instanceof Error ? err.message : String(err)}`\n );\n return 2;\n }\n }\n if (body !== undefined && body.trim() === '') {\n io.err('the PR body is empty — drop --body/--body-file or pass text');\n return 2;\n }\n\n // Captured by buildEvent for the daemon path: what is SHOWN locally (the\n // built kind:1617 content) is exactly what the delegated /git/patch\n // publishes — the daemon never re-derives the series.\n let builtPatchText: string | undefined;\n let builtCommits: { sha: string; parentSha: string }[] = [];\n\n return runEvent({\n command: 'pr',\n flags,\n deps,\n actionLabel: `patch ${JSON.stringify(title)}`,\n buildEvent: async (addr) => {\n let patchText: string;\n let commits: { sha: string; parentSha: string }[];\n if (range !== undefined) {\n // REAL format-patch output from the local repository (v1 publishes\n // the whole series as ONE event; see PR_USAGE).\n const reader = new GitRepoReader(await resolveRepoRoot(deps.cwd));\n patchText = await reader.formatPatch(range);\n if (patchText === '') {\n throw new Error(\n `range ${JSON.stringify(range)} selects no commits — nothing to publish`\n );\n }\n // commit/parent-commit tags for exactly the commits the series\n // carries (parsed from the patch itself, so the tags can never drift\n // from the content). Root commits have no parent and contribute no\n // tag pair.\n const shas = extractPatchShas(patchText);\n const parents = await reader.commitParents(shas);\n commits = shas.flatMap((sha) => {\n const parentSha = parents.get(sha)?.[0];\n return parentSha ? [{ sha, parentSha }] : [];\n });\n } else {\n patchText = await readFile(patchFile as string, 'utf-8');\n if (patchText.trim() === '') {\n throw new Error(`--patch-file ${patchFile} is empty — nothing to publish`);\n }\n commits = [];\n }\n builtPatchText = patchText;\n builtCommits = commits;\n return buildPatch(\n addr.ownerPubkey,\n addr.repoId,\n title,\n commits,\n branch,\n patchText,\n body\n );\n },\n sendDaemon: (client, addr) => {\n if (builtPatchText === undefined) {\n throw new Error('internal: patch text not built before delegation');\n }\n return client.gitPatch({\n repoAddr: addr,\n title,\n patchText: builtPatchText,\n ...(body !== undefined ? { description: body } : {}),\n ...(builtCommits.length > 0 ? { commits: builtCommits } : {}),\n ...(branch !== undefined ? { branch } : {}),\n });\n },\n });\n}\n\n// ---------------------------------------------------------------------------\n// rig pr status (top-level `rig status` before #250 — now git's)\n// ---------------------------------------------------------------------------\n\n/** NIP-34 status kinds by wire value (mirrors the daemon's mapping). */\nconst STATUS_KIND_BY_VALUE: Record<GitStatusValue, StatusKind> = {\n open: STATUS_OPEN_KIND,\n applied: STATUS_APPLIED_KIND,\n closed: STATUS_CLOSED_KIND,\n draft: STATUS_DRAFT_KIND,\n};\n\nfunction isStatusValue(value: string): value is GitStatusValue {\n return Object.hasOwn(STATUS_KIND_BY_VALUE, value);\n}\n\n/** `rig pr status` — kind:1630-1633 status publish. */\nasync function runPrStatus(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let flags: CommonFlags;\n let targetEventId: string;\n let status: GitStatusValue;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: COMMON_OPTIONS,\n allowPositionals: true,\n });\n flags = pickCommon(values);\n if (flags.help) {\n io.out(PR_STATUS_USAGE);\n return 0;\n }\n if (positionals.length !== 2) {\n throw new Error(\n 'expected exactly two arguments: <target-event-id> <open|applied|closed|draft>'\n );\n }\n targetEventId = positionals[0] as string;\n assertHex64(targetEventId, '<target-event-id>');\n const rawStatus = positionals[1] as string;\n if (!isStatusValue(rawStatus)) {\n throw new Error(\n `status must be one of open | applied | closed | draft (got ${JSON.stringify(rawStatus)})`\n );\n }\n status = rawStatus;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(PR_STATUS_USAGE);\n return 2;\n }\n\n return runEvent({\n command: 'pr status',\n flags,\n deps,\n actionLabel: `status ${status} on ${targetEventId.slice(0, 8)}…`,\n buildEvent: async (addr) =>\n // buildStatus (rig#160) now emits the root-marked `e` tag and the repo\n // `a` tag itself, so readers can scope a status stream to the\n // repository without resolving the target first (mirrors the\n // daemon's gitStatus).\n buildStatus(\n addr.ownerPubkey,\n addr.repoId,\n targetEventId,\n STATUS_KIND_BY_VALUE[status]\n ),\n // Authority warning (#287): a status event only moves an issue/PR's\n // resolved state for repo-authority-honoring clients if its author is the\n // owner or a declared maintainer. Warn clearly when the active identity is\n // neither — the publish still happens (permissionless relay; the caller\n // may be acting on their own repo/fork), but the futility is made obvious.\n preConfirm: (args) => warnIfNotMaintainer(deps, args),\n sendDaemon: (client, addr) =>\n client.gitStatus({ repoAddr: addr, targetEventId, status }),\n });\n}\n\n/**\n * Read the target repo's kind:30617 and warn on stderr when the active\n * identity is NOT an authorized status author (owner ∪ declared maintainers,\n * #287). Never throws / never blocks: a relay read failure downgrades to a\n * \"could not verify\" note and the publish proceeds under the normal gate.\n */\nasync function warnIfNotMaintainer(\n deps: EventCommandDeps,\n args: {\n identity: IdentityReport;\n addr: GitRepoAddr;\n relayUrl: string | undefined;\n }\n): Promise<void> {\n const { io } = deps;\n const { identity, addr, relayUrl } = args;\n // The owner is always an implicit maintainer — no need to read the relay.\n if (identity.pubkey.toLowerCase() === addr.ownerPubkey.toLowerCase()) return;\n if (relayUrl === undefined) return;\n try {\n const remote = await fetchRemoteState({\n relayUrls: [relayUrl],\n ownerPubkey: addr.ownerPubkey,\n repoId: addr.repoId,\n ...(deps.webSocketFactory\n ? { webSocketFactory: deps.webSocketFactory }\n : {}),\n });\n const authorized = authorizedStatusAuthors(\n addr.ownerPubkey,\n remote.announceEvent?.tags ?? []\n );\n if (authorized.has(identity.pubkey.toLowerCase())) return;\n io.err(\n `warning: you (${identity.pubkey.slice(0, 8)}…) are not a maintainer of ` +\n `30617:${addr.ownerPubkey.slice(0, 8)}…:${addr.repoId} — clients honoring ` +\n 'repo authority (rig, rig-web) will IGNORE this status when resolving the ' +\n \"issue/PR's state, UNLESS you are also the target event's own author \" +\n '(rig#160: an issue/PR author may move their own item’s status even ' +\n 'without maintainer standing — this check cannot tell from here, since it ' +\n \"does not know the target's author without a second relay read). \" +\n 'Publishing anyway (the relay is permissionless); ask the owner to ' +\n '`rig maintainers add` you if this should stick for OTHER items too.'\n );\n } catch {\n io.err(\n 'warning: could not read the repo announcement to verify your maintainer ' +\n 'status — if you are not the owner, a declared maintainer, or the target ' +\n \"event's own author, authority-honoring clients will ignore this status.\"\n );\n }\n}\n","/**\n * The FREE tracker views (#278): `rig issue list|show` and `rig pr list|show`.\n *\n * Pure relay reads over NIP-01 (../remote-state.ts `queryRelay` — the same\n * decoder that tolerates the devnet relay's non-canonical EVENT payload\n * encodings): kind:1621 issues / kind:1617 patches scoped to the repo by the\n * `#a` tag (`30617:<owner>:<repoId>`), kind:1630-1633 status events to derive\n * each item's state (LATEST-WINS: highest created_at, ties broken by lowest\n * id), and comments under `show` — NIP-22 kind:1111 (matched on the UPPERCASE\n * `E` root tag) merged with legacy kind:1622 by `created_at` (#159). No\n * payments, no channel, no identity — reads are free on TOON.\n *\n * State derivation mirrors rig-web's proven `resolvePRStatus`, upgraded to\n * latest-wins for issues too (a re-opened issue is open again).\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n ISSUE_KIND,\n PATCH_KIND,\n REPOSITORY_ANNOUNCEMENT_KIND,\n STATUS_APPLIED_KIND,\n STATUS_CLOSED_KIND,\n STATUS_DRAFT_KIND,\n STATUS_OPEN_KIND,\n} from '@toon-protocol/core/nip34';\nimport {\n COMMENT_KIND,\n LEGACY_COMMENT_KIND,\n authorizedStatusAuthors,\n commentBelongsToThread,\n firstTagValue,\n} from '../nip34-events.js';\nimport { ownerToHex } from '../npub.js';\nimport {\n queryRelay,\n type NostrEvent,\n type NostrFilter,\n type WebSocketFactory,\n type WebSocketLike,\n} from '../remote-state.js';\nimport {\n emitCliError,\n UnconfiguredRepoAddressError,\n InvalidRelayUrlError,\n} from './errors.js';\nimport { readToonConfig, resolveRepoRoot } from './git-config.js';\nimport type { ReadCommandDeps } from './read-seams.js';\nimport { resolveRelays } from './remote.js';\n\n// ---------------------------------------------------------------------------\n// Usage\n// ---------------------------------------------------------------------------\n\nconst READ_COMMON_FLAGS = ` --repo-id <id> repository id / NIP-34 d-tag (default: git config)\n --owner <pubkey> repository owner (npub or 64-char hex; default: git config)\n --remote <name> read via this configured git remote (default: origin)\n --relay <url> ad-hoc relay override; repeatable — reads are merged\n --json machine-readable envelope\n -h, --help show this help`;\n\nexport const ISSUE_LIST_USAGE = `Usage: rig issue list [--state open|closed|all] [options]\n\nList the repo's issues (kind:1621) with their derived state — FREE (relay\nreads only). State comes from kind:1630-1633 status events: the latest status\nwins; an issue with no status events is open.\n\nOptions:\n --state <state> open | closed | all (default: all)\n${READ_COMMON_FLAGS}`;\n\nexport const ISSUE_SHOW_USAGE = `Usage: rig issue show <event-id> [options]\n\nShow one issue (kind:1621): metadata, derived state, body, and its comments\n— NIP-22 kind:1111 merged with legacy kind:1622 in time order — FREE (relay\nreads only). <event-id> is the 64-char hex id \\`rig issue create\\` printed\n(also visible in \\`rig issue list\\`).\n\nOptions:\n${READ_COMMON_FLAGS}`;\n\nexport const PR_LIST_USAGE = `Usage: rig pr list [--state open|applied|closed|draft|all] [options]\n\nList the repo's patches/PRs (kind:1617) with their derived state — FREE\n(relay reads only). State comes from kind:1630-1633 status events: the\nlatest status wins; a patch with no status events is open.\n\nOptions:\n --state <state> open | applied | closed | draft | all (default: all)\n${READ_COMMON_FLAGS}`;\n\nexport const PR_SHOW_USAGE = `Usage: rig pr show <event-id> [options]\n\nShow one patch/PR (kind:1617): metadata, derived state, the FULL patch text\n(real \\`git format-patch\\` output — pipe it to \\`git am\\` to apply), and its\ncomments — NIP-22 kind:1111 merged with legacy kind:1622 in time order —\nFREE (relay reads only).\n\nOptions:\n${READ_COMMON_FLAGS}`;\n\n// ---------------------------------------------------------------------------\n// Status derivation (latest-wins)\n// ---------------------------------------------------------------------------\n\nexport type TrackerStatus = 'open' | 'applied' | 'closed' | 'draft';\n\nconst STATUS_BY_KIND: Record<number, TrackerStatus> = {\n [STATUS_OPEN_KIND]: 'open',\n [STATUS_APPLIED_KIND]: 'applied',\n [STATUS_CLOSED_KIND]: 'closed',\n [STATUS_DRAFT_KIND]: 'draft',\n};\n\nconst STATUS_KINDS = [\n STATUS_OPEN_KIND,\n STATUS_APPLIED_KIND,\n STATUS_CLOSED_KIND,\n STATUS_DRAFT_KIND,\n];\n\n/** Local alias for the shared, case-sensitive tag reader (../nip34-events.ts). */\nconst tagValue = firstTagValue;\n\nfunction tagValues(tags: string[][], name: string): string[] {\n return tags.filter((t) => t[0] === name && t[1]).map((t) => t[1] as string);\n}\n\n/**\n * Derive the state of an issue/patch from its status events: consider only\n * kind:1630-1633 events whose `e` tag references the target AND whose author\n * is AUTHORIZED — the repo owner ∪ declared maintainers ∪ the target's own\n * author (#287, rig#160). The `e` tag match is on `tags[1]` only, so both the\n * NIP-10 marker form (`[\"e\", <id>, \"\", \"root\"]`) and the legacy bare form\n * (`[\"e\", <id>]`) are honored identically. Among the authorized events the\n * LATEST wins (highest created_at, ties broken by lowest event id — the same\n * replaceable convention remote-state uses), regardless of which form each\n * used. Unauthorized status events (any funded stranger) are IGNORED for\n * state; they never move it. No authorized status events ⇒ open.\n *\n * `authorized` is the caller's authority set for THIS target: the repo-wide\n * {@link authorizedStatusAuthors} result (owner ∪ maintainers) unioned with\n * the target event's own author pubkey — callers do that union per item,\n * since the target author varies per target while the repo-wide set does\n * not (see `fetchItems`/`fetchItem`). When it is empty NOTHING is authorized\n * and the state stays open — a safe, non-spoofable default.\n */\nexport function deriveStatus(\n targetEventId: string,\n statusEvents: Iterable<NostrEvent>,\n authorized: ReadonlySet<string>\n): TrackerStatus {\n let winner: NostrEvent | null = null;\n for (const event of statusEvents) {\n if (STATUS_BY_KIND[event.kind] === undefined) continue;\n if (!authorized.has(event.pubkey.toLowerCase())) continue;\n if (!event.tags.some((t) => t[0] === 'e' && t[1] === targetEventId))\n continue;\n if (\n winner === null ||\n event.created_at > winner.created_at ||\n (event.created_at === winner.created_at && event.id < winner.id)\n ) {\n winner = event;\n }\n }\n return winner === null\n ? 'open'\n : (STATUS_BY_KIND[winner.kind] as TrackerStatus);\n}\n\n/**\n * Union a target's own author into the repo-wide authorized set (rig#160):\n * the target's own author is ALSO authorized to move its own status, on top\n * of the repo-wide owner ∪ maintainers set (see {@link deriveStatus}'s doc\n * comment). Returns a NEW Set; does not mutate `authorized`.\n */\nexport function withTargetAuthor(\n authorized: ReadonlySet<string>,\n targetAuthorPubkey: string\n): Set<string> {\n return new Set([...authorized, targetAuthorPubkey.toLowerCase()]);\n}\n\n// ---------------------------------------------------------------------------\n// Relay querying (multi-relay merge; tolerant decode via queryRelay)\n// ---------------------------------------------------------------------------\n\nconst RELAY_TIMEOUT_MS = 10000;\nconst HEX64_RE = /^[0-9a-f]{64}$/;\nconst WS_URL_RE = /^wss?:\\/\\//i;\n\nfunction defaultWebSocketFactory(url: string): WebSocketLike {\n const ctor = (\n globalThis as { WebSocket?: new (url: string) => WebSocketLike }\n ).WebSocket;\n if (!ctor) {\n throw new Error(\n 'No global WebSocket constructor (Node >= 22 required) — pass webSocketFactory'\n );\n }\n return new ctor(url);\n}\n\n/**\n * Query every relay with every filter and merge events by id. Resolves as\n * long as at least one relay answered; throws when all fail.\n */\nasync function queryAll(\n relays: string[],\n filters: NostrFilter[],\n webSocketFactory: WebSocketFactory\n): Promise<Map<string, NostrEvent>> {\n const jobs = relays.flatMap((relay) =>\n filters.map((filter) =>\n queryRelay(relay, filter, RELAY_TIMEOUT_MS, webSocketFactory)\n )\n );\n const results = await Promise.allSettled(jobs);\n const byId = new Map<string, NostrEvent>();\n let failures = 0;\n let firstError: unknown;\n for (const result of results) {\n if (result.status === 'rejected') {\n failures += 1;\n firstError ??= result.reason;\n continue;\n }\n for (const event of result.value) {\n if (typeof event.id === 'string' && !byId.has(event.id)) {\n byId.set(event.id, event);\n }\n }\n }\n if (failures === results.length && results.length > 0) {\n throw firstError instanceof Error\n ? firstError\n : new Error(String(firstError));\n }\n return byId;\n}\n\n// ---------------------------------------------------------------------------\n// Shared context resolution (repo address + relays; NO identity, NO payment)\n// ---------------------------------------------------------------------------\n\ninterface TrackerFlags {\n json: boolean;\n help: boolean;\n state?: string;\n relay: string[];\n remote?: string;\n repoId?: string;\n owner?: string;\n}\n\nconst TRACKER_OPTIONS = {\n json: { type: 'boolean', default: false },\n state: { type: 'string' },\n relay: { type: 'string', multiple: true },\n remote: { type: 'string' },\n 'repo-id': { type: 'string' },\n owner: { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n} as const;\n\nfunction pickTrackerFlags(values: Record<string, unknown>): TrackerFlags {\n const flags: TrackerFlags = {\n json: values['json'] === true,\n help: values['help'] === true,\n relay: Array.isArray(values['relay']) ? (values['relay'] as string[]) : [],\n };\n if (typeof values['state'] === 'string') flags.state = values['state'];\n if (typeof values['remote'] === 'string') flags.remote = values['remote'];\n if (typeof values['repo-id'] === 'string') flags.repoId = values['repo-id'];\n if (typeof values['owner'] === 'string')\n flags.owner = ownerToHex(values['owner']);\n return flags;\n}\n\ninterface TrackerContext {\n relays: string[];\n /** Set when the repo address resolved (list always has it; show may not). */\n repoAddr: { ownerPubkey: string; repoId: string } | null;\n webSocketFactory: WebSocketFactory;\n}\n\n/**\n * Resolve relays (+ repo address when `needRepoAddr`) from flags and the git\n * config, mirroring the paid commands' #249 chain — but reads may target\n * MULTIPLE relays (results are merged), and only ws/wss URLs are usable.\n */\nasync function resolveTrackerContext(\n flags: TrackerFlags,\n deps: ReadCommandDeps,\n needRepoAddr: boolean\n): Promise<TrackerContext> {\n let repoRoot: string | undefined;\n let toonConfig: { repoId?: string; owner?: string; relays: string[] } = {\n relays: [],\n };\n try {\n repoRoot = await resolveRepoRoot(deps.cwd);\n toonConfig = await readToonConfig(repoRoot);\n } catch {\n // Not inside a git repo — flags must carry everything.\n }\n\n // Resolve the repo address from flags/git config. `list` REQUIRES it (throws\n // when unresolved). `show` does not, but resolves it OPPORTUNISTICALLY when\n // available so it can fall back to it for the authority set (#287) when the\n // shown item lacks a parseable `a` tag — otherwise `show` would report a\n // falsely-`open` status that `list` (which always has the address) resolves\n // correctly.\n let repoAddr: TrackerContext['repoAddr'] = null;\n const repoId = flags.repoId ?? toonConfig.repoId;\n const owner = flags.owner ?? toonConfig.owner;\n if (repoId && owner) {\n repoAddr = { ownerPubkey: owner, repoId };\n } else if (needRepoAddr) {\n if (!repoId) throw new UnconfiguredRepoAddressError('repository id');\n throw new UnconfiguredRepoAddressError('repository owner');\n }\n\n const resolved = await resolveRelays({\n relayFlags: flags.relay,\n remoteName: flags.remote,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n const wsRelays = resolved.relays.filter((url) => WS_URL_RE.test(url));\n if (wsRelays.length === 0) {\n throw new InvalidRelayUrlError(\n resolved.relays[0] ?? '',\n 'reads need a ws:// or wss:// relay'\n );\n }\n\n return {\n relays: wsRelays,\n repoAddr,\n webSocketFactory: deps.webSocketFactory ?? defaultWebSocketFactory,\n };\n}\n\nfunction repoATag(addr: { ownerPubkey: string; repoId: string }): string {\n return `${REPOSITORY_ANNOUNCEMENT_KIND}:${addr.ownerPubkey}:${addr.repoId}`;\n}\n\n/**\n * Resolve the AUTHORIZED status authors (#287) for a repo: the owner ∪ the\n * maintainers declared on the repo's kind:30617 announcement. Reads the 30617\n * from the relay(s) — untrusted relays may over-return, so only the owner's\n * own announcement for this `d`-tag is honored. When no announcement is found\n * the set falls back to OWNER-ONLY (the owner is always an implicit\n * maintainer); this is the safe default — an unresolved 30617 can never widen\n * authority to a stranger.\n */\nasync function fetchAuthorizedAuthors(\n ctx: TrackerContext,\n ownerPubkey: string,\n repoId: string\n): Promise<Set<string>> {\n let announceTags: string[][] = [];\n try {\n const events = await queryAll(\n ctx.relays,\n [\n {\n kinds: [REPOSITORY_ANNOUNCEMENT_KIND],\n authors: [ownerPubkey],\n '#d': [repoId],\n },\n ],\n ctx.webSocketFactory\n );\n // Latest replaceable 30617 by (created_at, id) from the trusted owner.\n let latest: NostrEvent | null = null;\n for (const event of events.values()) {\n if (event.kind !== REPOSITORY_ANNOUNCEMENT_KIND) continue;\n if (event.pubkey !== ownerPubkey) continue;\n if (!event.tags.some((t) => t[0] === 'd' && t[1] === repoId)) continue;\n if (\n latest === null ||\n event.created_at > latest.created_at ||\n (event.created_at === latest.created_at && event.id < latest.id)\n ) {\n latest = event;\n }\n }\n if (latest) announceTags = latest.tags;\n } catch {\n // Relay read failed — fall back to owner-only authority.\n }\n return authorizedStatusAuthors(ownerPubkey, announceTags);\n}\n\n// ---------------------------------------------------------------------------\n// Shared list/show engines (issues and PRs differ only in kind + fields)\n// ---------------------------------------------------------------------------\n\ninterface TrackerItem {\n eventId: string;\n kind: number;\n title: string;\n status: TrackerStatus;\n authorPubkey: string;\n createdAt: number;\n labels: string[];\n content: string;\n /** kind:1617 only: `commit` tag SHAs. */\n commitShas?: string[];\n /**\n * kind:1617 only: branch name, read from `branch-name` first (#161 — the\n * tag new patches write), falling back to the legacy `branch` tag. Never\n * read from `t`: a legacy patch that only carries the branch in `t` is not\n * guessed at and renders as it always has (unlabeled branch, `t` as a\n * label).\n */\n branch?: string;\n /**\n * kind:1617 only: the PR body from the `description` tag (#280). Separate\n * from `content`, which is pure `git format-patch` output for `git am`.\n */\n description?: string;\n}\n\nfunction parseTrackerItem(\n event: NostrEvent,\n status: TrackerStatus\n): TrackerItem {\n const item: TrackerItem = {\n eventId: event.id,\n kind: event.kind,\n title:\n tagValue(event.tags, 'subject') ??\n (event.content.split('\\n')[0] ?? '').slice(0, 120),\n status,\n authorPubkey: event.pubkey,\n createdAt: event.created_at,\n labels: tagValues(event.tags, 't'),\n content: event.content,\n };\n if (event.kind === PATCH_KIND) {\n item.commitShas = tagValues(event.tags, 'commit');\n const branch =\n tagValue(event.tags, 'branch-name') ?? tagValue(event.tags, 'branch');\n if (branch !== undefined) item.branch = branch;\n const description = tagValue(event.tags, 'description');\n if (description !== undefined) item.description = description;\n }\n return item;\n}\n\nfunction isoDate(createdAt: number): string {\n return new Date(createdAt * 1000).toISOString().slice(0, 10);\n}\n\n/** Fetch items of `kind` for the repo + their statuses; derive state. */\nasync function fetchItems(\n ctx: TrackerContext,\n kind: number\n): Promise<TrackerItem[]> {\n const addr = ctx.repoAddr as { ownerPubkey: string; repoId: string };\n const aTag = repoATag(addr);\n // Authority set (#287): owner ∪ declared maintainers from the 30617. Fetched\n // in parallel with the items — status resolution honors ONLY these authors.\n const authorizedPromise = fetchAuthorizedAuthors(\n ctx,\n addr.ownerPubkey,\n addr.repoId\n );\n const [itemEvents, aStatusEvents] = await Promise.all([\n queryAll(\n ctx.relays,\n [{ kinds: [kind], '#a': [aTag] }],\n ctx.webSocketFactory\n ),\n queryAll(\n ctx.relays,\n [{ kinds: STATUS_KINDS, '#a': [aTag] }],\n ctx.webSocketFactory\n ),\n ]);\n\n // Defense against over-returning relays: keep only the right kind + repo.\n const items = [...itemEvents.values()].filter(\n (e) => e.kind === kind && e.tags.some((t) => t[0] === 'a' && t[1] === aTag)\n );\n\n // Statuses may lack the repo `a` tag (other clients) — also query by `#e`.\n const statuses = new Map(aStatusEvents);\n if (items.length > 0) {\n const byE = await queryAll(\n ctx.relays,\n [{ kinds: STATUS_KINDS, '#e': items.map((i) => i.id) }],\n ctx.webSocketFactory\n );\n for (const [id, event] of byE)\n if (!statuses.has(id)) statuses.set(id, event);\n }\n\n const authorized = await authorizedPromise;\n return items\n .map((event) =>\n parseTrackerItem(\n event,\n deriveStatus(\n event.id,\n statuses.values(),\n withTargetAuthor(authorized, event.pubkey)\n )\n )\n )\n .sort((a, b) => b.createdAt - a.createdAt);\n}\n\n/** One comment in a merged thread (NIP-22 kind:1111 ∪ legacy kind:1622). */\ninterface ShownComment {\n eventId: string;\n authorPubkey: string;\n createdAt: number;\n content: string;\n /** Wire kind this comment arrived as: 1111 (NIP-22) or 1622 (legacy). */\n kind: number;\n /**\n * The event this comment replies to — the lowercase `e` tag. Equals the\n * thread root for a top-level comment; another comment's id for a nested\n * reply. `null` when the event carries no lowercase `e` (legacy shapes).\n */\n replyToEventId: string | null;\n}\n\ninterface ShownItem {\n item: TrackerItem;\n comments: ShownComment[];\n repoATag: string | null;\n}\n\n/** Fetch one item by event id + its statuses and comments. */\nasync function fetchItem(\n ctx: TrackerContext,\n eventId: string,\n expectedKind: number\n): Promise<ShownItem> {\n const found = await queryAll(\n ctx.relays,\n [{ ids: [eventId] }],\n ctx.webSocketFactory\n );\n const event = found.get(eventId);\n if (!event) {\n throw new Error(`event ${eventId} not found on ${ctx.relays.join(', ')}`);\n }\n if (event.kind !== expectedKind) {\n const hint =\n event.kind === PATCH_KIND\n ? ' (it is a kind:1617 patch — use `rig pr show`)'\n : event.kind === ISSUE_KIND\n ? ' (it is a kind:1621 issue — use `rig issue show`)'\n : '';\n throw new Error(\n `event ${eventId} has kind ${event.kind}, expected ${expectedKind}${hint}`\n );\n }\n\n const [statusEvents, commentEvents] = await Promise.all([\n queryAll(\n ctx.relays,\n [{ kinds: STATUS_KINDS, '#e': [eventId] }],\n ctx.webSocketFactory\n ),\n // One thread, two wire shapes (#159): NIP-22 kind:1111 comments hang off\n // the root's UPPERCASE `E` tag (a nested reply's lowercase `e` names its\n // parent comment, so `#e` would miss it); legacy kind:1622 comments only\n // ever carry the lowercase `e`. Both are merged below by `created_at`.\n queryAll(\n ctx.relays,\n [\n { kinds: [COMMENT_KIND], '#E': [eventId] },\n { kinds: [LEGACY_COMMENT_KIND], '#e': [eventId] },\n ],\n ctx.webSocketFactory\n ),\n ]);\n\n const comments = [...commentEvents.values()]\n .filter((e) => commentBelongsToThread(e, eventId))\n .sort((a, b) => a.created_at - b.created_at)\n .map((e) => ({\n eventId: e.id,\n kind: e.kind,\n replyToEventId: tagValue(e.tags, 'e') ?? null,\n authorPubkey: e.pubkey,\n createdAt: e.created_at,\n content: e.content,\n }));\n\n // Authority set (#287): prefer the shown item's own `a` tag\n // (30617:<owner>:<id>) and read that repo's 30617 for the maintainers. When\n // the item lacks a parseable `a` tag, fall back to the configured repo\n // address (--repo-id/--owner or git config) so `show` matches `list` instead\n // of reporting a falsely-`open` status. Only when NEITHER is available is the\n // set empty ⇒ status stays open (safe: no stranger can move it either way).\n const repoATag = tagValue(event.tags, 'a') ?? null;\n const parsedAddr = parseRepoATag(repoATag) ?? ctx.repoAddr;\n const authorized = parsedAddr\n ? await fetchAuthorizedAuthors(ctx, parsedAddr.ownerPubkey, parsedAddr.repoId)\n : new Set<string>();\n\n return {\n item: parseTrackerItem(\n event,\n deriveStatus(\n eventId,\n statusEvents.values(),\n withTargetAuthor(authorized, event.pubkey)\n )\n ),\n comments,\n repoATag,\n };\n}\n\n/** Parse a NIP-34 repo `a` tag `30617:<owner-hex>:<repoId>` into its parts. */\nfunction parseRepoATag(\n aTag: string | null\n): { ownerPubkey: string; repoId: string } | null {\n if (!aTag) return null;\n const [kind, ownerPubkey, ...repoIdParts] = aTag.split(':');\n const repoId = repoIdParts.join(':');\n if (kind !== String(REPOSITORY_ANNOUNCEMENT_KIND) || !ownerPubkey || !repoId) {\n return null;\n }\n return { ownerPubkey, repoId };\n}\n\n// ---------------------------------------------------------------------------\n// list command (shared by issue/pr)\n// ---------------------------------------------------------------------------\n\ninterface ListSpec {\n command: 'issue list' | 'pr list';\n kind: number;\n usage: string;\n states: readonly TrackerStatus[];\n jsonKey: 'issues' | 'prs';\n}\n\nasync function runList(\n args: string[],\n deps: ReadCommandDeps,\n spec: ListSpec\n): Promise<number> {\n const { io } = deps;\n let flags: TrackerFlags;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: TRACKER_OPTIONS,\n allowPositionals: true,\n });\n if (positionals.length > 0) {\n throw new Error(`rig ${spec.command} takes no positional arguments`);\n }\n flags = pickTrackerFlags(values);\n if (\n flags.state !== undefined &&\n flags.state !== 'all' &&\n !spec.states.includes(flags.state as TrackerStatus)\n ) {\n throw new Error(\n `--state must be one of ${[...spec.states, 'all'].join(' | ')} (got ${JSON.stringify(flags.state)})`\n );\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(spec.usage);\n return 2;\n }\n if (flags.help) {\n io.out(spec.usage);\n return 0;\n }\n\n try {\n const ctx = await resolveTrackerContext(flags, deps, true);\n const all = await fetchItems(ctx, spec.kind);\n const state = flags.state ?? 'all';\n const items = state === 'all' ? all : all.filter((i) => i.status === state);\n\n if (flags.json) {\n io.emitJson({\n command: spec.command,\n repoAddr: ctx.repoAddr,\n relays: ctx.relays,\n state,\n count: items.length,\n [spec.jsonKey]: items,\n });\n return 0;\n }\n\n if (items.length === 0) {\n io.out(\n `no ${state === 'all' ? '' : `${state} `}${spec.jsonKey} found for ` +\n `${repoATag(ctx.repoAddr as { ownerPubkey: string; repoId: string })}`\n );\n return 0;\n }\n for (const item of items) {\n const labels =\n item.labels.length > 0 ? ` [${item.labels.join(', ')}]` : '';\n // #161: kind:1617 items only — issues never set `.branch`.\n const branch = item.branch !== undefined ? ` → ${item.branch}` : '';\n io.out(\n `${item.status.padEnd(7)} ${item.eventId.slice(0, 8)} ${item.title}` +\n ` (${item.authorPubkey.slice(0, 8)}, ${isoDate(item.createdAt)})${labels}${branch}`\n );\n }\n io.out(\n `${items.length} ${spec.jsonKey}${state === 'all' ? '' : ` (${state})`}`\n );\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, spec.command, err);\n }\n}\n\n// ---------------------------------------------------------------------------\n// show command (shared by issue/pr)\n// ---------------------------------------------------------------------------\n\ninterface ShowSpec {\n command: 'issue show' | 'pr show';\n kind: number;\n usage: string;\n jsonKey: 'issue' | 'pr';\n /** PRs print their full patch text; issues print the body. */\n bodyLabel: string;\n}\n\nasync function runShow(\n args: string[],\n deps: ReadCommandDeps,\n spec: ShowSpec\n): Promise<number> {\n const { io } = deps;\n let flags: TrackerFlags;\n let eventId: string;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: TRACKER_OPTIONS,\n allowPositionals: true,\n });\n flags = pickTrackerFlags(values);\n if (flags.help) {\n io.out(spec.usage);\n return 0;\n }\n if (positionals.length !== 1) {\n throw new Error('expected exactly one <event-id>');\n }\n eventId = positionals[0] as string;\n if (!HEX64_RE.test(eventId)) {\n throw new Error(\n `<event-id> must be a 64-char lowercase hex id (got ${JSON.stringify(eventId)})`\n );\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(spec.usage);\n return 2;\n }\n\n try {\n const ctx = await resolveTrackerContext(flags, deps, false);\n const shown = await fetchItem(ctx, eventId, spec.kind);\n\n if (flags.json) {\n io.emitJson({\n command: spec.command,\n relays: ctx.relays,\n repoATag: shown.repoATag,\n [spec.jsonKey]: shown.item,\n comments: shown.comments,\n });\n return 0;\n }\n\n const { item } = shown;\n io.out(`${spec.jsonKey} ${item.eventId}`);\n io.out(`Title: ${item.title}`);\n io.out(`Status: ${item.status}`);\n io.out(`Author: ${item.authorPubkey}`);\n io.out(`Date: ${isoDate(item.createdAt)}`);\n if (item.labels.length > 0) io.out(`Labels: ${item.labels.join(', ')}`);\n if (item.branch !== undefined) io.out(`Branch: ${item.branch}`);\n if (item.commitShas && item.commitShas.length > 0) {\n io.out(`Commits: ${item.commitShas.join(', ')}`);\n }\n if (shown.repoATag !== null) io.out(`Repo: ${shown.repoATag}`);\n if (item.description !== undefined) {\n // The `description` tag (`rig pr create --body`): shown as its own\n // section so the patch text below stays pipeable into `git am`.\n io.out('');\n io.out('Body:');\n for (const line of item.description.split('\\n')) io.out(line);\n }\n io.out('');\n io.out(`${spec.bodyLabel}:`);\n for (const line of item.content.split('\\n')) io.out(line);\n io.out('');\n io.out(`Comments (${shown.comments.length}):`);\n for (const comment of shown.comments) {\n // A nested reply's lowercase `e` names another comment, not the thread\n // root — surface that so a NIP-22 thread reads as a conversation (#159).\n const replyTo =\n comment.replyToEventId !== null &&\n comment.replyToEventId !== item.eventId\n ? ` in reply to ${comment.replyToEventId.slice(0, 8)}`\n : '';\n io.out(\n `--- ${comment.eventId.slice(0, 8)} by ${comment.authorPubkey.slice(0, 8)} ` +\n `on ${isoDate(comment.createdAt)}${replyTo}`\n );\n for (const line of comment.content.split('\\n')) io.out(line);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, spec.command, err);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public entry points\n// ---------------------------------------------------------------------------\n\nconst ISSUE_STATES = ['open', 'closed', 'applied', 'draft'] as const;\nconst PR_STATES = ['open', 'applied', 'closed', 'draft'] as const;\n\n/** `rig issue list` */\nexport function runIssueList(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n return runList(args, deps, {\n command: 'issue list',\n kind: ISSUE_KIND,\n usage: ISSUE_LIST_USAGE,\n states: ISSUE_STATES,\n jsonKey: 'issues',\n });\n}\n\n/** `rig issue show <event-id>` */\nexport function runIssueShow(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n return runShow(args, deps, {\n command: 'issue show',\n kind: ISSUE_KIND,\n usage: ISSUE_SHOW_USAGE,\n jsonKey: 'issue',\n bodyLabel: 'Body',\n });\n}\n\n/** `rig pr list` */\nexport function runPrList(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n return runList(args, deps, {\n command: 'pr list',\n kind: PATCH_KIND,\n usage: PR_LIST_USAGE,\n states: PR_STATES,\n jsonKey: 'prs',\n });\n}\n\n/** `rig pr show <event-id>` */\nexport function runPrShow(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n return runShow(args, deps, {\n command: 'pr show',\n kind: PATCH_KIND,\n usage: PR_SHOW_USAGE,\n jsonKey: 'pr',\n bodyLabel: 'Patch',\n });\n}\n","/**\n * `rig entry` — name the TOON connector rig pays.\n *\n * One URL is the whole network configuration since 4.0: a connector describes\n * itself on `GET /ilp` (addresses, prices, chains, sealing key — connector ADR\n * 0050), so there is nothing else to point rig at. This command records that\n * URL as `connectorUrl` in the shared client config, optionally with the\n * free-read relay (`--relay`) the same node serves, and shows what is in\n * effect and where it came from. Free: only the local config file is touched.\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { parseArgs } from 'node:util';\nimport { emitCliError } from './errors.js';\nimport type { CliIo } from './output.js';\n\nexport const ENTRY_USAGE = `Usage: rig entry [<connector-url> | clear] [options]\n\nName the TOON connector rig pays. A connector describes itself on GET /ilp\n(its addresses, routes and prices, settlement chains), so its URL is the\nwhole configuration. Free: only the local config file is touched.\n\n rig entry show the effective connector + relay and their source\n rig entry <connector-url> record the node's client-edge URL (https://…);\n pass --relay <wss-url> to also record its free-read relay\n rig entry clear forget the recorded connector (and relay)\n\nExisting payment channels are per node: after switching, the next paid\ncommand opens or adopts a channel with the new node.\n\nNOTE for repos: the relay a repo publishes to is its git \\`origin\\` remote,\nwhich OVERRIDES the config relayUrl. After switching, point the repo too:\n\\`rig remote add origin <relay-url>\\` (or use a fresh repo).\n\nOptions:\n --relay <url> with <connector-url>: also record the relay URL (ws:// or wss://)\n --json machine-readable envelope\n -h, --help show this help`;\n\n/** What `rig entry` needs from the command environment. */\nexport interface EntryDeps {\n io: CliIo;\n env: NodeJS.ProcessEnv;\n}\n\n/** The slice of the shared client config `rig entry` reads/writes. */\ninterface EntryConfigFile {\n connectorUrl?: string;\n relayUrl?: string;\n /** @deprecated pre-4.0 spellings, migrated away on write. */\n proxyUrl?: string;\n btpUrl?: string;\n [key: string]: unknown;\n}\n\n/** Where an effective endpoint value came from. */\nexport type EndpointSource =\n 'env' | 'config' | 'legacy-env' | 'legacy-config' | null;\n\n/** `--json` envelope. */\ninterface EntryJson {\n command: 'entry';\n connectorUrl: string | null;\n connectorSource: EndpointSource;\n relayUrl: string | null;\n relaySource: EndpointSource;\n /** What was written to config (mutations only). */\n wrote?: { connectorUrl: string | null; relayUrl: string | null };\n configPath: string;\n warnings?: string[];\n}\n\n/** Resolve the client config directory + path (mirrors `rig chain`). */\nfunction configPathFor(env: NodeJS.ProcessEnv): string {\n const dir = env['TOON_CLIENT_HOME'] ?? join(homedir(), '.toon-client');\n return join(dir, 'config.json');\n}\n\nfunction readEntryConfig(configPath: string): EntryConfigFile {\n try {\n return JSON.parse(readFileSync(configPath, 'utf8')) as EntryConfigFile;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw new Error(\n `failed to read client config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n}\n\n/** Read-merge-write: preserve every other field. */\nfunction writeEntryConfig(configPath: string, file: EntryConfigFile): void {\n mkdirSync(dirname(configPath), { recursive: true });\n writeFileSync(configPath, `${JSON.stringify(file, null, 2)}\\n`, 'utf8');\n}\n\n/** The effective connector and relay, with the precedence the paid path uses. */\nexport function effectiveEntry(\n env: NodeJS.ProcessEnv,\n file: EntryConfigFile\n): {\n connectorUrl: string | null;\n connectorSource: EndpointSource;\n relayUrl: string | null;\n relaySource: EndpointSource;\n} {\n let connectorUrl: string | null = null;\n let connectorSource: EndpointSource = null;\n if (env['TOON_CONNECTOR']) {\n connectorUrl = env['TOON_CONNECTOR'];\n connectorSource = 'env';\n } else if (env['TOON_CLIENT_PROXY_URL']) {\n connectorUrl = env['TOON_CLIENT_PROXY_URL'];\n connectorSource = 'legacy-env';\n } else if (file.connectorUrl) {\n connectorUrl = file.connectorUrl;\n connectorSource = 'config';\n } else if (file.proxyUrl) {\n connectorUrl = file.proxyUrl;\n connectorSource = 'legacy-config';\n }\n const relayUrl = env['TOON_CLIENT_RELAY_URL'] ?? file.relayUrl ?? null;\n const relaySource: EndpointSource = env['TOON_CLIENT_RELAY_URL']\n ? 'env'\n : file.relayUrl\n ? 'config'\n : null;\n return { connectorUrl, connectorSource, relayUrl, relaySource };\n}\n\nconst HTTP_URL = /^https?:\\/\\/.+/i;\nconst WS_URL = /^wss?:\\/\\/.+/i;\n\n/** Run `rig entry`; returns the process exit code. */\nexport async function runEntry(\n args: string[],\n deps: EntryDeps\n): Promise<number> {\n const { io, env } = deps;\n\n let positionals: string[];\n let relayFlag: string | undefined;\n let json = false;\n try {\n const parsed = parseArgs({\n args,\n allowPositionals: true,\n options: {\n relay: { type: 'string' },\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n });\n if (parsed.values.help) {\n io.out(ENTRY_USAGE);\n return 0;\n }\n positionals = parsed.positionals;\n relayFlag = parsed.values.relay;\n json = parsed.values.json ?? false;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(ENTRY_USAGE);\n return 2;\n }\n\n if (positionals.length > 1) {\n io.err(\n `rig entry takes at most one argument, got ${String(positionals.length)}: ${positionals.join(' ')}`\n );\n io.err(ENTRY_USAGE);\n return 2;\n }\n const target = positionals[0];\n\n // Usage-validate the target OUTSIDE the runtime-error wrapper (exit 2).\n let mutation:\n | { kind: 'clear' }\n | { kind: 'url'; connectorUrl: string; relayUrl?: string }\n | undefined;\n if (target !== undefined) {\n if (target === 'clear') {\n if (relayFlag !== undefined) {\n io.err('--relay only applies to a <connector-url> entry');\n io.err(ENTRY_USAGE);\n return 2;\n }\n mutation = { kind: 'clear' };\n } else if (HTTP_URL.test(target)) {\n if (relayFlag !== undefined && !WS_URL.test(relayFlag)) {\n io.err(`--relay must be a ws(s) URL, got ${JSON.stringify(relayFlag)}`);\n io.err(ENTRY_USAGE);\n return 2;\n }\n mutation = {\n kind: 'url',\n connectorUrl: target.replace(/\\/+$/, ''),\n ...(relayFlag !== undefined ? { relayUrl: relayFlag } : {}),\n };\n } else if (WS_URL.test(target)) {\n io.err(\n `${JSON.stringify(target)} is a WebSocket URL — the entry is the connector's http(s) URL ` +\n '(the one whose GET /ilp describes it); pass the relay with --relay'\n );\n io.err(ENTRY_USAGE);\n return 2;\n } else {\n io.err(\n `unknown entry ${JSON.stringify(target)} — expected a connector http(s):// URL or \\`clear\\``\n );\n io.err(ENTRY_USAGE);\n return 2;\n }\n }\n\n try {\n const configPath = configPathFor(env);\n const file = readEntryConfig(configPath);\n\n const label = (source: EndpointSource): string =>\n source === 'env'\n ? 'env'\n : source === 'legacy-env'\n ? 'env (TOON_CLIENT_PROXY_URL, pre-4.0 spelling — set TOON_CONNECTOR)'\n : source === 'config'\n ? `config (${configPath})`\n : source === 'legacy-config'\n ? `config proxyUrl (${configPath}, pre-4.0 spelling)`\n : 'not configured';\n\n // ── show (no argument) ─────────────────────────────────────────────────\n if (mutation === undefined) {\n const state = effectiveEntry(env, file);\n if (json) {\n io.emitJson({\n command: 'entry',\n ...state,\n configPath,\n } satisfies EntryJson);\n return 0;\n }\n io.out(\n `Connector ${state.connectorUrl ?? '(none)'} [${label(state.connectorSource)}]`\n );\n io.out(\n `Relay ${state.relayUrl ?? '(none)'} [${label(state.relaySource)}]`\n );\n if (!state.connectorUrl) {\n io.out(\n 'Set one with `rig entry <connector-url>` (or export TOON_CONNECTOR).'\n );\n }\n return 0;\n }\n\n // ── mutations ──────────────────────────────────────────────────────────\n const warnings: string[] = [];\n const next: EntryConfigFile = { ...file };\n // The pre-4.0 spellings are retired on any write: a stale `proxyUrl`\n // would otherwise keep outranking nothing, and `btpUrl` is ignored.\n if (file.proxyUrl !== undefined || file.btpUrl !== undefined) {\n delete next.proxyUrl;\n delete next.btpUrl;\n warnings.push(\n 'removed the pre-4.0 proxyUrl/btpUrl fields (the connector URL replaces both)'\n );\n }\n if (mutation.kind === 'clear') {\n delete next.connectorUrl;\n delete next.relayUrl;\n } else {\n next.connectorUrl = mutation.connectorUrl;\n if (mutation.relayUrl !== undefined) next.relayUrl = mutation.relayUrl;\n }\n if (env['TOON_CONNECTOR'] || env['TOON_CLIENT_PROXY_URL']) {\n warnings.push(\n 'TOON_CONNECTOR / TOON_CLIENT_PROXY_URL is set in this shell and outranks the config file'\n );\n }\n writeEntryConfig(configPath, next);\n const wrote = {\n connectorUrl: next.connectorUrl ?? null,\n relayUrl: next.relayUrl ?? null,\n };\n const state = effectiveEntry(env, next);\n\n if (json) {\n io.emitJson({\n command: 'entry',\n ...state,\n wrote,\n configPath,\n ...(warnings.length > 0 ? { warnings } : {}),\n } satisfies EntryJson);\n return 0;\n }\n if (mutation.kind === 'clear') {\n io.out(`Cleared the recorded connector in ${configPath}.`);\n } else {\n io.out(`Recorded connector ${mutation.connectorUrl} in ${configPath}.`);\n if (mutation.relayUrl !== undefined)\n io.out(`Recorded relay ${mutation.relayUrl}.`);\n }\n for (const w of warnings) io.out(`warning: ${w}`);\n io.out(\n `Effective connector: ${state.connectorUrl ?? '(none)'} [${label(state.connectorSource)}]`\n );\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'entry', err);\n }\n}\n","/**\n * `rig fetch` (#278) — the clone pipeline against an EXISTING repository:\n * fetch the remote refs + sha→txId map from the relay, download only the\n * objects the local repository is missing (SHA-1 verified), and update the\n * remote-tracking refs (refs/remotes/<remote>/*; tags to refs/tags/*),\n * reporting what moved like `git fetch` does. FREE — no payments anywhere.\n *\n * No merge: integrating fetched refs is `rig merge origin/main` (the git\n * passthrough), exactly like plain git. `rig fetch` shadows `git fetch` the\n * same way `rig push` shadows `git push`; plain-git fetches stay available\n * by running `git fetch` directly.\n */\n\nimport { parseArgs } from 'node:util';\nimport { readGateways } from '../gateway-preference.js';\nimport { shaResolverFor } from '../git-sha-resolver.js';\nimport {\n isSafeRefname,\n runGit,\n updateRef,\n writeGitObjects,\n} from '../materialize.js';\nimport { ownerToHex } from '../npub.js';\nimport { collectRepoObjects } from '../read-pipeline.js';\nimport { fetchRemoteState } from '../remote-state.js';\nimport { GitRepoReader } from '../repo-reader.js';\nimport {\n emitCliError,\n InvalidRelayUrlError,\n MultiUrlRemoteError,\n UnconfiguredRepoAddressError,\n UnknownRemoteError,\n} from './errors.js';\nimport {\n readToonConfig,\n getGitRemoteUrls,\n resolveRepoRoot,\n} from './git-config.js';\nimport { MissingRemoteObjectsError } from './clone.js';\nimport type { ReadCommandDeps } from './read-seams.js';\n\nexport const FETCH_USAGE = `Usage: rig fetch [remote] [options]\n\nFetch from a TOON remote — FREE (relay reads + Arweave gateway downloads; no\npayments, no identity needed). Reads the kind:30618 repository state from the\nremote's relay, downloads only the git objects this repository is missing\n(SHA-1 verified), and updates the remote-tracking refs\n(refs/remotes/<remote>/*; tags land at refs/tags/*), reporting what moved.\n\nNo merge happens: integrate with the git passthrough, e.g.\n\\`rig merge origin/main\\`. \\`rig fetch\\` is the TOON transport and shadows\n\\`git fetch\\` — plain-git fetches remain available via \\`git fetch\\` directly.\n\nThe repo address (toon.repoid/toon.owner) comes from the config \\`rig init\\`\nor \\`rig clone\\` writes; --repo-id/--owner override.\n\nOptions:\n --repo-id <id> repository id / NIP-34 d-tag (default: git config)\n --owner <pubkey> repository owner (npub or 64-char hex; default: git config)\n --relay <url> ad-hoc relay override — bypasses the remote's URL\n --gateway <url> gateway to read objects through FIRST, on its raw-bytes\n route <url>/raw/<txId>, ahead of the public gateway\n list — name a private, local or air-gapped gateway to\n fetch objects the public ones do not carry\n (env RIG_ARWEAVE_GATEWAY also sets it)\n --concurrency <n> parallel gateway downloads (default 8)\n --json machine-readable result envelope\n -h, --help show this help`;\n\n/** One remote-tracking ref movement, `git fetch`-style. */\nexport interface RefUpdate {\n /** Remote refname (as announced), e.g. `refs/heads/main`. */\n refname: string;\n /** Local ref that was updated, e.g. `refs/remotes/origin/main`. */\n localRef: string;\n oldSha: string | null;\n newSha: string;\n kind: 'new' | 'fast-forward' | 'forced' | 'up-to-date';\n}\n\nconst WS_URL_RE = /^wss?:\\/\\//i;\n\n/** Map an announced refname to its local destination for `remote`. */\nfunction localRefFor(refname: string, remote: string): string | null {\n if (refname.startsWith('refs/heads/')) {\n return `refs/remotes/${remote}/${refname.slice('refs/heads/'.length)}`;\n }\n if (refname.startsWith('refs/tags/')) return refname;\n return null; // exotic namespaces are skipped\n}\n\n/** rev-parse a ref, null when it doesn't exist. */\nasync function resolveLocalRef(\n repoRoot: string,\n refname: string\n): Promise<string | null> {\n try {\n const out = await runGit(repoRoot, [\n 'rev-parse',\n '--verify',\n '--quiet',\n refname,\n ]);\n const sha = out.trim();\n return /^[0-9a-f]{40}$/.test(sha) ? sha : null;\n } catch {\n return null;\n }\n}\n\n/** Run `rig fetch …`; returns the process exit code. */\nexport async function runFetch(\n args: string[],\n deps: ReadCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let json = false;\n let remote = 'origin';\n let relayFlag: string | undefined;\n let repoIdFlag: string | undefined;\n let ownerFlag: string | undefined;\n let gatewayFlag: string | undefined;\n let concurrency: number | undefined;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n relay: { type: 'string' },\n 'repo-id': { type: 'string' },\n owner: { type: 'string' },\n gateway: { type: 'string' },\n concurrency: { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: true,\n });\n if (values.help) {\n io.out(FETCH_USAGE);\n return 0;\n }\n json = values.json === true;\n if (positionals.length > 1) {\n throw new Error(\n `expected at most one [remote] argument, got ${positionals.length}`\n );\n }\n if (positionals[0] !== undefined) remote = positionals[0];\n relayFlag = values.relay;\n repoIdFlag = values['repo-id'];\n ownerFlag =\n values.owner !== undefined ? ownerToHex(values.owner) : undefined;\n gatewayFlag = values.gateway;\n if (values.concurrency !== undefined) {\n concurrency = Number.parseInt(values.concurrency, 10);\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) {\n throw new Error('--concurrency must be a positive integer');\n }\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(FETCH_USAGE);\n return 2;\n }\n\n try {\n // ── Repo addressing + relay resolution ─────────────────────────────────\n const repoRoot = await resolveRepoRoot(deps.cwd);\n const toonConfig = await readToonConfig(repoRoot);\n const repoId = repoIdFlag ?? toonConfig.repoId;\n if (!repoId) throw new UnconfiguredRepoAddressError('repository id');\n const owner = ownerFlag ?? toonConfig.owner;\n if (!owner) throw new UnconfiguredRepoAddressError('repository owner');\n\n let relayUrl: string;\n if (relayFlag !== undefined) {\n relayUrl = relayFlag;\n } else {\n const urls = await getGitRemoteUrls(repoRoot, remote);\n if (urls.length === 0) throw new UnknownRemoteError(remote);\n if (urls.length > 1) throw new MultiUrlRemoteError(remote, urls);\n relayUrl = urls[0] as string;\n }\n if (!WS_URL_RE.test(relayUrl)) {\n throw new InvalidRelayUrlError(\n relayUrl,\n `remote ${JSON.stringify(remote)}`\n );\n }\n\n // ── Remote state ────────────────────────────────────────────────────────\n const remoteState = await fetchRemoteState({\n relayUrls: [relayUrl],\n ownerPubkey: owner,\n repoId,\n ...(deps.webSocketFactory\n ? { webSocketFactory: deps.webSocketFactory }\n : {}),\n // The GraphQL fallback for SHAs the map does not cover asks the SAME\n // permaweb the objects are read from (#183).\n resolveSha: deps.resolveSha ?? shaResolverFor(gatewayFlag, deps.env),\n });\n\n // Plan the tracking-ref updates (hostile-relay refname gate included).\n const planned: { refname: string; localRef: string; newSha: string }[] = [];\n for (const [refname, sha] of remoteState.refs) {\n if (!isSafeRefname(refname)) {\n io.err(\n `warning: skipping unsafe ref name from relay: ${JSON.stringify(refname)}`\n );\n continue;\n }\n const localRef = localRefFor(refname, remote);\n if (localRef === null) {\n io.err(\n `warning: skipping ref outside refs/heads and refs/tags: ${refname}`\n );\n continue;\n }\n planned.push({ refname, localRef, newSha: sha });\n }\n\n // ── Delta: download only what the local repository is missing ──────────\n const reader = new GitRepoReader(repoRoot);\n const tips = [...new Set(planned.map((p) => p.newSha))];\n // What the repository already has, read from the object database itself.\n // NOT derived from the remote's `arweave` map: that map is capped (#162)\n // and a SHA missing from it says nothing about local presence — deriving\n // \"have\" from it would re-download history this repo already holds.\n const presentLocally = new Set(await reader.listAllObjectShas());\n\n const collected = await collectRepoObjects({\n tips,\n shaToTxId: remoteState.shaToTxId,\n resolveMissing: (shas) => remoteState.resolveMissing(shas),\n presentLocally,\n // `--gateway` / RIG_ARWEAVE_GATEWAY first, public list behind it (#176).\n gateways: readGateways(gatewayFlag, deps.env),\n ...(deps.fetchFn ? { fetchFn: deps.fetchFn } : {}),\n ...(concurrency !== undefined ? { concurrency } : {}),\n });\n if (collected.missing.length > 0) {\n throw new MissingRemoteObjectsError(\n collected.missing,\n `cannot fetch from ${relayUrl}`\n );\n }\n const written = await writeGitObjects(repoRoot, collected.objects.values());\n\n // ── Update tracking refs + report movements ─────────────────────────────\n const updates: RefUpdate[] = [];\n for (const { refname, localRef, newSha } of planned) {\n const oldSha = await resolveLocalRef(repoRoot, localRef);\n if (oldSha === newSha) {\n updates.push({ refname, localRef, oldSha, newSha, kind: 'up-to-date' });\n continue;\n }\n let kind: RefUpdate['kind'];\n if (oldSha === null) {\n kind = 'new';\n } else {\n kind = (await reader.isAncestor(oldSha, newSha))\n ? 'fast-forward'\n : 'forced';\n }\n await updateRef(repoRoot, localRef, newSha);\n updates.push({ refname, localRef, oldSha, newSha, kind });\n }\n\n // ── Report ──────────────────────────────────────────────────────────────\n const moved = updates.filter((u) => u.kind !== 'up-to-date');\n if (json) {\n io.emitJson({\n command: 'fetch',\n repoAddr: { ownerPubkey: owner, repoId },\n remote,\n relay: relayUrl,\n objectsDownloaded: written,\n updates,\n executed: true,\n });\n return 0;\n }\n if (moved.length === 0) {\n io.out('Already up to date.');\n return 0;\n }\n io.out(`From ${relayUrl}`);\n for (const u of moved) {\n const short = (refname: string): string =>\n refname\n .replace(/^refs\\/heads\\//, '')\n .replace(/^refs\\/tags\\//, '')\n .replace(/^refs\\/remotes\\//, '');\n const src = short(u.refname);\n const dst = short(u.localRef);\n if (u.kind === 'new') {\n const label = u.refname.startsWith('refs/tags/')\n ? '[new tag]'\n : '[new branch]';\n io.out(` * ${label.padEnd(17)} ${src.padEnd(14)} -> ${dst}`);\n } else if (u.kind === 'forced') {\n io.out(\n ` + ${(u.oldSha as string).slice(0, 7)}...${u.newSha.slice(0, 7)} ${src.padEnd(14)} -> ${dst} (forced update)`\n );\n } else {\n io.out(\n ` ${(u.oldSha as string).slice(0, 7)}..${u.newSha.slice(0, 7)} ${src.padEnd(14)} -> ${dst}`\n );\n }\n }\n io.out(`Downloaded ${written} object(s) (SHA-1 verified).`);\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'fetch', err);\n }\n}\n","/**\n * `rig fund` — drip devnet test funds to the active identity's wallet (#263).\n *\n * A FREE command: no relay, no client start, no nonce guard, no payment\n * channel — just the identity chain (RIG_MNEMONIC precedence, ./identity.ts)\n * to derive the chain address(es), and an HTTP POST per chain to the devnet\n * faucet (`@toon-protocol/client`'s `fundWallet`, which hits the USDC-ONLY\n * legs: `POST {faucet}/api/base-sepolia/request` for EVM,\n * `/api/solana/usdc-request`, `/api/mina/usdc-request` — body `{ address }`;\n * the faucet drips a FIXED amount, so there is no --amount). Each per-chain\n * drip funds ONLY the settlement token (USDC) and ASSUMES the wallet already\n * holds enough native gas to transact — the EVM leg still best-effort tops up\n * Base Sepolia gas, but Solana/Mina expect the address to already hold SOL/MINA.\n *\n * MULTI-CHAIN BY DEFAULT: with no chain argument, `rig fund` funds ALL supported\n * chains (evm + solana + mina) so the wallet matches the multi-chain\n * `rig balance` view (#299) in one run instead of three. A chain argument —\n * positional (`rig fund sol`) or `--chain <one>` — narrows to a single chain;\n * `all` is the explicit alias for the default. The drips run in PARALLEL — the\n * Mina faucet legitimately takes\n * ~75s, so serializing would cost ~150s for a run that overlaps to ~75s — and\n * each chain's result is INDEPENDENT: one chain's faucet failing never aborts\n * the others. Exit code is 0 only when every targeted chain funded; if any\n * chain failed the exit code is 1 and the per-chain breakdown is always shown.\n *\n * Faucet resolution mirrors the toon-clientd conventions\n * (client-mcp/src/daemon/config.ts — no import, keep in sync):\n * `TOON_CLIENT_FAUCET_URL` env → `faucetUrl` in the shared client config →\n * the deployed devnet faucet when the network IS (or is inferred as) devnet.\n * A configured `*.devnet.toonprotocol.dev` origin infers devnet even when\n * `network` still reads its `custom` default (#288) — that origin is BOTH a\n * devnet-looking relay/proxy/btp endpoint in env/config AND the git `origin`\n * remote `rig remote` configures (resolved the same way push/fetch resolve\n * their relay), so a fresh user who only ran `rig remote add origin\n * wss://relay-ws.devnet.toonprotocol.dev` gets the drip from a plain\n * `rig fund` with no env var. A truly FRESH install — no origin configured\n * anywhere (env, config, git `origin`) — falls back to core's committed\n * genesis seed, whose relay/btp origin names the live shared devnet, so\n * `npm i -g @toon-protocol/rig && rig fund` drips with zero config; any\n * configured origin (devnet or not) suppresses the seed, keeping the #288\n * \"explicit stays authoritative\" rule. On any other network there is no\n * faucet: the command prints the derived wallet address(es) to fund\n * externally instead of failing silently.\n *\n * The drips are awaited (a CLI has no background) but run concurrently: the\n * Mina 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) and a serial evm→solana→mina run would\n * stack those budgets — parallel drips overlap them.\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 { readToonConfig, resolveRepoRoot } from './git-config.js';\nimport { resolveIdentity } from './identity.js';\nimport type { CliIo, IdentityReport } from './push.js';\nimport { renderIdentityLine } from './render.js';\nimport { resolveRelays } from './remote.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'] as const;\ntype FundChain = (typeof CHAINS)[number];\n\n/**\n * Accepted chain arguments (positional `rig fund sol` or `--chain sol`), mapped\n * to the canonical selector. Short aliases (`sol`) are accepted alongside the\n * canonical names; `all` funds every supported chain (the default).\n */\nconst CHAIN_ALIASES: Record<string, FundChain | 'all'> = {\n evm: 'evm',\n eth: 'evm',\n sol: 'solana',\n solana: 'solana',\n all: 'all',\n};\n\n/** Human-readable list of accepted chain arguments (for usage/errors). */\nconst CHAIN_ARG_LIST = 'evm | sol | solana | all';\n\n/**\n * Resolve a raw chain argument (positional or `--chain`) to the canonical\n * selector, accepting short aliases. Throws a usage error on an unknown value.\n * Returns `undefined` when no chain was given (→ the all-chains default).\n */\nfunction resolveChainArg(raw: string | undefined): FundChain | 'all' | undefined {\n if (raw === undefined) return undefined;\n const canonical = CHAIN_ALIASES[raw.toLowerCase()];\n if (!canonical) {\n throw new Error(\n `chain must be one of ${CHAIN_ARG_LIST}, got ${JSON.stringify(raw)}`\n );\n }\n return canonical;\n}\n\nexport const FUND_USAGE = `Usage: rig fund [chain] [options]\n\nDrip devnet USDC to the active identity's wallet — free (the faucet pays). Each\ndrip funds ONLY the settlement token (USDC) and assumes the wallet already holds\nenough native gas to transact. By default funds ALL supported chains (evm +\nsolana + mina) so the wallet matches the multi-chain \\`rig balance\\` view in one\nrun; name a chain — positional (\\`rig fund sol\\`) or \\`--chain\\` — to narrow to\none. The per-chain drips run in parallel and are independent — one chain's\nfaucet failing does not abort the others (exit 0 only when every targeted chain\nfunded; exit 1 if any failed, with the per-chain breakdown always shown).\n\nThe identity comes from RIG_MNEMONIC (env or a project .env) or the\n~/.toon-client keystore/config; the faucet from TOON_CLIENT_FAUCET_URL, the\nfaucetUrl config field, or the deployed devnet faucet when the network is\ndevnet — including when a configured *.devnet.toonprotocol.dev origin infers\nit (a devnet relay/proxy/btp endpoint, or the git origin remote from\n\\`rig remote add origin <devnet relay>\\`). A completely fresh install with NO\norigin configured anywhere infers devnet from the built-in genesis seed, so a\nbare \\`rig fund\\` works with zero config. The faucet drips a FIXED amount per\nchain (there is no --amount). On a network without a faucet, prints the wallet\naddress(es) to fund externally instead.\n\nOptions:\n [chain] evm | sol | solana | mina | all — positional chain to\n fund (default: all supported chains)\n --chain <chain> same as the positional chain argument\n --address <address> fund this address instead of the identity's own\n (requires an explicit single chain)\n --json machine-readable envelope (per-chain results array)\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 * Genesis-seed loader seam: consulted ONLY when nothing else — env, config,\n * or the git `origin` remote — names an origin at all (a truly fresh\n * install with no config). Defaults to the lazy standalone\n * network-bootstrap import (core's committed genesis peer); tests inject.\n */\n loadGenesisSeed?: () => Promise<\n { relayUrl?: string; btpEndpoint?: string } | undefined\n >;\n}\n\n/** The slice of the shared client config file `rig fund` consumes. */\nexport interface FundConfigFile {\n network?: string;\n faucetUrl?: string;\n faucetTimeoutMs?: number;\n relayUrl?: string;\n proxyUrl?: string;\n btpUrl?: string;\n}\n\n/** One chain's drip outcome — the parallel, independent unit of work. */\ninterface ChainDripResult {\n chain: FundChain;\n /** True when this chain's faucet drip succeeded. */\n funded: boolean;\n /** The address that was (or would have been) funded; null if none derived. */\n address: string | null;\n /** Raw faucet response body on success (shape is faucet-defined). */\n response?: unknown;\n /** Failure reason when `funded` is false. */\n error?: string;\n /** Wall-clock duration of this chain's drip in ms (present once attempted). */\n elapsedMs?: number;\n}\n\n/** `--json` envelope. */\ninterface FundJson {\n command: 'fund';\n identity: IdentityReport;\n /** True only when EVERY targeted chain funded (overall success). */\n funded: boolean;\n network: string | null;\n faucetUrl?: string;\n /** The per-chain drip results (one entry per targeted chain). */\n results?: ChainDripResult[];\n /**\n * Set when `network` was inferred as `devnet` from a\n * `*.devnet.toonprotocol.dev` origin (#288) rather than an explicit\n * `TOON_CLIENT_NETWORK`/config value — carries the origin that triggered\n * it. A fresh-install inference from the built-in genesis seed (no origin\n * configured anywhere) is marked with a ` (genesis seed)` suffix.\n */\n inferredDevnetFrom?: string;\n /** Non-devnet path: the derived wallet addresses to fund externally. */\n addresses?: { evm: string | null; solana: string | null };\n guidance?: string;\n}\n\n/** Hostname suffix of every shared-devnet edge (relay, proxy, faucet …). */\nconst SHARED_DEVNET_SUFFIX = '.devnet.toonprotocol.dev';\n\n/** `url` when its host is a shared-devnet edge (`*.devnet.toonprotocol.dev`). */\nfunction devnetHost(url: string | undefined): string | undefined {\n if (!url) return undefined;\n try {\n const { hostname } = new URL(url);\n if (\n hostname.endsWith(SHARED_DEVNET_SUFFIX) ||\n hostname === SHARED_DEVNET_SUFFIX.slice(1)\n ) {\n return url;\n }\n } catch {\n // junk URL — other commands surface that; fund only sniffs\n }\n return undefined;\n}\n\n/**\n * The first configured relay/uplink URL that points at the shared devnet\n * (`*.devnet.toonprotocol.dev`), if any. When the user's endpoints already\n * target the shared devnet but `network` still says `custom`, the fix for a\n * failed `rig fund` is `TOON_CLIENT_NETWORK=devnet` — NOT hunting for a\n * faucet URL (the #280 UX-study trap).\n *\n * The candidate endpoints are the env/config relay/proxy/btp URLs PLUS the\n * relay(s) resolved from the git `origin` remote (`originRelays`, resolved by\n * the same `rig remote`/git-config path push and fetch use — see\n * {@link resolveOriginRelays}). The git origin is the endpoint a fresh user\n * actually configures with `rig remote add origin <devnet relay>`; keying off\n * only env/config (#291) missed it, so plain `rig fund` still refused to drip\n * (#288 reopened). Exported for tests.\n */\nexport function sharedDevnetOrigin(\n env: NodeJS.ProcessEnv,\n file: FundConfigFile,\n originRelays: string[] = []\n): string | undefined {\n const candidates = [\n env['TOON_CLIENT_RELAY_URL'] ?? file.relayUrl,\n env['TOON_CLIENT_PROXY_URL'] ?? file.proxyUrl,\n env['TOON_CLIENT_BTP_URL'] ?? file.btpUrl,\n ...originRelays,\n ];\n for (const url of candidates) {\n const hit = devnetHost(url);\n if (hit) return hit;\n }\n return undefined;\n}\n\n/**\n * The relay URL(s) the git `origin` remote resolves to — the SAME resolution\n * `rig push`/`rig fetch` use (`resolveRelays` over the repo's real git\n * remotes + the deprecated `toon.relay` fallback). `rig fund` only sniffs the\n * host for the devnet suffix, so every failure mode is swallowed to `[]`: not\n * a git repo, no `origin`, a non-relay `origin` (a GitHub clone URL), or an\n * ambiguous multi-URL origin all mean \"no origin relay to infer from\" — never\n * an error out of a free command.\n */\n/**\n * Default {@link FundDeps.loadGenesisSeed}: core's committed genesis peer,\n * loaded lazily (same pattern as `rig init`'s offline relay fallback) so a\n * run that never needs it — any configured origin — never drags the\n * standalone bootstrap in. Failures mean \"no seed\", never an error out of a\n * free command.\n */\nasync function loadGenesisSeedDefault(): Promise<\n { relayUrl?: string; btpEndpoint?: string } | undefined\n> {\n // There is no built-in network seed since 4.0: a node is named (TOON_CONNECTOR\n // / `rig entry <url>`), never discovered. Nothing configured means no seed.\n return undefined;\n}\n\n/**\n * The devnet-or-not decision shared by `rig fund` and `rig name` (#288 + the\n * genesis-seed fresh-install fallback). Precedence:\n *\n * 1. An explicit non-`custom` `TOON_CLIENT_NETWORK`/config `network` is\n * authoritative — never coerced.\n * 2. Otherwise a configured `*.devnet.toonprotocol.dev` origin (env/config\n * relay/proxy/btp URL, or the git `origin` relay) infers devnet.\n * 3. Otherwise — NOTHING configured anywhere (a truly fresh install) —\n * core's committed genesis seed is consulted. Its URLs still go through\n * {@link devnetHost}: \"seed\" never hardcodes \"devnet\"; a future seed\n * pointing elsewhere simply stops inferring. Any configured origin,\n * devnet or not, suppresses the seed so a deliberately non-devnet setup\n * keeps refusing to drip.\n *\n * Exported for `rig name` (default `--via` DVM) and tests.\n */\nexport async function resolveEffectiveNetwork(opts: {\n env: NodeJS.ProcessEnv;\n cwd: string;\n /** Pre-read client config slice (callers that already loaded it). */\n file?: FundConfigFile;\n /** Genesis-seed loader seam (tests inject; default core's committed seed). */\n loadGenesisSeed?: FundDeps['loadGenesisSeed'];\n}): Promise<{\n /** The explicit env/config network value, if any. */\n network: string | undefined;\n /** `network` with devnet inference applied. */\n effectiveNetwork: string | undefined;\n /** The devnet-looking origin that drove (or could drive) inference. */\n devnetOrigin: string | undefined;\n /** True when the origin came from the built-in genesis seed. */\n seededOrigin: boolean;\n /** True when `effectiveNetwork` is an INFERRED devnet (not explicit). */\n inferredDevnet: boolean;\n}> {\n const { env, cwd } = opts;\n const file = opts.file ?? readFundConfig(env).file;\n const network = env['TOON_CLIENT_NETWORK'] ?? file.network;\n const canInfer = network === undefined || network === 'custom';\n const originRelays = canInfer ? await resolveOriginRelays(cwd) : [];\n let devnetOrigin = sharedDevnetOrigin(env, file, originRelays);\n let seededOrigin = false;\n if (devnetOrigin === undefined && canInfer) {\n const anyConfiguredOrigin = [\n env['TOON_CLIENT_RELAY_URL'] ?? file.relayUrl,\n env['TOON_CLIENT_PROXY_URL'] ?? file.proxyUrl,\n env['TOON_CLIENT_BTP_URL'] ?? file.btpUrl,\n ...originRelays,\n ].some((url) => url !== undefined);\n if (!anyConfiguredOrigin) {\n const seed = await (opts.loadGenesisSeed ?? loadGenesisSeedDefault)();\n devnetOrigin = devnetHost(seed?.relayUrl) ?? devnetHost(seed?.btpEndpoint);\n seededOrigin = devnetOrigin !== undefined;\n }\n }\n const inferredDevnet = devnetOrigin !== undefined && canInfer;\n return {\n network,\n effectiveNetwork: inferredDevnet ? 'devnet' : network,\n devnetOrigin,\n seededOrigin,\n inferredDevnet,\n };\n}\n\nexport async function resolveOriginRelays(cwd: string): Promise<string[]> {\n let repoRoot: string;\n try {\n repoRoot = await resolveRepoRoot(cwd);\n } catch {\n return [];\n }\n try {\n const toonConfig = await readToonConfig(repoRoot);\n const resolved = await resolveRelays({\n relayFlags: [],\n remoteName: undefined,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n return resolved.relays;\n } catch {\n return [];\n }\n}\n\n/**\n * Remediation for `rig fund` on a network without a faucet. Orders the\n * suggestions by likelihood (#280): the network preset FIRST — a fresh\n * config defaults to `custom`, and on the shared devnet the whole fix is\n * `TOON_CLIENT_NETWORK=devnet` — then the faucet-URL override for\n * self-hosted networks, then external funding. Exported for tests.\n */\nexport function noFaucetGuidance(\n network: string | undefined,\n devnetOrigin: string | undefined\n): string {\n const head = `no faucet is configured for network ${JSON.stringify(network ?? 'custom')}`;\n const external =\n 'To fund the wallet externally instead, send the settlement token plus ' +\n 'native gas to the address below for the chain your channels settle on.';\n if (devnetOrigin !== undefined) {\n return (\n `${head} — but your configured origin (${devnetOrigin}) looks like ` +\n 'the shared devnet. Set TOON_CLIENT_NETWORK=devnet (or \"network\": ' +\n '\"devnet\" in the client config) and re-run `rig fund` — no faucet ' +\n `URL is needed there. ${external}`\n );\n }\n return (\n `${head}. If you meant the shared devnet, set TOON_CLIENT_NETWORK=devnet ` +\n 'and re-run `rig fund` — no faucet URL is needed there. If this is a ' +\n 'self-hosted network with its own faucet, set TOON_CLIENT_FAUCET_URL ' +\n `(or the faucetUrl config field). ${external}`\n );\n}\n\nfunction readFundConfig(env: NodeJS.ProcessEnv): {\n file: FundConfigFile;\n configPath: string;\n} {\n const dir = env['TOON_CLIENT_HOME'] ?? join(homedir(), '.toon-client');\n const configPath = join(dir, 'config.json');\n try {\n return {\n file: JSON.parse(readFileSync(configPath, 'utf8')) as FundConfigFile,\n configPath,\n };\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { file: {}, configPath };\n }\n throw new Error(\n `failed to read client config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n}\n\n/** Run `rig fund`; returns the process exit code. */\nexport async function runFund(args: string[], deps: FundDeps): Promise<number> {\n const { io, env } = deps;\n\n let resolvedChain: FundChain | 'all' | undefined;\n let addressFlag: string | undefined;\n let json = false;\n try {\n const { values, positionals } = parseArgs({\n args,\n allowPositionals: true,\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 // The chain can be given positionally (`rig fund sol`) OR with `--chain`,\n // but not both, and at most one positional is accepted.\n if (positionals.length > 1) {\n throw new Error(\n `rig fund takes at most one chain argument, got ${positionals.length}: ${positionals.join(' ')}`\n );\n }\n const positionalChain = positionals[0];\n if (positionalChain !== undefined && values.chain !== undefined) {\n throw new Error(\n 'give the chain as a positional argument (`rig fund sol`) OR with --chain, not both'\n );\n }\n resolvedChain = resolveChainArg(positionalChain ?? values.chain);\n addressFlag = values.address;\n json = values.json ?? false;\n // A per-chain address (`--address`) is meaningless across chains — an EVM\n // 0x address cannot fund Solana or Mina. Require an explicit single chain.\n if (addressFlag !== undefined && (resolvedChain === undefined || resolvedChain === 'all')) {\n throw new Error(\n `--address requires an explicit single chain (${CHAIN_ARG_LIST}) — ` +\n 'a single address cannot fund every chain'\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 // MULTI-CHAIN BY DEFAULT (#299 parity): no chain argument (or `all`) funds\n // every supported chain; a specific chain narrows to one. The env/config\n // `chain` settlement preference no longer narrows `rig fund` — funding all\n // chains is a strict superset and matches `rig balance`.\n const targetChains: FundChain[] =\n resolvedChain === undefined || resolvedChain === 'all'\n ? [...CHAINS]\n : [resolvedChain];\n const network = env['TOON_CLIENT_NETWORK'] ?? file.network;\n // A configured `*.devnet.toonprotocol.dev` origin means the shared devnet\n // even when `network` still reads its `custom` default (#288): the host\n // already encodes it, so infer devnet and let the faucet \"just work\"\n // instead of making the user also export TOON_CLIENT_NETWORK=devnet. The\n // origin can be an env/config relay/proxy/btp endpoint OR the git `origin`\n // remote `rig remote add origin …` configured (resolved like push/fetch);\n // a fresh user who only ran that must still get the drip. An EXPLICIT\n // non-`custom` network stays authoritative — it is never coerced.\n //\n // Only an unset/`custom` network can be inferred to devnet; when the\n // network is explicit and non-`custom` the inference is a no-op, so skip\n // the git-origin resolution (several `git` subprocesses) entirely.\n const { devnetOrigin, seededOrigin, inferredDevnet, effectiveNetwork } =\n await resolveEffectiveNetwork({\n env,\n cwd: deps.cwd,\n file,\n ...(deps.loadGenesisSeed\n ? { loadGenesisSeed: deps.loadGenesisSeed }\n : {}),\n });\n const faucetUrl =\n env['TOON_CLIENT_FAUCET_URL'] ??\n file.faucetUrl ??\n (effectiveNetwork === 'devnet' ? DEVNET_FAUCET_URL : undefined);\n\n // ── Identity chain → wallet addresses (never the phrase) ────────────────\n const resolved = await resolveIdentity({\n env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n });\n const identity: IdentityReport = {\n pubkey: resolved.pubkey,\n source: resolved.source,\n sourceLabel: resolved.sourceLabel,\n };\n // Dynamic import: `@toon-protocol/client` is heavy; runs that fail\n // earlier (usage errors) never pay its startup cost.\n const client = await import('@toon-protocol/client');\n const derived = client.deriveFullIdentity(resolved.mnemonic, {\n accountIndex: resolved.accountIndex,\n scheme: 'legacy',\n });\n const addresses = {\n evm: derived.evm.address || null,\n solana: derived.solana.publicKey || null,\n };\n\n // ── No faucet on this network: name the ACTUAL knob first (#280) ────────\n if (!faucetUrl) {\n const guidance = noFaucetGuidance(network, devnetOrigin);\n if (json) {\n io.emitJson({\n command: 'fund',\n identity,\n funded: false,\n network: network ?? null,\n 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 return 0;\n }\n\n // ── Devnet faucet drips (parallel, independent per chain) ───────────────\n // Env/config override applies uniformly to every chain's drip.\n const timeoutEnv = env['TOON_CLIENT_FAUCET_TIMEOUT_MS'];\n const timeoutFor = (): number => {\n if (timeoutEnv && Number.isFinite(Number(timeoutEnv))) return Number(timeoutEnv);\n if (file.faucetTimeoutMs !== undefined) return file.faucetTimeoutMs;\n return 90_000;\n };\n\n if (!json && inferredDevnet) {\n io.out(\n seededOrigin\n ? `Inferred network 'devnet' from the built-in genesis seed ` +\n `${devnetOrigin} (nothing configured — fresh install). ` +\n 'Set TOON_CLIENT_NETWORK explicitly to override.'\n : `Inferred network 'devnet' from the configured origin ${devnetOrigin} ` +\n `(network was ${JSON.stringify(network ?? 'custom')}). ` +\n 'Set TOON_CLIENT_NETWORK explicitly to override.'\n );\n }\n if (!json) {\n const list = targetChains.join(', ');\n io.out(\n `Requesting ${targetChains.length === 1 ? '' : 'parallel '}USDC drip${targetChains.length === 1 ? '' : 's'} ` +\n `from ${faucetUrl} for ${list} …`\n );\n }\n\n // Each chain is an INDEPENDENT unit: derive-or-fail and drip-or-fail are\n // both captured into a ChainDripResult so one chain's failure never\n // rejects the batch. Kicking every drip off before awaiting makes them\n // genuinely concurrent (the Mina ~75s overlaps evm/solana, not stacks).\n const singleChain = targetChains.length === 1;\n const drips = targetChains.map(async (chain): Promise<ChainDripResult> => {\n const address = (singleChain ? addressFlag : undefined) ?? addresses[chain];\n if (!address) {\n return {\n chain,\n funded: false,\n address: null,\n error: `no ${chain} address could be derived for this identity`,\n };\n }\n const started = Date.now();\n try {\n const { response } = await client.fundWallet(faucetUrl, address, chain, {\n timeout: timeoutFor(),\n ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}),\n });\n return {\n chain,\n funded: true,\n address,\n response,\n elapsedMs: Date.now() - started,\n };\n } catch (err) {\n return {\n chain,\n funded: false,\n address,\n error: err instanceof Error ? err.message : String(err),\n elapsedMs: Date.now() - started,\n };\n }\n });\n const results = await Promise.all(drips);\n const allFunded = results.every((r) => r.funded);\n\n if (json) {\n io.emitJson({\n command: 'fund',\n identity,\n funded: allFunded,\n network: effectiveNetwork ?? null,\n faucetUrl,\n results,\n ...(inferredDevnet\n ? {\n inferredDevnetFrom: seededOrigin\n ? `${devnetOrigin} (genesis seed)`\n : devnetOrigin,\n }\n : {}),\n } satisfies FundJson);\n return allFunded ? 0 : 1;\n }\n\n for (const r of results) {\n const label = r.chain.padEnd(6);\n // Always echo the funded (or attempted) address so a human can confirm\n // WHERE the funds went — essential when `--address` targets an arbitrary,\n // non-derived address a typo could misdirect (only shown via --json\n // otherwise).\n const addr = r.address ? ` → ${r.address}` : '';\n if (r.funded) {\n // The faucet drips USDC only (gas is assumed); annotate the token, and\n // the wall time for slow chains (mina) so a >1-minute wait reads as normal.\n const slow = r.elapsedMs !== undefined && r.elapsedMs >= 5_000;\n const time = slow ? ` (${Math.round((r.elapsedMs as number) / 1000)}s)` : '';\n io.out(` ${label} ✓ funded (USDC)${addr}${time}`);\n } else {\n io.out(` ${label} ✗${addr} — ${r.error ?? 'failed'}`);\n }\n }\n io.out(renderIdentityLine(identity));\n io.out('Re-check with `rig balance` (a drip can take a few blocks to land).');\n return allFunded ? 0 : 1;\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 identity` — the cold-start identity command group (#294).\n *\n * rig resolves a signing identity along a precedence chain (./identity.ts) but,\n * before this command, it never MINTED one: a brand-new user hit\n * {@link MissingIdentityError} and had to hand-mint a BIP-39 phrase out of band\n * before anything ran. `rig identity` closes that gap while keeping rig's\n * deliberate security invariants intact:\n *\n * - `rig identity create` — generate a fresh BIP-39 mnemonic (via the\n * client's existing generator — no hand-rolled bip39/crypto), display it\n * ONCE with a prominent backup warning, and persist it to the ENCRYPTED\n * keystore under `TOON_CLIENT_HOME` (reusing the client/daemon keystore\n * write path + the auto-password convention). This is the ONLY command\n * that ever surfaces a phrase, and `--json` is the ONE sanctioned path\n * that emits the phrase in machine output (a scripting/agent need).\n * - `rig identity show` — report the active identity's SOURCE + derived\n * pubkey; NEVER the phrase, in any mode.\n * - `rig identity import` — read an existing phrase from stdin/prompt (NEVER\n * argv — that leaks to shell history / `ps`) and write it to the keystore.\n *\n * The phrase is written ONLY to the encrypted keystore (or shown once / emitted\n * in the sanctioned `create --json` envelope) — never to git config, never to a\n * repo file, never to plaintext outside the keystore. Persistence is gated on\n * the command being explicitly invoked (and refuses to clobber an existing\n * identity without `--force`).\n */\n\nimport { existsSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport { createInterface } from 'node:readline/promises';\nimport { parseArgs } from 'node:util';\nimport { emitCliError } from './errors.js';\nimport {\n clientConfigPath,\n clientKeystorePath,\n DEFAULT_KEYSTORE_PASSWORD,\n linkKeystoreInClientConfig,\n MissingIdentityError,\n readClientConfigFile,\n resolveAccountIndex,\n resolveIdentity,\n type ResolvedIdentity,\n} from './identity.js';\nimport type { CliIo } from './output.js';\nimport { renderIdentityLine } from './render.js';\nimport { deriveNostrKeyFromMnemonic } from '../standalone/nostr-identity.js';\n\n// ---------------------------------------------------------------------------\n// Deps + client-key seam\n// ---------------------------------------------------------------------------\n\n/** The `@toon-protocol/client` key operations `rig identity` reuses. */\nexport interface IdentityKeyOps {\n /** Generate a fresh mnemonic, encrypt it, and write the keystore to `path`. */\n generateKeystore(path: string, password: string): { mnemonic: string };\n /** Validate + encrypt an existing mnemonic and write the keystore to `path`. */\n importKeystore(path: string, mnemonic: string, password: string): unknown;\n /** Derive the Nostr pubkey (hex) for a mnemonic at a BIP-44 account index. */\n deriveNostrKeyFromMnemonic(\n mnemonic: string,\n accountIndex?: number\n ): { pubkey: string };\n}\n\n/** Default key-ops loader: the real client, dynamically imported (see below). */\nasync function loadKeyOps(): Promise<IdentityKeyOps> {\n const { generateKeystore, importKeystore } = await import(\n '@toon-protocol/client'\n );\n return { generateKeystore, importKeystore, deriveNostrKeyFromMnemonic };\n}\n\n/** Deps `rig identity` needs; the seams default to the real implementations. */\nexport interface IdentityDeps {\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 /** Client key-ops seam (tests); defaults to `@toon-protocol/client`. */\n loadKeyOps?: () => Promise<IdentityKeyOps>;\n /**\n * Read one line of secret input for `rig identity import` (tests). Defaults\n * to a stdin read (prompt on stderr when interactive). NEVER argv.\n */\n readSecretLine?: (prompt: string, isInteractive: boolean) => Promise<string>;\n}\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/** Refused: an identity already resolves and `--force` was not given. */\nexport class IdentityExistsError extends Error {\n constructor(\n public readonly pubkey: string,\n public readonly sourceLabel: string\n ) {\n super(\n `an identity already resolves (${pubkey}, from ${sourceLabel}) — rig ` +\n 'will not overwrite it. Inspect it with `rig identity show`, or pass ' +\n '`--force` to replace the keystore with a brand-new identity (the old ' +\n 'phrase becomes unrecoverable unless you backed it up).'\n );\n this.name = 'IdentityExistsError';\n }\n}\n\n/** Refused: a keystore file already sits at the target path (unlinked). */\nexport class KeystoreFileExistsError extends Error {\n constructor(public readonly keystorePath: string) {\n super(\n `a keystore file already exists at ${keystorePath} — rig will not ` +\n 'overwrite it. Link it via the client config, or pass `--force` to ' +\n 'replace it with a new identity.'\n );\n this.name = 'KeystoreFileExistsError';\n }\n}\n\n// ---------------------------------------------------------------------------\n// Core: generate / import → encrypted keystore\n// ---------------------------------------------------------------------------\n\n/** A newly minted (or imported) identity — the phrase is present ONLY here. */\nexport interface CreatedIdentity {\n /** The BIP-39 phrase. Surfaced only by `create` (once / `--json`). */\n mnemonic: string;\n pubkey: string;\n keystorePath: string;\n configPath: string;\n /** True when rig chose the default keystore password (no user password). */\n autoPassword: boolean;\n accountIndex: number;\n /**\n * Set only when a HIGHER-precedence source (env / .env) still shadows the\n * new keystore identity — possible only under `--force`.\n */\n shadowedBy?: { sourceLabel: string; pubkey: string };\n}\n\n/** Inputs shared by `create` and `import` (IO-free core). */\nexport interface MintIdentityInput {\n env: NodeJS.ProcessEnv;\n cwd: string;\n /** Overwrite an existing identity / keystore file. */\n force: boolean;\n warn(line: string): void;\n resolveIdentityImpl?: typeof resolveIdentity;\n loadKeyOps?: () => Promise<IdentityKeyOps>;\n}\n\ninterface KeystoreTarget {\n keystorePath: string;\n password: string;\n autoPassword: boolean;\n /** An identity that already resolved (guards + shadow reporting). */\n existing?: ResolvedIdentity;\n keyOps: IdentityKeyOps;\n}\n\n/** Guard against clobbering, resolve the keystore path + password. */\nasync function prepareKeystoreTarget(\n input: MintIdentityInput\n): Promise<KeystoreTarget> {\n const keyOps = await (input.loadKeyOps ?? loadKeyOps)();\n const resolveImpl = input.resolveIdentityImpl ?? resolveIdentity;\n\n let existing: ResolvedIdentity | undefined;\n try {\n existing = await resolveImpl({\n env: input.env,\n cwd: input.cwd,\n warn: input.warn,\n });\n } catch (err) {\n if (!(err instanceof MissingIdentityError)) throw err;\n }\n if (existing && !input.force) {\n throw new IdentityExistsError(existing.pubkey, existing.sourceLabel);\n }\n\n const keystorePath = clientKeystorePath(input.env);\n if (existsSync(keystorePath) && !input.force) {\n throw new KeystoreFileExistsError(keystorePath);\n }\n\n // The keystore password comes ONLY from TOON_CLIENT_KEYSTORE_PASSWORD (env),\n // never a CLI flag: a `--password` argv would leak the value that decrypts\n // the keystore to shell history / `ps` / `/proc` — the exact exposure this\n // command deliberately avoids for the seed phrase itself. No env var → the\n // default password, so the identity reloads with no configuration.\n const envPassword = input.env['TOON_CLIENT_KEYSTORE_PASSWORD']?.trim() || undefined;\n const autoPassword = envPassword === undefined;\n const password = envPassword ?? DEFAULT_KEYSTORE_PASSWORD;\n\n mkdirSync(dirname(keystorePath), { recursive: true });\n return { keystorePath, password, autoPassword, existing, keyOps };\n}\n\n/** BIP-44 account index exactly as {@link resolveIdentity} will pick it for\n * the keystore this command mints (`RIG_ACCOUNT_INDEX` env > shared config >\n * 0), so the reported pubkey matches subsequent runs. */\nfunction readAccountIndex(env: NodeJS.ProcessEnv): number {\n const file = readClientConfigFile(clientConfigPath(env));\n return resolveAccountIndex(env, 'keystore', file);\n}\n\n/** Assemble the {@link CreatedIdentity} once a phrase is on disk. */\nfunction finishMint(\n input: MintIdentityInput,\n target: KeystoreTarget,\n mnemonic: string\n): CreatedIdentity {\n const configPath = linkKeystoreInClientConfig(\n input.env,\n target.keystorePath,\n target.autoPassword\n );\n const accountIndex = readAccountIndex(input.env);\n const { pubkey } = target.keyOps.deriveNostrKeyFromMnemonic(\n mnemonic,\n accountIndex\n );\n const result: CreatedIdentity = {\n mnemonic,\n pubkey,\n keystorePath: target.keystorePath,\n configPath,\n autoPassword: target.autoPassword,\n accountIndex,\n };\n if (target.existing && target.existing.pubkey !== pubkey) {\n result.shadowedBy = {\n sourceLabel: target.existing.sourceLabel,\n pubkey: target.existing.pubkey,\n };\n }\n return result;\n}\n\n/** Generate a fresh identity into the encrypted keystore. */\nexport async function createIdentity(\n input: MintIdentityInput\n): Promise<CreatedIdentity> {\n const target = await prepareKeystoreTarget(input);\n const { mnemonic } = target.keyOps.generateKeystore(\n target.keystorePath,\n target.password\n );\n return finishMint(input, target, mnemonic);\n}\n\n/** Import an existing phrase into the encrypted keystore (validated). */\nexport async function importIdentity(\n input: MintIdentityInput & { mnemonic: string }\n): Promise<CreatedIdentity> {\n const target = await prepareKeystoreTarget(input);\n // importKeystore validates the BIP-39 phrase before writing anything.\n target.keyOps.importKeystore(\n target.keystorePath,\n input.mnemonic,\n target.password\n );\n return finishMint(input, target, input.mnemonic);\n}\n\n// ---------------------------------------------------------------------------\n// Human display (the one-time backup banner)\n// ---------------------------------------------------------------------------\n\n/** The one-time seed-phrase backup banner (human, non-`--json`). */\nexport function createdIdentityBanner(result: CreatedIdentity): string[] {\n return [\n '',\n '════════════════════════════════════════════════════════════════',\n ' rig: generated a new identity',\n '════════════════════════════════════════════════════════════════',\n ` Nostr pubkey : ${result.pubkey}`,\n '',\n ' Seed phrase — this phrase CONTROLS YOUR FUNDS. Write it down and',\n ' store it safely. It is shown ONCE and CANNOT be recovered:',\n '',\n ` ${result.mnemonic}`,\n '',\n ` Encrypted keystore: ${result.keystorePath}`,\n result.autoPassword\n ? ' Encrypted with the default password, so the identity reloads with no\\n' +\n ' env var. To use your own password: set TOON_CLIENT_KEYSTORE_PASSWORD\\n' +\n ' and re-import with `rig identity import`.'\n : ' Encrypted with your TOON_CLIENT_KEYSTORE_PASSWORD.',\n '════════════════════════════════════════════════════════════════',\n '',\n ];\n}\n\n/** The stderr note fired after a fresh mint, when a higher tier shadows it. */\nexport function shadowNote(shadowedBy: {\n sourceLabel: string;\n pubkey: string;\n}): string {\n return (\n `note: a higher-precedence identity (${shadowedBy.pubkey}, from ` +\n `${shadowedBy.sourceLabel}) still shadows the new keystore — rig keeps ` +\n 'using it until you remove that source (unset the env var / edit .env).'\n );\n}\n\n// ---------------------------------------------------------------------------\n// Command dispatch\n// ---------------------------------------------------------------------------\n\nexport const IDENTITY_USAGE = `Usage: rig identity <command> [options]\n\nManage the BIP-39 signing identity rig uses to sign and pay:\n\n create generate a fresh identity into the encrypted keystore under\n TOON_CLIENT_HOME. The seed phrase is shown ONCE — back it up.\n Refuses to overwrite an existing identity without --force.\n show report the ACTIVE identity's source + derived pubkey (never the\n phrase); errors with the resolution remediation when none exists.\n import read an EXISTING phrase from stdin (never a CLI argument) and write\n it to the encrypted keystore.\n\nOptions:\n --force (create/import) replace an existing identity/keystore\n --json machine-readable output. NOTE: \\`identity create --json\\`\n DELIBERATELY emits the seed phrase in a \\`mnemonic\\`\n field — treat that output as SECRET. \\`identity show\\`\n and \\`identity import\\` never emit the phrase.\n -h, --help show this help\n\nThe keystore is encrypted with TOON_CLIENT_KEYSTORE_PASSWORD when that env var\nis set, else a default password so the identity reloads with no configuration.\nrig deliberately does NOT accept the keystore password as a CLI flag — that\nwould leak the value that decrypts your keys to shell history and \\`ps\\`.`;\n\n/** Route `rig identity <sub>`; returns the process exit code. */\nexport async function runIdentity(\n args: string[],\n deps: IdentityDeps\n): Promise<number> {\n const [sub, ...rest] = args;\n switch (sub) {\n case 'create':\n return runIdentityCreate(rest, deps);\n case 'show':\n return runIdentityShow(rest, deps);\n case 'import':\n return runIdentityImport(rest, deps);\n case 'help':\n case '--help':\n case '-h':\n deps.io.out(IDENTITY_USAGE);\n return 0;\n case undefined:\n deps.io.err('rig identity needs a subcommand: create | show | import');\n deps.io.err(IDENTITY_USAGE);\n return 2;\n default:\n deps.io.err(`unknown rig identity subcommand: ${sub}`);\n deps.io.err(IDENTITY_USAGE);\n return 2;\n }\n}\n\ninterface MintFlags {\n force: boolean;\n json: boolean;\n help: boolean;\n}\n\nfunction parseMintArgs(args: string[], verb: string): MintFlags {\n // No `--password` option on purpose: an unknown `--password` therefore\n // errors out (caught → usage exit) rather than silently accepting a secret\n // on the command line. The keystore password comes from the env var only.\n const { values, positionals } = parseArgs({\n args,\n options: {\n force: { type: 'boolean', default: false },\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 identity ${verb} takes no positional arguments`);\n }\n return {\n force: values.force ?? false,\n json: values.json ?? false,\n help: values.help ?? false,\n };\n}\n\nasync function runIdentityCreate(\n args: string[],\n deps: IdentityDeps\n): Promise<number> {\n const { io } = deps;\n let flags: MintFlags;\n try {\n flags = parseMintArgs(args, 'create');\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(IDENTITY_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(IDENTITY_USAGE);\n return 0;\n }\n\n try {\n const result = await createIdentity({\n env: deps.env,\n cwd: deps.cwd,\n force: flags.force,\n warn: (line) => io.err(line),\n ...(deps.resolveIdentityImpl\n ? { resolveIdentityImpl: deps.resolveIdentityImpl }\n : {}),\n ...(deps.loadKeyOps ? { loadKeyOps: deps.loadKeyOps } : {}),\n });\n emitCreated(io, flags.json, 'identity create', result);\n return 0;\n } catch (err) {\n return emitMintError(io, flags.json, 'identity create', err);\n }\n}\n\nasync function runIdentityImport(\n args: string[],\n deps: IdentityDeps\n): Promise<number> {\n const { io } = deps;\n let flags: MintFlags;\n try {\n flags = parseMintArgs(args, 'import');\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(IDENTITY_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(IDENTITY_USAGE);\n return 0;\n }\n\n try {\n const read = deps.readSecretLine ?? defaultReadSecretLine;\n const phrase = (\n await read(\n 'Paste your BIP-39 seed phrase (read from stdin, not the terminal ' +\n 'history): ',\n io.isInteractive\n )\n ).trim();\n if (phrase === '') {\n throw new Error(\n 'no seed phrase provided on stdin — pipe it in or type it at the ' +\n 'prompt (never pass a phrase as a CLI argument; it leaks to shell ' +\n 'history and `ps`).'\n );\n }\n const result = await importIdentity({\n env: deps.env,\n cwd: deps.cwd,\n force: flags.force,\n mnemonic: phrase,\n warn: (line) => io.err(line),\n ...(deps.resolveIdentityImpl\n ? { resolveIdentityImpl: deps.resolveIdentityImpl }\n : {}),\n ...(deps.loadKeyOps ? { loadKeyOps: deps.loadKeyOps } : {}),\n });\n // Import NEVER echoes the phrase back (unlike create) — only the pubkey.\n if (flags.json) {\n io.emitJson({\n command: 'identity import',\n imported: true,\n pubkey: result.pubkey,\n keystorePath: result.keystorePath,\n autoPassword: result.autoPassword,\n ...(result.shadowedBy ? { shadowedBy: result.shadowedBy } : {}),\n });\n } else {\n io.out(`Imported identity ${result.pubkey}`);\n io.out(` Encrypted keystore: ${result.keystorePath}`);\n }\n if (result.shadowedBy) io.err(shadowNote(result.shadowedBy));\n return 0;\n } catch (err) {\n return emitMintError(io, flags.json, 'identity import', err);\n }\n}\n\nasync function runIdentityShow(\n args: string[],\n deps: IdentityDeps\n): Promise<number> {\n const { io } = deps;\n let json = false;\n let help = false;\n try {\n const parsed = parseArgs({\n args,\n options: {\n json: { type: 'boolean', default: false },\n help: { type: 'boolean', short: 'h', default: false },\n },\n allowPositionals: false,\n });\n json = parsed.values.json ?? false;\n help = parsed.values.help ?? false;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(IDENTITY_USAGE);\n return 2;\n }\n if (help) {\n io.out(IDENTITY_USAGE);\n return 0;\n }\n\n try {\n const identity = await (deps.resolveIdentityImpl ?? resolveIdentity)({\n env: deps.env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n });\n // NEVER the phrase — source + derived pubkey only.\n if (json) {\n io.emitJson({\n command: 'identity show',\n source: identity.source,\n sourceLabel: identity.sourceLabel,\n pubkey: identity.pubkey,\n accountIndex: identity.accountIndex,\n });\n } else {\n io.out(renderIdentityLine(identity));\n io.out(` source : ${identity.source} (${identity.sourceLabel})`);\n io.out(` pubkey : ${identity.pubkey}`);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, json, 'identity show', err);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Shared emitters\n// ---------------------------------------------------------------------------\n\n/**\n * Emit a freshly created identity. `--json` is the ONE sanctioned path that\n * carries the phrase (the `mnemonic` field) — a scripting/agent need — as the\n * single stdout document; human mode prints the one-time backup banner.\n */\nexport function emitCreated(\n io: CliIo,\n json: boolean,\n command: string,\n result: CreatedIdentity\n): void {\n if (json) {\n io.emitJson({\n command,\n created: true,\n pubkey: result.pubkey,\n keystorePath: result.keystorePath,\n autoPassword: result.autoPassword,\n // DELIBERATE, documented exception to \"never print the phrase\": the\n // scripting/agent path needs the generated phrase to back it up.\n mnemonic: result.mnemonic,\n ...(result.shadowedBy ? { shadowedBy: result.shadowedBy } : {}),\n });\n io.err(\n 'rig: `--json` emitted your seed phrase in the `mnemonic` field — this ' +\n 'output is SECRET; store it safely and do not log or share it.'\n );\n } else {\n for (const line of createdIdentityBanner(result)) io.out(line);\n }\n if (result.shadowedBy) io.err(shadowNote(result.shadowedBy));\n}\n\n/** Map the mint-path errors to output; refusals get their own stable codes. */\nfunction emitMintError(\n io: CliIo,\n json: boolean,\n command: string,\n err: unknown\n): 1 {\n if (err instanceof IdentityExistsError) {\n if (json) {\n io.emitJson({\n command,\n error: 'identity_exists',\n pubkey: err.pubkey,\n detail: err.message,\n });\n }\n for (const line of err.message.split('\\n')) io.err(line);\n return 1;\n }\n if (err instanceof KeystoreFileExistsError) {\n if (json) {\n io.emitJson({\n command,\n error: 'keystore_exists',\n keystorePath: err.keystorePath,\n detail: err.message,\n });\n }\n for (const line of err.message.split('\\n')) io.err(line);\n return 1;\n }\n return emitCliError(io, json, command, err);\n}\n\n/**\n * Default secret reader: one line from stdin. When a human types the phrase at\n * a TTY, the terminal echo is SUPPRESSED — the phrase is the most sensitive\n * value this CLI handles (\"CONTROLS YOUR FUNDS\"), so it must never land in\n * cleartext on screen, scrollback, or a session recording. We write the prompt\n * to stderr ourselves, then mute readline's echo of the typed characters (like\n * a conventional password prompt). Piped, non-interactive input has no echo to\n * mask, so it is read verbatim with no prompt.\n */\nasync function defaultReadSecretLine(\n prompt: string,\n isInteractive: boolean\n): Promise<string> {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n if (isInteractive) {\n process.stderr.write(prompt);\n // Suppress echo of the typed secret. readline routes every keystroke\n // through `_writeToOutput`; replacing it with a no-op masks the input\n // while still capturing the line.\n (rl as unknown as { _writeToOutput: (s: string) => void })._writeToOutput =\n () => {\n /* mask: swallow every echoed keystroke so the phrase never prints */\n };\n }\n try {\n const answer = await rl.question('');\n // The muted Enter left the cursor on the hidden prompt line; advance it.\n if (isInteractive) process.stderr.write('\\n');\n return answer;\n } finally {\n rl.close();\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. ensures the working directory is inside a git repository — when it is\n * not, it OFFERS to `git init` for you (a TTY `[y/N]` prompt, or the\n * non-interactive `--git-init` flag), mirroring how it offers to mint an\n * identity on a cold start; a refusal keeps the old `git init` hint;\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 resolveGitAuthor,\n profileTimeoutFromEnv,\n type GitAuthor,\n} from './git-author.js';\nimport {\n addGitRemote,\n initGitRepository,\n listGitRemotes,\n readToonConfig,\n resolveRepoRoot,\n setGitAuthor,\n writeToonConfig,\n type GitRemoteInfo,\n} from './git-config.js';\nimport {\n createIdentity,\n createdIdentityBanner,\n shadowNote,\n type CreatedIdentity,\n} from './identity-cmd.js';\nimport {\n MissingIdentityError,\n resolveIdentity,\n type ResolvedIdentity,\n} 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\nIt also sets the repo's LOCAL git commit-author from your nostr identity\n(never --global) so \\`rig commit\\`/\\`git commit\\` work out of the box and every\ncommit is attributed to the signer: user.email = <npub>@nostr, user.name =\nyour kind:0 profile display name when published (read best-effort from a\nrelay, latest-wins) else the npub. Re-running refreshes the name from a\nnow-readable profile.\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\nWhen the directory is NOT inside a git repository, init does not dead-end: in\na terminal it offers to create one (\\`Initialize a git repository here?\n[y/N]\\`), and \\`--git-init\\` does it non-interactively. Likewise, when NO\nidentity resolves it offers to generate one (\\`Create a new identity now?\n[y/N]\\`), and \\`--generate-identity\\` does it non-interactively (equivalent to\n\\`rig identity create\\` — the phrase is shown once to back up). Nothing — repo\nor identity — is ever created without your yes. \\`--git-init\n--generate-identity\\` is a fully non-interactive fresh setup.\n\nOptions:\n --repo-id <id> repository id / NIP-34 d-tag (default: the existing\n toon.repoid, then the repo directory basename)\n --git-init when the cwd is not a git repo, run \\`git init\\` here\n first, then proceed (no prompt)\n --relay <url> relay to read your kind:0 profile from for the git\n author name (default: origin/toon.relay, then the\n genesis seed; skipped if none is resolvable)\n --generate-identity when no identity resolves, mint a fresh one (no prompt)\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 /** Identity generator seam (tests); defaults to the real mint. */\n createIdentityImpl?: typeof createIdentity;\n /** Git-author resolver seam (tests); defaults to the real kind:0 read. */\n resolveGitAuthorImpl?: typeof resolveGitAuthor;\n}\n\ninterface InitFlags {\n repoId?: string;\n gitInit: boolean;\n relay?: string;\n generateIdentity: boolean;\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 'git-init': { type: 'boolean', default: false },\n relay: { type: 'string' },\n 'generate-identity': { type: 'boolean', default: false },\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 gitInit: values['git-init'] ?? false,\n generateIdentity: values['generate-identity'] ?? false,\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 const relay = values.relay;\n if (relay !== undefined) {\n if (relay.trim() === '') throw new Error('--relay must not be empty');\n flags.relay = relay.trim();\n }\n return flags;\n}\n\n/** True for a WebSocket-scheme URL (the kind:0 profile read speaks only ws(s)). */\nfunction isWebSocketRelay(url: string): boolean {\n return /^wss?:\\/\\//i.test(url);\n}\n\n/**\n * Resolve the relay to read the identity's kind:0 profile from, at init time —\n * BEFORE `rig remote add origin` may have run. Precedence: `--relay` flag →\n * the `origin` remote → the deprecated `toon.relay` → the #264 genesis seed.\n * Only ws(s) URLs qualify (the read is a WebSocket REQ); returns undefined when\n * none resolves, in which case the git author falls back to the npub.\n */\nasync function resolveProfileRelay(\n flagRelay: string | undefined,\n originRelay: string | undefined,\n toonRelays: string[]\n): Promise<string | undefined> {\n const candidates = [\n flagRelay,\n originRelay,\n ...toonRelays,\n ].filter((u): u is string => u !== undefined && isWebSocketRelay(u));\n if (candidates[0] !== undefined) return candidates[0];\n // No relay anywhere: the author falls back to the npub. (There is no\n // built-in network seed since 4.0 — a node is named, never discovered.)\n return undefined;\n}\n\n/** JSON envelope emitted by `rig init --json`. */\ninterface InitJsonOutput {\n command: 'init';\n repoRoot: string;\n /** True when THIS run created the git repository (`--git-init` or a TTY yes). */\n initializedGitRepo: boolean;\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 /**\n * The repo-local git commit-author derived from the nostr identity (#302):\n * `user.name` (kind:0 display name when published, else the npub) and\n * `user.email` = `<npub>@nostr`. Always set so `rig commit` works out of the\n * box; `source` records whether the name came from the profile or the npub.\n */\n gitAuthor: { name: string; email: string; source: GitAuthor['source'] };\n /** What this run changed in git config (false = already up to date). */\n changed: { repoId: boolean; owner: boolean };\n /**\n * Present only when THIS run generated the identity (`--generate-identity`\n * or a TTY yes). Like `rig identity create --json`, it carries the seed\n * phrase in `mnemonic` for the scripted path — treat as SECRET.\n */\n generatedIdentity?: {\n mnemonic: string;\n pubkey: string;\n keystorePath: string;\n autoPassword: boolean;\n };\n}\n\n/**\n * Resolve the git worktree root; when the cwd is not inside a repo, create one\n * instead of dead-ending — but ONLY with consent (`--git-init` or an\n * interactive `[y/N]` yes), mirroring the identity generate-on-first-run flow.\n * A refusal (non-interactive, or a prompt no) throws {@link\n * NotAGitRepositoryError}, whose remediation now leads with `rig init\n * --git-init`. `git init` runs in the cwd only (never a parent).\n */\nasync function resolveOrInitGitRepo(\n deps: InitDeps,\n flags: InitFlags\n): Promise<{ repoRoot: string; initialized: boolean }> {\n const { io } = deps;\n try {\n return { repoRoot: await resolveRepoRoot(deps.cwd), initialized: false };\n } catch {\n let doInit = flags.gitInit;\n if (!doInit && io.isInteractive && !flags.json) {\n io.err('Not a git repository — rig keeps its config and objects in one.');\n doInit = await io.confirm('Initialize a git repository here? [y/N] ');\n }\n if (!doInit) throw new NotAGitRepositoryError(deps.cwd);\n\n await initGitRepository(deps.cwd);\n // git init succeeded, so this must now resolve.\n return { repoRoot: await resolveRepoRoot(deps.cwd), initialized: true };\n }\n}\n\n/**\n * Resolve the signing identity; when nothing resolves, generate one instead of\n * dead-ending — but ONLY with consent (`--generate-identity` or an interactive\n * yes). A refusal (non-interactive, or a `[y/N]` no) rethrows the original\n * {@link MissingIdentityError}, whose remediation now leads with\n * `rig identity create`.\n */\nasync function resolveOrGenerateIdentity(\n deps: InitDeps,\n flags: InitFlags\n): Promise<{ identity: ResolvedIdentity; generated?: CreatedIdentity }> {\n const { io, env } = deps;\n const resolve = deps.resolveIdentityImpl ?? resolveIdentity;\n try {\n return { identity: await resolve({ env, cwd: deps.cwd, warn: io.err }) };\n } catch (err) {\n if (!(err instanceof MissingIdentityError)) throw err;\n\n let generate = flags.generateIdentity;\n if (!generate && io.isInteractive && !flags.json) {\n io.err('No identity found — rig needs one to sign and pay.');\n generate = await io.confirm('Create a new identity now? [y/N] ');\n }\n if (!generate) throw err;\n\n const created = await (deps.createIdentityImpl ?? createIdentity)({\n env,\n cwd: deps.cwd,\n force: false,\n warn: io.err,\n ...(deps.resolveIdentityImpl\n ? { resolveIdentityImpl: deps.resolveIdentityImpl }\n : {}),\n });\n // Build the ResolvedIdentity from the fresh mint directly (rather than\n // re-resolving) so a custom-password keystore needs no env var to link.\n const identity: ResolvedIdentity = {\n mnemonic: created.mnemonic,\n accountIndex: created.accountIndex,\n source: 'keystore',\n sourceLabel: created.keystorePath,\n pubkey: created.pubkey,\n };\n return { identity, generated: created };\n }\n}\n\n/** Run `rig init`; returns the process exit code. */\nexport async function runInit(args: string[], deps: InitDeps): Promise<number> {\n const { io } = 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) Git repository — create one (consent-gated) when there is none ──\n // A cold start (`mkdir x && rig init`) is no longer a dead end: with\n // consent init runs `git init` here first (prompt, or `--git-init`).\n const { repoRoot, initialized: initializedGitRepo } =\n await resolveOrInitGitRepo(deps, flags);\n\n // ── (b) Identity chain: source + derived pubkey (never the phrase) ──────\n // A chain miss no longer dead-ends: offer or honor identity generation.\n const { identity, generated } = await resolveOrGenerateIdentity(deps, flags);\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) Git commit-author from the nostr identity (#302) ────────────────\n // On a rig repo the nostr key IS the identity: set the repo's LOCAL git\n // author (never --global) so `rig commit` (a git passthrough) stops\n // dead-ending on \"empty ident name not allowed\" and every commit is\n // attributed to the signer. user.name = the kind:0 display name when\n // published (best-effort, latest-wins), else the npub; email `<npub>@nostr`.\n // Re-running refreshes user.name from a now-readable profile.\n const profileRelay = await resolveProfileRelay(\n flags.relay,\n originRelay,\n existing.relays\n );\n const resolveAuthor = deps.resolveGitAuthorImpl ?? resolveGitAuthor;\n const gitAuthor = await resolveAuthor({\n pubkey: identity.pubkey,\n relayUrl: profileRelay,\n ...(profileTimeoutFromEnv(deps.env) !== undefined\n ? { timeoutMs: profileTimeoutFromEnv(deps.env) as number }\n : {}),\n });\n await setGitAuthor(repoRoot, {\n name: gitAuthor.name,\n email: gitAuthor.email,\n });\n\n // ── (f) Report ───────────────────────────────────────────────────────────\n if (flags.json) {\n const output: InitJsonOutput = {\n command: 'init',\n repoRoot,\n initializedGitRepo,\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 gitAuthor: {\n name: gitAuthor.name,\n email: gitAuthor.email,\n source: gitAuthor.source,\n },\n changed,\n ...(generated\n ? {\n generatedIdentity: {\n mnemonic: generated.mnemonic,\n pubkey: generated.pubkey,\n keystorePath: generated.keystorePath,\n autoPassword: generated.autoPassword,\n },\n }\n : {}),\n };\n io.emitJson(output);\n if (generated) {\n io.err(\n 'rig: `--json` emitted your new seed phrase in ' +\n '`generatedIdentity.mnemonic` — this output is SECRET; store it ' +\n 'safely and do not log or share it.'\n );\n if (generated.shadowedBy) io.err(shadowNote(generated.shadowedBy));\n }\n return 0;\n }\n\n // A freshly minted identity gets its one-time backup banner FIRST, before\n // the init report, so the phrase is the thing the user sees.\n if (generated) {\n for (const line of createdIdentityBanner(generated)) io.out(line);\n if (generated.shadowedBy) io.err(shadowNote(generated.shadowedBy));\n }\n if (initializedGitRepo) io.out(`Created a git repository at ${repoRoot}`);\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 io.out(\n `Git author: ${gitAuthor.name} <${gitAuthor.email}> ` +\n `(from ${gitAuthor.source === 'profile' ? 'nostr profile' : 'npub'})`\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 * Git commit-author from the nostr identity (#302).\n *\n * On a rig repo the nostr key IS the identity, so `rig init` sets the repo's\n * LOCAL git author fields from it — the commit author == the push signer ==\n * the nostr identity, a coherent authorship chain baked permanently into the\n * git objects that land on Arweave. Without this, `rig commit` (a git\n * passthrough, #250) dead-ends on git's \"Author identity unknown / empty ident\n * name not allowed\" for anyone who never set a global git identity.\n *\n * user.email = `<npub>@nostr` — npub is bech32, lowercase-alphanumeric, a\n * valid email local part; `@nostr` is a stable\n * non-routable marker domain.\n * user.name = the identity's kind:0 profile DISPLAY NAME when published\n * (prefer `display_name`, else `name` from the content JSON),\n * read latest-wins (highest created_at) from a resolvable relay,\n * BEST-EFFORT; falls back to the npub when there is no profile,\n * no resolvable relay, or the read fails.\n *\n * The kind:0 read reuses the tolerant NIP-01 machinery from `../remote-state`\n * (double-JSON-encoded EVENT payloads and all). It never throws and never\n * blocks init: a short timeout, and any failure falls back to the npub.\n */\n\nimport { hexToNpub } from '../npub.js';\nimport { queryRelay, type WebSocketFactory } from '../remote-state.js';\n\n/** Nostr metadata event kind (profile). */\nexport const PROFILE_KIND = 0;\n\n/** Default bounded wait for the kind:0 profile read (env-overridable). */\nexport const DEFAULT_PROFILE_TIMEOUT_MS = 3000;\n\n/** Env var overriding the kind:0 read timeout (milliseconds). */\nexport const PROFILE_TIMEOUT_ENV = 'RIG_PROFILE_TIMEOUT_MS';\n\n/** Where `user.name` came from: the nostr profile, or the npub fallback. */\nexport type GitAuthorSource = 'profile' | 'npub';\n\n/** A resolved git commit-author derived from the nostr identity. */\nexport interface GitAuthor {\n /** `user.name`: the kind:0 display name, else the npub. */\n name: string;\n /** `user.email`: `<npub>@nostr`. */\n email: string;\n /** The npub of the identity (bech32). */\n npub: string;\n source: GitAuthorSource;\n}\n\nexport interface ResolveGitAuthorOptions {\n /** Identity pubkey (64-char hex). */\n pubkey: string;\n /**\n * Relay to read the kind:0 profile from (resolved at init time). When\n * undefined or not a ws(s) URL, the profile read is skipped and the npub is\n * used — init must not depend on a relay being reachable.\n */\n relayUrl?: string | undefined;\n /** Bounded wait for the kind:0 read (default {@link DEFAULT_PROFILE_TIMEOUT_MS}). */\n timeoutMs?: number;\n /** WebSocket factory override (defaults to the global WebSocket). */\n webSocketFactory?: WebSocketFactory;\n /** Relay-query seam (tests); defaults to {@link queryRelay}. */\n queryRelayImpl?: typeof queryRelay;\n}\n\n/** True for a WebSocket-scheme URL (the only scheme the kind:0 read speaks). */\nfunction isWebSocketRelay(url: string): boolean {\n return /^wss?:\\/\\//i.test(url);\n}\n\n/**\n * Extract a display name from a kind:0 event's content JSON: prefer\n * `display_name`, then `name`. Returns undefined when neither is a non-empty\n * string or the content is not parseable — the caller then keeps the npub.\n */\nexport function displayNameFromKind0(content: string): string | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const fields = parsed as Record<string, unknown>;\n for (const key of ['display_name', 'name'] as const) {\n const value = fields[key];\n if (typeof value === 'string' && value.trim() !== '') return value.trim();\n }\n return undefined;\n}\n\n/**\n * Resolve the git commit-author for the identity `pubkey`: `<npub>@nostr` email\n * plus a `user.name` of the published kind:0 display name (latest-wins) or, on\n * any miss, the npub. Best-effort and non-throwing — a relay that is missing,\n * unreachable, slow, or serves no/garbage profile just yields the npub.\n */\nexport async function resolveGitAuthor(\n options: ResolveGitAuthorOptions\n): Promise<GitAuthor> {\n const npub = hexToNpub(options.pubkey);\n const email = `${npub}@nostr`;\n const fallback: GitAuthor = { name: npub, email, npub, source: 'npub' };\n\n const { relayUrl } = options;\n if (relayUrl === undefined || !isWebSocketRelay(relayUrl)) {\n return fallback;\n }\n\n const query = options.queryRelayImpl ?? queryRelay;\n const timeoutMs = options.timeoutMs ?? DEFAULT_PROFILE_TIMEOUT_MS;\n const factory = options.webSocketFactory ?? defaultWebSocketFactory;\n\n try {\n const events = await query(\n relayUrl,\n { kinds: [PROFILE_KIND], authors: [options.pubkey], limit: 20 },\n timeoutMs,\n factory\n );\n // Latest-wins over the whole buffer — a relay may serve a stale kind:0\n // ahead of the newest (issue #157), so never trust first-in-buffer.\n let latest: { created_at: number; content: string } | undefined;\n for (const event of events) {\n if (event.kind !== PROFILE_KIND) continue;\n if (event.pubkey !== options.pubkey) continue;\n if (!latest || event.created_at > latest.created_at) {\n latest = { created_at: event.created_at, content: event.content };\n }\n }\n if (latest) {\n const name = displayNameFromKind0(latest.content);\n if (name !== undefined) {\n return { name, email, npub, source: 'profile' };\n }\n }\n } catch {\n // Best-effort: any failure keeps the npub fallback (init never blocks).\n }\n return fallback;\n}\n\n/** Read {@link PROFILE_TIMEOUT_ENV} as a positive integer, else undefined. */\nexport function profileTimeoutFromEnv(\n env: NodeJS.ProcessEnv\n): number | undefined {\n const raw = env[PROFILE_TIMEOUT_ENV]?.trim();\n if (!raw) return undefined;\n const ms = Number.parseInt(raw, 10);\n return Number.isFinite(ms) && ms > 0 ? ms : undefined;\n}\n\nfunction defaultWebSocketFactory(url: string): ReturnType<WebSocketFactory> {\n const ctor = (\n globalThis as {\n WebSocket?: new (url: string) => ReturnType<WebSocketFactory>;\n }\n ).WebSocket;\n if (!ctor) {\n throw new Error(\n 'No global WebSocket constructor (Node >= 22 required) for the kind:0 read'\n );\n }\n return new ctor(url);\n}\n","/**\n * `rig maintainers list|add|remove <pubkey>` (#287) — manage the declared\n * maintainer set on a repo's kind:30617 announcement.\n *\n * Status authority is CONSUMER-side: rig and rig-web resolve an issue/PR's\n * state ONLY from kind:1630-1633 events signed by the repo owner ∪ its\n * declared maintainers. The owner is ALWAYS an implicit maintainer; this\n * command edits the EXPLICIT set carried by the `[\"maintainers\", …]` tag.\n *\n * list FREE relay read — print owner + declared maintainers\n * add <pubkey> PAID — republish the 30617 with <pubkey> added\n * remove <pubkey> PAID — republish the 30617 with <pubkey> removed\n *\n * add/remove republish the WHOLE announcement (a replaceable event keyed by\n * author + `d` tag), so they preserve the existing name/description and only\n * mutate the maintainers list. Because the 30617 is addressed by its author,\n * only the OWNER's republish is authoritative — running add/remove under a\n * non-owner identity writes that identity's own (irrelevant) announcement, so\n * we refuse it. The daemon has no announcement route, so this always runs the\n * embedded standalone publisher; the confirm gate matches every other paid\n * write (`--yes` skips; a non-TTY without it refuses; `--json` without `--yes`\n * is a pure estimate).\n */\n\nimport { parseArgs } from 'node:util';\nimport { parseMaintainers } from '../nip34-events.js';\nimport {\n amendRepoAnnouncement,\n conformanceEdits,\n diffAnnouncementTags,\n} from '../repo-announcement.js';\nimport { ownerToHex } from '../npub.js';\nimport { fetchRemoteState } from '../remote-state.js';\nimport {\n serializeEventReceipt,\n type GitEventResponse,\n} from '../routes.js';\nimport type { EventCommandDeps } from './events.js';\nimport { emitCliError, InvalidRelayUrlError } from './errors.js';\nimport type { IdentityReport } from './push.js';\nimport { describeAnnouncementDiff, feeLabel } from './render.js';\nimport {\n openAnnouncementRepublish,\n pickRepoCommandFlags,\n REPO_COMMAND_OPTIONS,\n resolveRepoContext,\n WS_URL_RE,\n type RepoCommandFlags,\n} from './repo-command.js';\nimport type { StandaloneContext } from './standalone-context.js';\n\nconst HEX64_RE = /^[0-9a-f]{64}$/;\n\nexport const MAINTAINERS_USAGE = `Usage: rig maintainers <list|add|remove> [<pubkey>] [options]\n\nManage a repo's declared maintainers (#287). Status authority is consumer-side:\nrig and rig-web honor an issue/PR status (kind:1630-1633) ONLY when its author\nis the repo owner or a declared maintainer. The owner is always an implicit\nmaintainer; this command edits the explicit set on the kind:30617 announcement.\n\nSubcommands:\n list show the owner + declared maintainers — FREE (relay read)\n add <pubkey> add a maintainer (npub or 64-char hex) — PAID: republishes\n the kind:30617 (permanent, non-refundable)\n remove <pubkey> remove a maintainer — PAID: republishes the kind:30617\n\nadd/remove must run under the repo OWNER's identity (only the owner's\nannouncement is authoritative).\n\nOptions:\n --repo-id <id> repository id / NIP-34 d-tag (default: git config)\n --owner <pubkey> repository owner (npub or hex; default: git config)\n --remote <name> publish/read via this configured git remote (default: origin)\n --relay <url> ad-hoc relay override (exactly one for add/remove)\n --yes skip the fee confirmation (required when not a TTY)\n --json machine-readable envelope\n -h, --help show this help`;\n\n/** Run `rig maintainers …`; returns the process exit code. */\nexport async function runMaintainers(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n switch (sub) {\n case 'list':\n return runList(rest, deps);\n case 'add':\n return runMutate('add', rest, deps);\n case 'remove':\n return runMutate('remove', rest, deps);\n case '--help':\n case '-h':\n case 'help':\n io.out(MAINTAINERS_USAGE);\n return 0;\n default:\n io.err(\n sub === undefined\n ? 'missing subcommand: rig maintainers <list|add|remove>'\n : `unknown rig maintainers subcommand: ${sub}`\n );\n io.err(MAINTAINERS_USAGE);\n return 2;\n }\n}\n\n// ---------------------------------------------------------------------------\n// list (FREE)\n// ---------------------------------------------------------------------------\n\nasync function runList(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n let flags: RepoCommandFlags;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: REPO_COMMAND_OPTIONS,\n allowPositionals: true,\n });\n if (positionals.length > 0) {\n throw new Error('rig maintainers list takes no positional arguments');\n }\n flags = pickRepoCommandFlags(values);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(MAINTAINERS_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(MAINTAINERS_USAGE);\n return 0;\n }\n\n try {\n const ctx = await resolveRepoContext(flags, deps);\n const wsRelays = ctx.relays.filter((url) => WS_URL_RE.test(url));\n if (wsRelays.length === 0) {\n throw new InvalidRelayUrlError(\n ctx.relays[0] ?? '',\n 'reads need a ws:// or wss:// relay'\n );\n }\n const remote = await fetchRemoteState({\n relayUrls: wsRelays,\n ownerPubkey: ctx.owner,\n repoId: ctx.repoId,\n ...(deps.webSocketFactory\n ? { webSocketFactory: deps.webSocketFactory }\n : {}),\n });\n const maintainers = remote.maintainers;\n if (flags.json) {\n io.emitJson({\n command: 'maintainers list',\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n announced: remote.announced,\n owner: ctx.owner,\n maintainers,\n });\n return 0;\n }\n io.out(`Repo: 30617:${ctx.owner}:${ctx.repoId}`);\n io.out(`Owner: ${ctx.owner} (implicit maintainer)`);\n if (!remote.announced) {\n io.out('No kind:30617 announcement found — owner-only authority.');\n return 0;\n }\n if (maintainers.length === 0) {\n io.out('Maintainers: (none declared — owner-only authority)');\n } else {\n io.out(`Maintainers (${maintainers.length}):`);\n for (const m of maintainers) io.out(` ${m}`);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, 'maintainers list', err);\n }\n}\n\n// ---------------------------------------------------------------------------\n// add / remove (PAID — republish the 30617 under the owner's identity)\n// ---------------------------------------------------------------------------\n\ninterface MaintJsonOutput {\n command: 'maintainers add' | 'maintainers remove';\n repoAddr: { ownerPubkey: string; repoId: string };\n identity: IdentityReport;\n executed: boolean;\n feeEstimate: string | null;\n maintainers: string[];\n /**\n * Every tag the republish adds and drops (#158) — the maintainers edit plus\n * the conformance backfill. A `--json` consumer sees exactly what the fee\n * buys, the same as the human confirmation does.\n */\n changes: { added: string[][]; removed: string[][] };\n result?: GitEventResponse;\n hint?: string;\n}\n\nasync function runMutate(\n op: 'add' | 'remove',\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const command = `maintainers ${op}` as\n | 'maintainers add'\n | 'maintainers remove';\n\n let flags: RepoCommandFlags;\n let pubkey: string;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: REPO_COMMAND_OPTIONS,\n allowPositionals: true,\n });\n flags = pickRepoCommandFlags(values);\n if (flags.help) {\n io.out(MAINTAINERS_USAGE);\n return 0;\n }\n if (positionals.length !== 1) {\n throw new Error(`expected exactly one <pubkey> to ${op}`);\n }\n pubkey = ownerToHex(positionals[0] as string).toLowerCase();\n if (!HEX64_RE.test(pubkey)) {\n throw new Error(`<pubkey> must resolve to 64-char hex (got ${JSON.stringify(positionals[0])})`);\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(MAINTAINERS_USAGE);\n return 2;\n }\n\n let standaloneCtx: StandaloneContext | undefined;\n try {\n // Every money-safety refusal a paid republish must clear — one relay, the\n // embedded publisher, owner-only, and no phantom 30617 on an unannounced\n // repo — lives in ./repo-command.ts, shared with payout and refresh.\n const opened = await openAnnouncementRepublish({\n deps,\n flags,\n what: 'change the maintainer set',\n before: 'before managing maintainers',\n });\n standaloneCtx = opened.standalone;\n if (!opened.ok) return opened.exitCode;\n const { ctx, relayUrl, identity, remote, facts } = opened;\n\n const current = remote.announceEvent\n ? parseMaintainers(remote.announceEvent.tags)\n : [];\n const currentSet = new Set(current);\n if (op === 'add' && currentSet.has(pubkey)) {\n io.err(\n `rig: ${pubkey.slice(0, 8)}… is already a maintainer — nothing to do (not published).`\n );\n return 0;\n }\n if (op === 'remove' && !currentSet.has(pubkey)) {\n io.err(\n `rig: ${pubkey.slice(0, 8)}… is not a declared maintainer — nothing to do (not published).`\n );\n return 0;\n }\n const next =\n op === 'add'\n ? [...current, pubkey]\n : current.filter((m) => m !== pubkey);\n\n // Amend rather than rebuild (#154): `maintainers` is the ONLY field this\n // command edits, so name, description, the payout pointer (rig#92) and\n // every tag rig does not model — another client's role tags, `clone`,\n // `blossoms`, … — ride along verbatim instead of being wiped by the\n // replaceable write. Passing a field here would rewrite it.\n // #158: an owner-initiated republish also BACKFILLS the conformance tags\n // (`relays`, `web`, and the `euc` when the announcement has none), so a\n // repo announced before #158 becomes conformant without a special step.\n const event = amendRepoAnnouncement(remote.announceEvent, {\n repoId: ctx.repoId,\n maintainers: next,\n ...conformanceEdits(remote.announceEvent, facts),\n });\n const diff = diffAnnouncementTags(remote.announceEvent, event);\n const changes = { added: diff.added, removed: diff.removed };\n const fee = (\n await opened.standalone.publisher.getFeeRates()\n ).eventFee.toString();\n const action = `kind:30617 maintainers ${op} ${pubkey.slice(0, 8)}…`;\n\n // ── Confirm gate ────────────────────────────────────────────────────────\n if (!flags.json) {\n io.out(`Republish ${action}`);\n io.out(`Repo: 30617:${ctx.owner}:${ctx.repoId}`);\n io.out(`Maintainers after: ${next.length === 0 ? '(none)' : next.join(', ')}`);\n if (!diff.unchanged) {\n io.out('Tags changed:');\n for (const line of describeAnnouncementDiff(diff)) io.out(line);\n }\n io.out(`Fee: ${feeLabel(fee)}. Writes are permanent and non-refundable.`);\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n identity,\n executed: false,\n feeEstimate: fee,\n maintainers: next,\n changes,\n hint: 'estimate only — re-run with --yes to publish (permanent, non-refundable)',\n } satisfies MaintJsonOutput);\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n 'refusing to spend channel funds without confirmation in a non-interactive ' +\n 'session — re-run with --yes (or use --json for an estimate)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Proceed with paid republish (${feeLabel(fee)})? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was published.');\n return 1;\n }\n }\n\n // ── Execute ───────────────────────────────────────────────────────────────\n const receipt = await opened.standalone.publisher.publishEvent(event, [\n relayUrl,\n ]);\n const result = serializeEventReceipt(event.kind, receipt);\n\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n identity,\n executed: true,\n feeEstimate: fee,\n maintainers: next,\n changes,\n result,\n } satisfies MaintJsonOutput);\n } else {\n io.out(\n `Published ${action}: ${result.eventId} paid ${result.feePaid} base units`\n );\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, command, err);\n } finally {\n if (standaloneCtx) {\n try {\n await standaloneCtx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n","/**\n * `rig refresh` (#158) — republish a repo's kind:30617 announcement with NO\n * field edit, purely to bring its NIP-34 conformance tags up to date.\n *\n * `rig push` announces a repo ONCE and never republishes: a replaceable-event\n * republish costs an event fee, and an owner must never be charged a fee they\n * did not confirm. So a repo announced before #158 — or one whose relay or\n * viewer URL has since changed — has no way to gain `relays`, `web` and the\n * `euc` fork-identity tag except through an owner-initiated republish.\n * `rig maintainers` and `rig payout` backfill them as a side effect of the\n * edit they are already making; this command is the same backfill with\n * nothing else attached.\n *\n * It is deliberately the smallest possible command:\n *\n * - owner-only, for the same reason `rig maintainers add` is — only the\n * owner's announcement is authoritative, so a non-owner republish would\n * write that identity's own (ignored) announcement and pay for it;\n * - it shows the exact tags it would add, change or drop before the confirm\n * gate, so the owner sees what the fee buys;\n * - it publishes NOTHING and pays NOTHING when the republish would change\n * no tag — a no-op refresh is free, and says so;\n * - same `--json` contract as `rig maintainers`: without `--yes` the\n * envelope is a pure estimate and nothing is published.\n *\n * Every announcement it builds goes through `amendRepoAnnouncement`, so tags\n * rig does not model ride along verbatim (#154).\n */\n\nimport { parseArgs } from 'node:util';\nimport {\n amendRepoAnnouncement,\n conformanceEdits,\n diffAnnouncementTags,\n} from '../repo-announcement.js';\nimport { serializeEventReceipt, type GitEventResponse } from '../routes.js';\nimport type { EventCommandDeps } from './events.js';\nimport { emitCliError } from './errors.js';\nimport type { IdentityReport } from './push.js';\nimport { describeAnnouncementDiff, feeLabel } from './render.js';\nimport {\n openAnnouncementRepublish,\n pickRepoCommandFlags,\n REPO_COMMAND_OPTIONS,\n type RepoCommandFlags,\n} from './repo-command.js';\nimport type { StandaloneContext } from './standalone-context.js';\n\nexport const REFRESH_USAGE = `Usage: rig refresh [options]\n\nRepublish this repo's kind:30617 announcement with no field edit, refreshing\nits NIP-34 conformance tags (#158) so other clients can find and group it:\n\n relays the relay this repo publishes to — where its issues,\n patches and state live. Added to the relays the\n announcement already lists; none are removed\n web the repo's rig-web viewer URL, added alongside any\n viewer URL another client already announced\n r <sha> euc the earliest unique commit: the repo's fork identity.\n Written only if the announcement has none — once declared it\n never changes, so forks stay grouped\n\nEvery other tag rides along verbatim, including tags written by other NIP-34\nclients. rig never writes a \\`clone\\` tag (it has no git-clonable URL) and never\nremoves one.\n\nPAID: republishing the kind:30617 costs one event fee (permanent,\nnon-refundable). Nothing is published and nothing is paid when no tag would\nchange. Must run under the repo OWNER's identity — only the owner's\nannouncement is authoritative.\n\nOptions:\n --repo-id <id> repository id / NIP-34 d-tag (default: git config)\n --owner <pubkey> repository owner (npub or hex; default: git config)\n --remote <name> publish/read via this configured git remote (default: origin)\n --relay <url> ad-hoc relay override (exactly one)\n --yes skip the fee confirmation (required when not a TTY)\n --json machine-readable envelope\n -h, --help show this help`;\n\ninterface RefreshJsonOutput {\n command: 'refresh';\n repoAddr: { ownerPubkey: string; repoId: string };\n identity: IdentityReport;\n executed: boolean;\n /** `null` when nothing would change — a no-op refresh costs nothing. */\n feeEstimate: string | null;\n /** Tags the republish would add, and tags it would drop. */\n changes: { added: string[][]; removed: string[][] };\n result?: GitEventResponse;\n hint?: string;\n}\n\n/** Run `rig refresh …`; returns the process exit code. */\nexport async function runRefresh(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n\n let flags: RepoCommandFlags;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: REPO_COMMAND_OPTIONS,\n allowPositionals: true,\n });\n flags = pickRepoCommandFlags(values);\n if (flags.help) {\n io.out(REFRESH_USAGE);\n return 0;\n }\n if (positionals.length > 0) {\n throw new Error('rig refresh takes no positional arguments');\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(REFRESH_USAGE);\n return 2;\n }\n\n let standaloneCtx: StandaloneContext | undefined;\n try {\n const opened = await openAnnouncementRepublish({\n deps,\n flags,\n what: 'refresh the announcement',\n before: 'before refreshing it',\n });\n standaloneCtx = opened.standalone;\n if (!opened.ok) return opened.exitCode;\n const { ctx, relayUrl, identity, remote, facts } = opened;\n\n // No field edit: the ONLY changes are the conformance backfill (#158).\n const event = amendRepoAnnouncement(remote.announceEvent, {\n repoId: ctx.repoId,\n ...conformanceEdits(remote.announceEvent, facts),\n });\n const diff = diffAnnouncementTags(remote.announceEvent, event);\n\n // Nothing to change → nothing to publish, and nothing to pay for.\n if (diff.unchanged) {\n const changes = { added: diff.added, removed: diff.removed };\n if (flags.json) {\n io.emitJson({\n command: 'refresh',\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n identity,\n executed: false,\n feeEstimate: null,\n changes,\n hint: 'announcement is already up to date — nothing published, nothing paid',\n } satisfies RefreshJsonOutput);\n return 0;\n }\n io.out(\n `Announcement 30617:${ctx.owner}:${ctx.repoId} is already up to date — ` +\n 'nothing to do (not published, nothing paid).'\n );\n return 0;\n }\n\n const fee = (\n await opened.standalone.publisher.getFeeRates()\n ).eventFee.toString();\n const changes = { added: diff.added, removed: diff.removed };\n\n // ── Confirm gate ────────────────────────────────────────────────────────\n if (!flags.json) {\n io.out('Republish kind:30617 announcement (refresh)');\n io.out(`Repo: 30617:${ctx.owner}:${ctx.repoId}`);\n io.out('Tags changed:');\n for (const line of describeAnnouncementDiff(diff)) io.out(line);\n io.out(`Fee: ${feeLabel(fee)}. Writes are permanent and non-refundable.`);\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n command: 'refresh',\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n identity,\n executed: false,\n feeEstimate: fee,\n changes,\n hint: 'estimate only — re-run with --yes to publish (permanent, non-refundable)',\n } satisfies RefreshJsonOutput);\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n 'refusing to spend channel funds without confirmation in a non-interactive ' +\n 'session — re-run with --yes (or use --json for an estimate)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Proceed with paid republish (${feeLabel(fee)})? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was published.');\n return 1;\n }\n }\n\n // ── Execute ─────────────────────────────────────────────────────────────\n const receipt = await opened.standalone.publisher.publishEvent(event, [\n relayUrl,\n ]);\n const result = serializeEventReceipt(event.kind, receipt);\n\n if (flags.json) {\n io.emitJson({\n command: 'refresh',\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n identity,\n executed: true,\n feeEstimate: fee,\n changes,\n result,\n } satisfies RefreshJsonOutput);\n } else {\n io.out(\n `Published kind:30617 refresh: ${result.eventId} paid ${result.feePaid} base units`\n );\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, 'refresh', err);\n } finally {\n if (standaloneCtx) {\n try {\n await standaloneCtx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n","/**\n * `rig name` — ArNS naming verbs (#367): buy / set / status, owned and paid\n * by the rig mnemonic's Solana key.\n *\n * ArNS is the missing NAMING layer over everything Rig serves from Arweave.\n * Since ar.io's Solana migration, ArNS names are owned and managed by Solana\n * wallets, and `@ar.io/sdk` is Solana-native with prices denominated in mARIO.\n * The rig identity ALREADY has the required key: `@toon-protocol/client`\n * derives a Solana Ed25519 keypair from the same mnemonic that pays for pushes\n * (`m/44'/501'/{index}'/0'`, SLIP-0010 — see packages/client/src/keys) and\n * `rig fund --chain solana` funds it. So the same phrase can own ArNS names and\n * pay for them, with ZERO new key material or config.\n *\n * PAYMENT MODEL — the load-bearing distinction (see {@link MARIO_PAYMENT_NOTE}):\n * `rig name buy` spends **mARIO from the identity's Solana wallet, charged\n * on-chain by the ar.io registry program**. It does NOT move value through the\n * TOON ILP payment channels that `rig push` uses — a name purchase is a\n * Solana-settled registry transaction, not a pay-to-write relay claim.\n *\n * Same discipline as every paid rig command: estimate → confirm → execute,\n * strict `--json` contract, `--yes` for non-TTY. `buy` and `set` are the\n * money/state-moving paths (gated); `status` is FREE (a registry read, like\n * `rig balance`).\n *\n * DEPENDENCY HYGIENE (#367 open question, decided): `@ar.io/sdk` is an\n * OPTIONAL, lazily-imported dependency — it is `import()`ed only inside the\n * command path (via the {@link LoadArns} seam), so the base `rig` install stays\n * lean and runs that never touch names never pay its startup cost. When it is\n * not installed, the command fails with a clean, actionable error\n * ({@link ArnsSdkUnavailableError}) instead of a module-resolution stack trace.\n *\n * SDK WIRING (#376): `@ar.io/sdk` >= 4.0.3 is Solana-native. There is no\n * `SolanaSigner` class and no AO registry process id, and `ARIO.init()` builds\n * NO default rpc — the caller constructs everything from `@solana/kit`:\n * `createSolanaRpc` (all calls), plus `createSolanaRpcSubscriptions` and a\n * `createKeyPairSignerFromBytes` signer for writes only. The FREE read path\n * (`status`) therefore runs signerless ({@link LoadArnsOptions.mode}) — reads\n * being free is the rig discipline everywhere else. This surface is pinned by\n * a live smoke test against the published SDK\n * (`src/__integration__/arns-live-read.integration.test.ts`), because both\n * #376 bugs came from coding against an API no released version exports.\n *\n * DEVNET (#367 open question, revised by #376): post-migration, registry\n * selection is a Solana CLUSTER, not an AO process id — `--network\n * mainnet|devnet` (or `RIG_ARIO_NETWORK`) picks the cluster (devnet applies\n * the SDK's `DEVNET_PROGRAM_IDS`); ar.io deploys nothing on Solana's testnet\n * cluster, so `testnet` is rejected up front. `--process-id <id>` (or\n * `RIG_ARIO_PROCESS_ID`) overrides the ArNS registry program id outright.\n * Defaults to mainnet.\n */\n\nimport { deriveNostrKeyFromMnemonic } from '../standalone/nostr-identity.js';\nimport { randomUUID } from 'node:crypto';\nimport { parseArgs } from 'node:util';\nimport { formatUnits } from './balance.js';\nimport { emitCliError } from './errors.js';\nimport { resolveEffectiveNetwork } from './fund.js';\nimport { resolveIdentity } from './identity.js';\nimport type { CliIo } from './output.js';\nimport type { IdentityReport } from './push.js';\nimport { defaultLoadStandalone } from './push.js';\nimport type { StoreJobRequest, StoreJobResponse } from '../publisher.js';\nimport type { LoadStandalone } from './standalone-context.js';\nimport { renderIdentityLine } from './render.js';\n\n// ---------------------------------------------------------------------------\n// mARIO / ARIO\n// ---------------------------------------------------------------------------\n\n/**\n * $ARIO token decimals: 1 ARIO = 1_000_000 mARIO (mARIO is the base unit\n * `@ar.io/sdk` quotes in). Used only to render a human ARIO figure alongside\n * the exact mARIO amount — the mARIO integer is always the authoritative value.\n */\nexport const ARIO_DECIMALS = 6;\n\n/** Render a mARIO base-unit amount as `<mARIO> mARIO (~<ARIO> ARIO)`. */\nexport function renderMario(mario: bigint): string {\n return `${mario.toString()} mARIO (~${formatUnits(mario.toString(), ARIO_DECIMALS)} ARIO)`;\n}\n\n/**\n * THE load-bearing note (#367): a name purchase spends mARIO on Solana via the\n * ar.io registry program — NOT through TOON ILP payment channels. Exported so\n * the buy human output, the `--json` hint, and the tests all pin one string.\n */\nexport const MARIO_PAYMENT_NOTE =\n \"Payment is mARIO from this identity's Solana wallet, charged on-chain by \" +\n 'the ar.io registry program — NOT through TOON ILP payment channels. Fund ' +\n 'this wallet with `rig fund --chain solana` (or send $ARIO to the Solana ' +\n 'address above).';\n\n/**\n * The brokered (\"buyfor\") counterpart of {@link MARIO_PAYMENT_NOTE}: with\n * `--via <dvm>`, a store DVM pays the mARIO name price from ITS wallet by\n * executing the kind:5095 ArNS-buy job — this identity never holds $ARIO.\n * The client still OWNS the name from inception, because the job carries the\n * processId of an ANT this identity spawned and owns (`ANT.spawn` costs only\n * dust SOL). Exported so the buy output and the tests pin one string.\n */\nexport const DVM_PAYMENT_NOTE =\n 'Brokered buy (--via): the DVM pays the mARIO name price from ITS Solana ' +\n 'wallet via the kind:5095 job; this wallet needs only dust SOL to spawn ' +\n 'the ANT it owns. On the paid path the job fee is enforced by the ' +\n 'connector payment proxy in front of the DVM; when --via targets the DVM ' +\n 'backend directly the job payment is STUBBED (dev/e2e only). The ArNS ' +\n 'purchase itself is real either way, and the name is owned by YOUR ANT ' +\n 'from inception.';\n\n// ---------------------------------------------------------------------------\n// The ar.io SDK seam (lazily imported; tests inject a stub — NEVER the live net)\n// ---------------------------------------------------------------------------\n\n/** A name registration kind: a time-boxed lease or a one-time permabuy. */\nexport type NameType = 'lease' | 'permabuy';\n\n/**\n * The Solana clusters ar.io deploys its programs to; mainnet is the default.\n * (No `testnet`: ar.io has no deployment on Solana's testnet cluster — #376.)\n */\nexport type ArioNetwork = 'mainnet' | 'devnet';\n\n/** One name's current registry record (the free `status` read). */\nexport interface ArnsRecordView {\n /**\n * ANT (Arweave Name Token) process id that owns/serves the name, or `null`\n * when no ANT is attached. The registry's all-ones placeholder\n * ({@link ARNS_NULL_PROCESS_ID}) is normalized to `null` at this seam — a\n * non-null value here always means a real ANT (#79).\n */\n processId: string | null;\n /** `lease` or `permabuy`, when known. */\n type: NameType | null;\n /** Lease/registration start (ms epoch), when known. */\n startTimestamp?: number;\n /** Lease expiry (ms epoch); absent/undefined for a permabuy. */\n endTimestamp?: number;\n /** Included undername slots (ArNS ships 10 per name). */\n undernameLimit?: number;\n}\n\n/** One ANT record target (base name or an undername). */\nexport interface AntRecordTarget {\n /** Arweave txId the record points at (typically a path manifest). */\n transactionId: string;\n /** Record TTL in seconds (gateway cache hint). */\n ttlSeconds: number;\n}\n\n/**\n * A handle on one name's ANT process — used by `set` (write) and `status`\n * (read). The base name record is conventionally the `@` undername.\n */\nexport interface ArnsAnt {\n /** All current record targets, keyed by undername (`@` = the base name). */\n getRecords(): Promise<Record<string, AntRecordTarget>>;\n /** Point the base name at an Arweave txId. */\n setBaseNameRecord(args: {\n transactionId: string;\n ttlSeconds: number;\n }): Promise<{ id: string }>;\n /** Point an undername (`<sub>_<name>`) at an Arweave txId. */\n setUndernameRecord(args: {\n undername: string;\n transactionId: string;\n ttlSeconds: number;\n }): Promise<{ id: string }>;\n}\n\n/**\n * The slice of `@ar.io/sdk` `rig name` uses, behind our own seam so tests can\n * inject a stub and NEVER reach the live ar.io registry (the hard safety rule:\n * no real $ARIO is ever spent, no real registry call is ever made in code we\n * run or in tests).\n */\nexport interface ArnsSdk {\n /** Quote the mARIO cost of an intent (here always `Buy-Name`). */\n getTokenCost(args: {\n intent: 'Buy-Name';\n name: string;\n type: NameType;\n years?: number;\n }): Promise<bigint>;\n /**\n * Register (buy) a name. `processId`, when supplied, binds the purchase to\n * an ANT the caller already owns (both `rig name` buy paths spawn their\n * own ANT first and pass its id here — #79 — so the name is never\n * registered against the registry's placeholder). Returns the settling\n * registry transaction id and, when the SDK echoes it back, the ANT\n * process id actually bound; absent that echo, callers trust the\n * `processId` they requested.\n */\n buyRecord(args: {\n name: string;\n type: NameType;\n years?: number;\n processId?: string;\n }): Promise<{ id: string; processId?: string }>;\n /**\n * Spawn a fresh ANT owned by THIS identity's Solana key (`ANT.spawn` —\n * mints the MPL Core asset + initializes the ario-ant PDAs; costs only\n * rent/fee dust, no $ARIO). The returned `processId` (the asset pubkey) is\n * what a brokered `--via` buy hands the DVM so the client owns the bought\n * name from inception. Write mode only — a signerless SDK must throw.\n */\n spawnAnt(args: {\n name: string;\n }): Promise<{ processId: string; signature: string }>;\n /**\n * Build (do NOT send) a partially-signed ANT record-set transaction for\n * the gas-station path (toon-meta#163): feePayer = the DVM's advertised\n * gas wallet, lifetime = the quoted blockhash, caller = THIS identity's\n * Solana key, which partial-signs. Returns the base64 wire transaction\n * ready for a kind:5096 execute job. Write mode only.\n */\n buildSetRecordTransaction(args: {\n antProcessId: string;\n /** `@` for the base name. */\n undername: string;\n transactionId: string;\n ttlSeconds: number;\n feePayer: string;\n recentBlockhash: string;\n }): Promise<string>;\n /** Read a name's current registry record (free). */\n getArNSRecord(args: { name: string }): Promise<ArnsRecordView | null>;\n /** Bind an ANT handle for a name's process id (for `set` / `status`). */\n ant(processId: string): Promise<ArnsAnt>;\n}\n\n/** What the {@link LoadArns} seam needs to build a targeted SDK. */\nexport interface LoadArnsOptions {\n /**\n * Which capability the caller needs (#376). `read` builds a SIGNERLESS,\n * read-only client — the FREE lookups (`status`, cost quotes) must never\n * require write plumbing. `write` additionally derives a `@solana/kit`\n * signer from `solanaSecretKey` and wires the rpc-subscriptions client that\n * transaction confirmation requires.\n */\n mode: 'read' | 'write';\n /**\n * 64-byte Ed25519 Solana keypair (secretKey ‖ publicKey) that owns and\n * pays — consumed only in `write` mode (readers never touch it).\n */\n solanaSecretKey: Uint8Array;\n /** Solana public key (base58) — for the signer + human messaging. */\n solanaPublicKey: string;\n /** Which cluster's ar.io deployment to target. */\n network: ArioNetwork;\n /** Explicit ArNS registry program id override (wins over `network`). */\n processId?: string;\n}\n\n/** Build a network-targeted {@link ArnsSdk} (tests inject a stub). */\nexport type LoadArns = (options: LoadArnsOptions) => Promise<ArnsSdk>;\n\n/**\n * The Solana System Program id (32 base58 \"1\"s) — the ar.io registry writes\n * this into a record's `processId` when no ANT is actually attached. It is a\n * real, valid program id (not a null the SDK invented), so a buy that never\n * attaches an ANT looks superficially like it worked unless this exact\n * string is checked for wherever an ANT process id is accepted or reported\n * (#79 — a direct buy silently registering against this placeholder is the\n * bug this constant exists to make impossible to miss).\n */\nexport const ARNS_NULL_PROCESS_ID = '11111111111111111111111111111111';\n\n/**\n * Normalize an ANT process id: the real id, or `null` when no ANT is attached\n * (absent, or the registry's all-ones placeholder). Every command that accepts\n * or reports an ANT process id goes through this, so the placeholder can never\n * be mistaken for a working attachment (#79 AC4).\n */\nfunction antProcessIdOf(id: string | null | undefined): string | null {\n if (id === null || id === undefined || id === ARNS_NULL_PROCESS_ID) {\n return null;\n }\n return id;\n}\n\n/**\n * The minimum `@ar.io/sdk` release `rig name` is built against: the first\n * Solana-native surface verified to expose the clients the default loader\n * wires (`ARIO.init`/`ANT.init` over a caller-built `@solana/kit` rpc, signer\n * optional). Mirrored by the `optionalDependencies` pin in package.json.\n */\nexport const MIN_ARIO_SDK_VERSION = '4.0.3';\n\n/**\n * An optional module (`@ar.io/sdk`, or its `@solana/kit` companion) is not\n * installed. Optional-dependency by design (#367): surface a clean,\n * actionable message instead of a module-resolution stack trace. Distinct\n * from {@link ArnsSdkIncompatibleError} — \"not installed\" and \"installed but\n * the wrong API surface\" need different remediations (#376).\n */\nexport class ArnsSdkUnavailableError extends Error {\n constructor(cause?: unknown, module = '@ar.io/sdk') {\n super(\n `\\`rig name\\` needs the optional \\`${module}\\` dependency, which is not ` +\n 'installed. It is intentionally NOT a base `rig` dependency (keeps the ' +\n 'install lean). Add it to use ArNS naming:\\n' +\n ` npm i @ar.io/sdk@^${MIN_ARIO_SDK_VERSION} # or: pnpm add @ar.io/sdk@^${MIN_ARIO_SDK_VERSION}\\n` +\n '(`@solana/kit` installs alongside it) then re-run your `rig name` ' +\n 'command.' +\n (cause instanceof Error ? `\\n(underlying error: ${cause.message})` : '')\n );\n this.name = 'ArnsSdkUnavailableError';\n }\n}\n\n/**\n * `@ar.io/sdk` (or `@solana/kit`) IS installed but exposes an API surface\n * `rig name` cannot drive — e.g. a pre-Solana-migration build. Kept separate\n * from {@link ArnsSdkUnavailableError} so users are never told to install a\n * package they already have (#376: the old message sent users chasing an\n * upgrade that did not exist).\n */\nexport class ArnsSdkIncompatibleError extends Error {\n constructor(detail: string) {\n super(\n `the installed @ar.io/sdk is incompatible with \\`rig name\\`: ${detail}.\\n` +\n `\\`rig name\\` requires @ar.io/sdk >= ${MIN_ARIO_SDK_VERSION} (the ` +\n 'Solana-native release driven via a `@solana/kit` rpc + signer). ' +\n 'Upgrade with:\\n' +\n ' npm i @ar.io/sdk@latest # or: pnpm add @ar.io/sdk@latest'\n );\n this.name = 'ArnsSdkIncompatibleError';\n }\n}\n\n/** Public Solana RPC endpoints (fallbacks when the SDK exports none). */\nconst SOLANA_MAINNET_RPC_URL = 'https://api.mainnet-beta.solana.com';\nconst SOLANA_DEVNET_RPC_URL = 'https://api.devnet.solana.com';\n\n/**\n * The untyped shape of the pieces of `@ar.io/sdk` the default loader reaches\n * for (verified against the published 4.0.3). Kept local (the package is\n * optional and its types are not a build dep) and cast through `unknown` —\n * never `any`, so eslint's no-explicit-any holds.\n */\ninterface RawArioModule {\n ARIO?: {\n init?: (config: unknown) => RawArioInstance;\n };\n ANT?: {\n /** 4.x resolves the ANT program from the asset, hence async. */\n init?: (config: unknown) => Promise<RawAntInstance>;\n /** 4.x Solana `ANT.spawn` — mints the MPL Core asset (write only). */\n spawn?: (\n params: unknown\n ) => Promise<{ processId: string; signature: string }>;\n };\n DEFAULT_SOLANA_RPC_URL?: string;\n MAINNET_RPC_URL?: string;\n DEVNET_RPC_URL?: string;\n /** Devnet (staging) program-id overrides — required off mainnet. */\n DEVNET_PROGRAM_IDS?: {\n core?: string;\n gar?: string;\n arns?: string;\n ant?: string;\n };\n /** Root-exported PDA helper: (mint, undername, antProgramId?) → [pda]. */\n getAntRecordPDA?: (\n mint: unknown,\n undername: string,\n programId?: unknown\n ) => Promise<readonly unknown[]>;\n}\ninterface RawArioInstance {\n getTokenCost: (args: unknown) => Promise<unknown>;\n /** Present only on the writeable (signer-built) client. */\n buyRecord?: (args: unknown) => Promise<unknown>;\n getArNSRecord: (args: unknown) => Promise<unknown>;\n}\ninterface RawAntInstance {\n getRecords: () => Promise<\n Record<string, { transactionId: string; ttlSeconds: number }>\n >;\n /** Present only on the writeable (signer-built) client. */\n setBaseNameRecord?: (args: unknown) => Promise<{ id: string }>;\n setUndernameRecord?: (args: unknown) => Promise<{ id: string }>;\n}\n/** The three `@solana/kit` factories the Solana-native SDK is driven with. */\ninterface RawSolanaKitModule {\n createSolanaRpc?: (url: string) => unknown;\n createSolanaRpcSubscriptions?: (url: string) => unknown;\n createKeyPairSignerFromBytes?: (bytes: Uint8Array) => Promise<unknown>;\n // ── extras the gas-station tx builder uses (all loose-typed on purpose:\n // the optional module's types are not a build dep) ──\n createKeyPairFromBytes?: (bytes: Uint8Array) => Promise<unknown>;\n createNoopSigner?: (addr: unknown) => unknown;\n address?: (s: string) => unknown;\n blockhash?: (s: string) => unknown;\n createTransactionMessage?: (o: { version: number }) => unknown;\n setTransactionMessageFeePayer?: (a: unknown, m: unknown) => unknown;\n setTransactionMessageLifetimeUsingBlockhash?: (\n l: unknown,\n m: unknown\n ) => unknown;\n appendTransactionMessageInstructions?: (ix: unknown[], m: unknown) => unknown;\n compileTransaction?: (m: unknown) => unknown;\n partiallySignTransaction?: (kps: unknown[], tx: unknown) => Promise<unknown>;\n getBase64EncodedWireTransaction?: (tx: unknown) => string;\n}\n/** The `@ar.io/solana-contracts/ant` slice the record-set builder uses. */\ninterface RawAntContractsModule {\n getSetRecordInstructionAsync?: (\n input: Record<string, unknown>,\n config?: { programAddress?: unknown }\n ) => Promise<unknown>;\n}\n\n/**\n * Default {@link LoadArns}: lazily `import('@ar.io/sdk')` + `@solana/kit` and\n * adapt them to our seam. Specifiers are stored in `string`-typed variables so\n * TypeScript does not try to resolve the optional modules at build time; a\n * missing package surfaces as {@link ArnsSdkUnavailableError}, a wrong API\n * surface as {@link ArnsSdkIncompatibleError}.\n *\n * THE #376 LESSON, load-bearing: the SDK provides NO defaults. Bare\n * `ARIO.init()` throws and `ARIO.init({})` produces a client whose every read\n * fails — the caller must build the rpc (`createSolanaRpc`) explicitly, and\n * for writes also `rpcSubscriptions` + a `createKeyPairSignerFromBytes`\n * signer. Read mode constructs NO signer at all, so free lookups need zero\n * key material at the SDK layer.\n *\n * NOTE: no test drives this adapter against the live registry except the\n * env-gated smoke test (`__integration__/arns-live-read.integration.test.ts`,\n * FREE reads only) — every money-moving path runs ONLY against injected\n * stubs, and no real $ARIO is ever spent by code we run.\n */\nexport const defaultLoadArns: LoadArns = async (options) => {\n // Cast to `string` (not a literal type) so TypeScript does not try to\n // resolve the OPTIONAL modules at build time — a missing package must\n // surface as a clean runtime error, not a compile failure.\n const sdkSpecifier = '@ar.io/sdk' as string;\n let mod: RawArioModule;\n try {\n mod = (await import(sdkSpecifier)) as unknown as RawArioModule;\n } catch (err) {\n throw new ArnsSdkUnavailableError(err);\n }\n // `@solana/kit` carries the rpc/signer factories the Solana-native SDK is\n // driven with. It is a dependency of `@ar.io/sdk` AND declared in rig's own\n // optionalDependencies so strict (pnpm-style) layouts resolve it here too.\n const kitSpecifier = '@solana/kit' as string;\n let kit: RawSolanaKitModule;\n try {\n kit = (await import(kitSpecifier)) as unknown as RawSolanaKitModule;\n } catch (err) {\n throw new ArnsSdkUnavailableError(err, '@solana/kit');\n }\n\n const arioInit = mod.ARIO?.init;\n const antInit = mod.ANT?.init;\n if (!arioInit || !antInit) {\n throw new ArnsSdkIncompatibleError('it exposes no ARIO.init / ANT.init');\n }\n const {\n createSolanaRpc,\n createSolanaRpcSubscriptions,\n createKeyPairSignerFromBytes,\n } = kit;\n if (\n !createSolanaRpc ||\n !createSolanaRpcSubscriptions ||\n !createKeyPairSignerFromBytes\n ) {\n throw new ArnsSdkIncompatibleError(\n 'the resolved @solana/kit exposes no createSolanaRpc / ' +\n 'createSolanaRpcSubscriptions / createKeyPairSignerFromBytes'\n );\n }\n\n // Cluster targeting: rpc endpoint + (off mainnet) program-id overrides.\n const rpcUrl =\n options.network === 'devnet'\n ? (mod.DEVNET_RPC_URL ?? SOLANA_DEVNET_RPC_URL)\n : (mod.DEFAULT_SOLANA_RPC_URL ??\n mod.MAINNET_RPC_URL ??\n SOLANA_MAINNET_RPC_URL);\n const devnetIds =\n options.network === 'devnet' ? mod.DEVNET_PROGRAM_IDS : undefined;\n if (options.network === 'devnet' && devnetIds === undefined) {\n throw new ArnsSdkIncompatibleError(\n 'it exposes no DEVNET_PROGRAM_IDS — devnet targeting needs the ' +\n \"SDK's staging program ids\"\n );\n }\n const antProgramId = devnetIds?.ant;\n const programOverrides = {\n ...(devnetIds?.core !== undefined ? { coreProgramId: devnetIds.core } : {}),\n ...(devnetIds?.gar !== undefined ? { garProgramId: devnetIds.gar } : {}),\n ...(devnetIds?.arns !== undefined ? { arnsProgramId: devnetIds.arns } : {}),\n ...(antProgramId !== undefined ? { antProgramId } : {}),\n // --process-id / RIG_ARIO_PROCESS_ID: explicit ArNS registry program\n // override (wins over the cluster default).\n ...(options.processId !== undefined\n ? { arnsProgramId: options.processId }\n : {}),\n };\n\n // Build the transport(s) explicitly — see the #376 lesson above. Write mode\n // alone derives the signer (from the identity's 64-byte Ed25519 keypair)\n // and the ws subscriptions client that transaction confirmation needs.\n const rpc = createSolanaRpc(rpcUrl);\n const writeExtras =\n options.mode === 'write'\n ? {\n signer: await createKeyPairSignerFromBytes(options.solanaSecretKey),\n rpcSubscriptions: createSolanaRpcSubscriptions(\n rpcUrl.replace(/^http/, 'ws')\n ),\n }\n : {};\n const ario = arioInit({ rpc, ...writeExtras, ...programOverrides });\n\n return {\n getTokenCost: async (args) => BigInt(String(await ario.getTokenCost(args))),\n buyRecord: async (args) => {\n if (typeof ario.buyRecord !== 'function') {\n throw new ArnsSdkIncompatibleError(\n 'the signed ARIO client exposes no buyRecord'\n );\n }\n return (await ario.buyRecord(args)) as { id: string; processId?: string };\n },\n spawnAnt: async (args) => {\n const spawn = mod.ANT?.spawn;\n if (typeof spawn !== 'function') {\n throw new ArnsSdkIncompatibleError('it exposes no ANT.spawn');\n }\n if (options.mode !== 'write') {\n // Mirrors the SDK's own contract: spawning signs a transaction, so a\n // signerless (read) client must never attempt it.\n throw new ArnsSdkIncompatibleError(\n 'ANT.spawn requires the write-mode SDK (a signer) — this client ' +\n 'was built signerless'\n );\n }\n const result = await spawn({\n rpc,\n ...writeExtras,\n state: { name: args.name },\n ...(antProgramId !== undefined ? { antProgramId } : {}),\n });\n return { processId: result.processId, signature: result.signature };\n },\n buildSetRecordTransaction: async (args) => {\n if (options.mode !== 'write') {\n throw new ArnsSdkIncompatibleError(\n 'buildSetRecordTransaction requires the write-mode SDK (a client ' +\n 'partial-signature) — this client was built signerless'\n );\n }\n const contractsSpecifier = '@ar.io/solana-contracts/ant' as string;\n let contracts: RawAntContractsModule;\n try {\n contracts = (await import(\n contractsSpecifier\n )) as unknown as RawAntContractsModule;\n } catch (err) {\n throw new ArnsSdkUnavailableError(err, '@ar.io/solana-contracts');\n }\n const getSetRecordInstructionAsync =\n contracts.getSetRecordInstructionAsync;\n const getAntRecordPDA = mod.getAntRecordPDA;\n const {\n createKeyPairFromBytes,\n createNoopSigner,\n address: toAddr,\n blockhash: toBlockhash,\n createTransactionMessage,\n setTransactionMessageFeePayer,\n setTransactionMessageLifetimeUsingBlockhash,\n appendTransactionMessageInstructions,\n compileTransaction,\n partiallySignTransaction,\n getBase64EncodedWireTransaction,\n } = kit;\n if (\n !getSetRecordInstructionAsync ||\n !getAntRecordPDA ||\n !createKeyPairFromBytes ||\n !createNoopSigner ||\n !toAddr ||\n !toBlockhash ||\n !createTransactionMessage ||\n !setTransactionMessageFeePayer ||\n !setTransactionMessageLifetimeUsingBlockhash ||\n !appendTransactionMessageInstructions ||\n !compileTransaction ||\n !partiallySignTransaction ||\n !getBase64EncodedWireTransaction\n ) {\n throw new ArnsSdkIncompatibleError(\n 'the installed @ar.io/sdk / @ar.io/solana-contracts / @solana/kit ' +\n 'do not expose the record-set transaction builder surface'\n );\n }\n\n const asset = toAddr(args.antProcessId);\n const antProgram =\n antProgramId !== undefined ? toAddr(antProgramId) : undefined;\n const [recordPda] = await getAntRecordPDA(\n asset,\n args.undername,\n antProgram\n );\n // The client is the record CALLER (authority) — a noop signer here so\n // the compiled account meta is marked signer; the real signature comes\n // from partiallySignTransaction below. The DVM's gas wallet is ONLY\n // the fee payer.\n const ix = await getSetRecordInstructionAsync(\n {\n asset,\n record: recordPda,\n caller: createNoopSigner(toAddr(options.solanaPublicKey)),\n undername: args.undername,\n target: args.transactionId,\n targetProtocol: 0,\n ttlSeconds: args.ttlSeconds,\n priority: null,\n recordOwner: null,\n },\n antProgram !== undefined ? { programAddress: antProgram } : undefined\n );\n\n let message = createTransactionMessage({ version: 0 });\n message = setTransactionMessageFeePayer(toAddr(args.feePayer), message);\n message = setTransactionMessageLifetimeUsingBlockhash(\n {\n blockhash: toBlockhash(args.recentBlockhash),\n lastValidBlockHeight: 0n,\n },\n message\n );\n message = appendTransactionMessageInstructions([ix], message);\n\n const keyPair = await createKeyPairFromBytes(options.solanaSecretKey);\n const signed = await partiallySignTransaction(\n [keyPair],\n compileTransaction(message)\n );\n return getBase64EncodedWireTransaction(signed);\n },\n getArNSRecord: async (args) => {\n // 4.x throws on an unregistered name; our seam reports `null` so\n // `status` can render \"available\" instead of an error.\n let raw: {\n processId?: string;\n type?: NameType;\n startTimestamp?: number;\n endTimestamp?: number;\n undernameLimit?: number;\n };\n try {\n raw = (await ario.getArNSRecord(args)) as typeof raw;\n } catch (err) {\n if (err instanceof Error && /not found/i.test(err.message)) return null;\n throw err;\n }\n // Solana-native records carry cluster unix timestamps in SECONDS; the\n // seam contract (and the human expiry render) is ms epoch.\n return {\n // #79 AC4: the registry writes the all-ones placeholder when no ANT\n // is attached. The seam contract is \"a process id or null\", so the\n // placeholder is normalized to null right here — every caller then\n // sees \"no ANT\" instead of a valid-looking System Program address.\n processId: antProcessIdOf(raw.processId),\n type: raw.type ?? null,\n ...(raw.startTimestamp !== undefined\n ? { startTimestamp: raw.startTimestamp * 1000 }\n : {}),\n ...(raw.endTimestamp !== undefined\n ? { endTimestamp: raw.endTimestamp * 1000 }\n : {}),\n ...(raw.undernameLimit !== undefined\n ? { undernameLimit: raw.undernameLimit }\n : {}),\n };\n },\n ant: async (pid) => {\n const ant = await antInit({\n processId: pid,\n rpc,\n ...writeExtras,\n ...(antProgramId !== undefined ? { antProgramId } : {}),\n });\n return {\n getRecords: async () => {\n // Pin the seam shape: 4.x records carry extra fields (index,\n // targetProtocol, …) that must not leak into the `--json` contract.\n const records = await ant.getRecords();\n const targets: Record<string, AntRecordTarget> = {};\n for (const [undername, record] of Object.entries(records)) {\n targets[undername] = {\n transactionId: record.transactionId,\n ttlSeconds: record.ttlSeconds,\n };\n }\n return targets;\n },\n setBaseNameRecord: async (a) => {\n if (typeof ant.setBaseNameRecord !== 'function') {\n throw new ArnsSdkIncompatibleError(\n 'the signed ANT client exposes no setBaseNameRecord'\n );\n }\n return ant.setBaseNameRecord(a);\n },\n setUndernameRecord: async (a) => {\n if (typeof ant.setUndernameRecord !== 'function') {\n throw new ArnsSdkIncompatibleError(\n 'the signed ANT client exposes no setUndernameRecord'\n );\n }\n return ant.setUndernameRecord(a);\n },\n };\n },\n };\n};\n\n// ---------------------------------------------------------------------------\n// The brokered-buy DVM job seam (#buyfor)\n// ---------------------------------------------------------------------------\n\n/**\n * The NIP-90 job kind for a brokered ArNS name purchase — mirrors the store\n * repo's `ARNS_BUY_KIND` (the DVM registers this next to its kind:5094\n * Arweave storage job).\n */\nexport const ARNS_BUY_JOB_KIND = 5095;\n\n/**\n * Paid transport for one NIP-90 job to a store node's DVM (#101).\n *\n * This is {@link Publisher.submitStoreJob} narrowed to a function, so the two\n * job seams below depend on the capability rather than on a whole publisher.\n */\nexport type SubmitStoreJob = (\n request: StoreJobRequest\n) => Promise<StoreJobResponse>;\n\n/** One brokered buy job, ready to submit to a DVM. */\nexport interface DvmBuyJobRequest {\n /**\n * The store node's ILP destination that `--via` resolved. Carried for error\n * messages only — the paid transport is {@link DvmBuyJobRequest.submit},\n * which is already bound to this destination.\n */\n destination: string;\n name: string;\n type: NameType;\n /** Lease years; null for a permabuy. */\n years: number | null;\n /** The CLIENT's freshly-spawned ANT (asset pubkey) — the owner-to-be. */\n processId: string;\n /**\n * Paid transport to that node's DVM. The job event is signed by the\n * publisher's own identity, exactly as a kind:5094 store write is, so no\n * key material travels through this seam.\n */\n submit: SubmitStoreJob;\n}\n\n/** What the DVM reports back for an executed buy job. */\nexport interface DvmBuyJobReceipt {\n /** Registry transaction signature of the DVM-paid buy. */\n registryTxId: string;\n /** The mARIO the DVM quoted/paid, when reported. */\n quotedMario: string | null;\n /** The permissionless `syncAttributes` reconcile tx, when it succeeded. */\n syncAttributesTxId: string | null;\n}\n\n/** Submit one kind:5095 job (tests inject a stub — NEVER the live net). */\nexport type SubmitDvmBuyJob = (\n request: DvmBuyJobRequest\n) => Promise<DvmBuyJobReceipt>;\n\n/** A DVM refused or failed a brokered buy job. */\nexport class DvmBuyJobError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'DvmBuyJobError';\n }\n}\n\n/**\n * Default {@link SubmitDvmBuyJob}: carry the kind:5095 job to the store node's\n * DVM over the PAID path (#101).\n *\n * This used to `fetch(${viaUrl}/store)` directly. No connector serves `/store`\n * and none should: the store sits behind the connector's payment termination,\n * so a publicly reachable one would be an anonymous free gateway to a paid\n * handler — exactly the failure ADR 0020 exists to close. The job now travels\n * as a kind:5094 store write does, inside a paid ILP packet with `/store` as\n * the envelope target beneath the route's handler path.\n *\n * The job's `param` tags are unchanged, so the handler sees the identical\n * event either way.\n */\nexport const defaultSubmitDvmBuyJob: SubmitDvmBuyJob = async (request) => {\n let answer;\n try {\n answer = await request.submit({\n kind: ARNS_BUY_JOB_KIND,\n params: [\n ['name', request.name],\n ['type', request.type],\n ...(request.years !== null\n ? ([['years', String(request.years)]] as [string, string][])\n : []),\n ['processId', request.processId],\n ],\n });\n } catch (err) {\n throw new DvmBuyJobError(\n `could not reach the DVM at ${request.destination}: ` +\n `${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n if (!answer.accept) {\n throw new DvmBuyJobError(\n `the DVM at ${request.destination} rejected the kind:${ARNS_BUY_JOB_KIND} ` +\n `buy job (HTTP ${answer.status}${answer.code ? `, ${answer.code}` : ''})` +\n `${answer.message ? `: ${answer.message}` : ''}`\n );\n }\n const registryTxId = answer.result?.['registryTxId'];\n if (typeof registryTxId !== 'string' || registryTxId.length === 0) {\n throw new DvmBuyJobError(\n `the DVM accepted the job but returned no registryTxId — response: ` +\n JSON.stringify(answer.result ?? null)\n );\n }\n const quotedMario = answer.result?.['quotedMario'];\n const syncAttributesTxId = answer.result?.['syncAttributesTxId'];\n return {\n registryTxId,\n quotedMario: typeof quotedMario === 'string' ? quotedMario : null,\n syncAttributesTxId:\n typeof syncAttributesTxId === 'string' ? syncAttributesTxId : null,\n };\n};\n\n// ---------------------------------------------------------------------------\n// The gas-station job seam (kind:5096 — toon-meta#163)\n// ---------------------------------------------------------------------------\n\n/** The NIP-90 job kind for a gas-station (fee-payer-as-a-service) job. */\nexport const GAS_STATION_JOB_KIND = 5096;\n\n/** A kind:5096 quote — the merged quote/blockhash deadline contract. */\nexport interface GasStationQuote {\n quoteId: string;\n /** The DVM's advertised fee-payer address — set as the tx feePayer. */\n feePayer: string;\n /** The delta cap the DVM will enforce (lamports, base-10 string). */\n maxLamports: string;\n /** Build + partial-sign against exactly this blockhash. */\n recentBlockhash: string;\n /** ms epoch — submit before this or re-quote. */\n expiresAt: number;\n}\n\n/** A landed kind:5096 execute result. */\nexport interface GasStationExecuteResult {\n signature: string;\n slot: string | null;\n feeLamportsActual: string | null;\n replayed?: boolean;\n}\n\n/** The DVM refused or failed a gas-station job (machine-readable reason). */\nexport class GasStationJobError extends Error {\n constructor(\n public readonly reason: string,\n message: string\n ) {\n super(message);\n this.name = 'GasStationJobError';\n }\n}\n\n/** kind:5096 client seam (tests inject a stub — NEVER the live net). */\nexport interface GasStationClient {\n quote(args: {\n /** Store node's ILP destination, for error messages. */\n destination: string;\n /** Optional draft wire tx for an accurate (rent-aware) maxLamports. */\n transaction?: string;\n /** Paid transport to that node's DVM. */\n submit: SubmitStoreJob;\n }): Promise<GasStationQuote>;\n execute(args: {\n destination: string;\n transaction: string;\n quoteId: string;\n idempotencyKey: string;\n submit: SubmitStoreJob;\n }): Promise<GasStationExecuteResult>;\n}\n\n/**\n * Carry one kind:5096 job to the DVM over the PAID path (#101).\n *\n * Same change as the buy job above, and for the same reason: `/store` is an\n * envelope target beneath the route's handler, not a public URL path.\n */\nasync function submitGasStationJob(\n destination: string,\n params: [string, string][],\n submit: SubmitStoreJob\n): Promise<Record<string, unknown>> {\n let answer;\n try {\n answer = await submit({ kind: GAS_STATION_JOB_KIND, params });\n } catch (err) {\n throw new GasStationJobError(\n 'unreachable',\n `could not reach the DVM at ${destination}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n if (!answer.accept || !answer.result) {\n throw new GasStationJobError(\n String(answer.code ?? 'rejected'),\n `the DVM at ${destination} rejected the kind:${GAS_STATION_JOB_KIND} job (HTTP ${answer.status}${answer.code ? `, ${answer.code}` : ''})${answer.message ? `: ${answer.message}` : ''}`\n );\n }\n const result = answer.result;\n if (result['status'] === 'failed') {\n throw new GasStationJobError(\n String(result['reason'] ?? 'failed'),\n `gas-station job failed: ${String(result['reason'] ?? 'unknown')} — ${String(result['detail'] ?? '')}`\n );\n }\n return result;\n}\n\n/**\n * Default {@link GasStationClient}: signed kind:5096 events POSTed to the\n * DVM's payment-oblivious `/store` backend — the identical HTTP request the\n * connector payment proxy replays on the paid path (RouteTermination).\n */\nexport const defaultGasStationClient: GasStationClient = {\n quote: async (args) => {\n const result = await submitGasStationJob(\n args.destination,\n [\n ['phase', 'quote'],\n ...(args.transaction !== undefined\n ? ([['transaction', args.transaction]] as [string, string][])\n : []),\n ],\n args.submit\n );\n const { quoteId, feePayer, maxLamports, recentBlockhash, expiresAt } =\n result as Partial<GasStationQuote>;\n if (\n typeof quoteId !== 'string' ||\n typeof feePayer !== 'string' ||\n typeof maxLamports !== 'string' ||\n typeof recentBlockhash !== 'string' ||\n typeof expiresAt !== 'number'\n ) {\n throw new GasStationJobError(\n 'bad_response',\n `the DVM quote is missing fields: ${JSON.stringify(result)}`\n );\n }\n return { quoteId, feePayer, maxLamports, recentBlockhash, expiresAt };\n },\n execute: async (args) => {\n const result = await submitGasStationJob(\n args.destination,\n [\n ['phase', 'execute'],\n ['transaction', args.transaction],\n ['quoteId', args.quoteId],\n ['idempotencyKey', args.idempotencyKey],\n ],\n args.submit\n );\n const signature = result['signature'];\n if (typeof signature !== 'string' || signature.length === 0) {\n throw new GasStationJobError(\n 'bad_response',\n `the DVM execute result carries no signature: ${JSON.stringify(result)}`\n );\n }\n return {\n signature,\n slot: typeof result['slot'] === 'string' ? result['slot'] : null,\n feeLamportsActual:\n typeof result['feeLamportsActual'] === 'string'\n ? result['feeLamportsActual']\n : null,\n ...(result['replayed'] === true ? { replayed: true } : {}),\n };\n },\n};\n\n// ---------------------------------------------------------------------------\n// Deps + usage\n// ---------------------------------------------------------------------------\n\n/** What `rig name` needs from the command environment. */\nexport interface NameDeps {\n io: CliIo;\n env: NodeJS.ProcessEnv;\n /** Working directory (project-local `.env` walk for the identity). */\n cwd: string;\n /** ar.io SDK loader seam; defaults to the lazy `@ar.io/sdk` import. */\n loadArns?: LoadArns;\n /** kind:5095 job submitter seam; defaults to the paid ILP submission. */\n submitDvmBuyJob?: SubmitDvmBuyJob;\n /** kind:5096 gas-station client seam; defaults to the paid ILP submission. */\n gasStation?: GasStationClient;\n /**\n * Standalone-session factory for the `--via` paid path (#101); defaults to\n * `rig push`'s. Tests inject a fake so no session is ever opened and no\n * packet is ever paid for.\n */\n loadStandalone?: LoadStandalone;\n /**\n * TOON-network resolution seam for the default `--via` DVM (defaults to\n * `rig fund`'s {@link resolveEffectiveNetwork}; tests inject). The devnet\n * DVM is only defaulted when the TOON side ALSO resolves to devnet.\n */\n resolveToonNetwork?: typeof resolveEffectiveNetwork;\n}\n\n/**\n * The deployed devnet store DVM — defaulted as `--via` for buy/set when BOTH\n * the ArNS `--network` and the TOON network resolve to devnet and the user\n * neither named a DVM (`--via`/`RIG_ARNS_DVM_DESTINATION`) nor opted out\n * (`--direct`).\n */\nexport const DEVNET_DVM_DESTINATION = 'g.toon.ario';\n\n/**\n * @deprecated `--via` names an ILP destination, not an HTTP endpoint (#101).\n * Kept as an alias so an importer of the old name still compiles; it now holds\n * the same destination as {@link DEVNET_DVM_DESTINATION}.\n */\nexport const DEVNET_DVM_URL = DEVNET_DVM_DESTINATION;\n\nexport const NAME_USAGE = `Usage: rig name <buy|set|status> <name> [options]\n\nArNS naming for Arweave-served artifacts. A name registered on the ar.io\nregistry resolves at every ar.io gateway (https://<name>.<gateway>/), pointing\nat whatever Arweave txId its ANT record targets (10 undernames included).\n\nNames are OWNED and PAID FOR by this rig identity's Solana key — the same\nmnemonic that pays for pushes (derived at m/44'/501'/0'/0'). Fund it with\n\\`rig fund --chain solana\\`. Purchases spend mARIO on Solana via the ar.io\nregistry program — NOT through TOON ILP payment channels.\n\nCommands:\n name buy <name> [--years n | --permabuy] [--via <destination>]\n quote (mARIO) → confirm → register. The spawned ANT is\n owned by this identity's Solana key. Default: 1-year\n lease. PAID — spends mARIO from the Solana wallet.\n With --via: BROKERED — this identity spawns and owns\n the ANT (dust SOL only), then a store DVM executes the\n kind:5095 buy job and pays the mARIO from ITS wallet;\n the name is owned by your ANT from inception.\n name set <name> <txId> [--undername <sub>] [--ttl <seconds>] [--via <destination>]\n point the name (or an undername) at an Arweave txId\n (typically a deployed path manifest). Signs an ANT\n record update with the Solana key. With --via: the\n gas-station path (kind:5096) — you author and\n partial-sign, the DVM co-signs as fee payer and pays\n the lamports; needs ZERO SOL in this wallet.\n <txId> may instead be given via --tx-id <id> — use\n that instead of the positional when the txId leads\n with '-' or '_' (Arweave txids are base64url). For a\n leading '-' write --tx-id=<id> (the '=' form), since\n \"--tx-id -XYZ...\" is itself ambiguous to the parser.\n name status <name> FREE: registry record (lease/permabuy, expiry), ANT\n process id, current target txId(s), TTL, undernames.\n\nOptions:\n --years <n> lease length in years (buy; default 1; mutually\n exclusive with --permabuy)\n --permabuy permanent registration instead of a lease (buy)\n --undername <sub> target the undername <sub>_<name> instead of the base\n name (set)\n --ttl <seconds> record TTL in seconds (set; default 3600)\n --tx-id <id> set only: the Arweave txId to point at, as an\n explicit option instead of the positional (mutually\n exclusive with the positional <txId>). For a value\n leading with '-' use --tx-id=<id>.\n --network <net> cluster: mainnet | devnet (default mainnet; or\n RIG_ARIO_NETWORK). ar.io has no Solana-testnet\n deployment. Non-mainnet gateway resolution is\n unverified.\n --process-id <id> explicit ArNS registry program id — a Solana program\n address (overrides --network; or RIG_ARIO_PROCESS_ID)\n --via <destination> broker buy/set through a store node's DVM, naming its\n ILP DESTINATION (or RIG_ARNS_DVM_DESTINATION), e.g.\n --via ${DEVNET_DVM_DESTINATION}. The DVM pays the mARIO;\n you own the name via your spawned ANT.\n The job travels as a PAID packet, exactly as a git-object\n store write does — the store sits behind the connector's\n payment termination, so there is no unpaid endpoint to\n aim at. That node's ingress, route price and payment\n channel are all discovered from its own announce, so the\n destination is the only thing you supply.\n Costs one store-route packet per job (two for set:\n quote + execute).\n DEVNET DEFAULT: with --network devnet and the TOON\n network on devnet too, buy/set default to the deployed\n devnet store DVM (${DEVNET_DVM_DESTINATION})\n unless --direct opts out.\n --direct force the direct wallet-paid path: never default (or\n read RIG_ARNS_DVM_DESTINATION as) a --via DVM. Mutually\n exclusive with an explicit --via.\n --yes skip the confirmation (required when not a TTY) for\n buy/set\n --json machine-readable envelope; for buy/set without --yes it\n is a pure estimate (nothing is bought or written)\n -h, --help show this help`;\n\n// ---------------------------------------------------------------------------\n// Shared setup: identity → Solana key → SDK\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_TTL_SECONDS = 3600;\nconst DEFAULT_LEASE_YEARS = 1;\nconst NETWORKS: readonly ArioNetwork[] = ['mainnet', 'devnet'];\n\n/** Resolved wallet context shared by every `rig name` action. */\ninterface NameContext {\n identity: IdentityReport;\n solanaAddress: string;\n network: ArioNetwork;\n processId: string | undefined;\n sdk: ArnsSdk;\n /** Nostr secret key of the identity — signs brokered kind:5095 jobs. */\n nostrSecretKey: Uint8Array;\n}\n\n/**\n * Resolve the rig identity, derive its Solana key (the owner/payer), and build\n * the (stub-injected in tests) ArNS SDK targeted at the chosen registry.\n * `mode` decides whether the SDK gets write plumbing: every FREE lookup —\n * `status`, the buy quote, the set preview — runs `read` (signerless, #376);\n * `buy`/`set` escalate to `write` only at execute time, after the confirm\n * gate.\n */\n/**\n * Open a paid session against the store node `--via` names, and hand back its\n * job seam plus the teardown the caller must run (#101).\n *\n * `storeDestination` is the whole configuration this needs. From it, the\n * machinery `rig push` already uses discovers that node's BTP ingress from its\n * own kind:10032 announce, opens (or resumes) a payment channel against its\n * settlement address, and reads its route price to floor the claim — the same\n * store leg #98 built, pointed somewhere chosen per invocation.\n *\n * ⚠️ The caller owns the returned `stop`. A session left open holds the\n * identity lock and an started embedded client.\n */\nasync function openStoreJobSession(\n deps: NameDeps,\n destination: string\n): Promise<{ submit: SubmitStoreJob; stop: () => Promise<void> }> {\n const ctx = await (deps.loadStandalone ?? defaultLoadStandalone)({\n env: deps.env,\n cwd: deps.cwd,\n warn: (line) => deps.io.err(line),\n storeDestination: destination,\n });\n const submitStoreJob = ctx.publisher.submitStoreJob;\n if (!submitStoreJob) {\n await ctx.stop();\n throw new Error(\n 'the active publisher cannot submit a store job (submitStoreJob ' +\n 'unavailable) — `rig name --via` requires the standalone publisher'\n );\n }\n return {\n submit: (request) => submitStoreJob.call(ctx.publisher, request),\n stop: () => ctx.stop(),\n };\n}\n\nasync function resolveNameContext(\n deps: NameDeps,\n network: ArioNetwork,\n processId: string | undefined,\n mode: 'read' | 'write'\n): Promise<NameContext> {\n const { io, env } = deps;\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 — the same lazy load\n // `rig fund`/`rig balance` use to derive the multi-chain identity.\n const client = await import('@toon-protocol/client');\n const derived = client.deriveFullIdentity(resolved.mnemonic, {\n accountIndex: resolved.accountIndex,\n scheme: 'legacy',\n });\n const solanaAddress = derived.solana.publicKey;\n if (!solanaAddress) {\n throw new Error(\n 'no Solana key could be derived for this identity — ArNS names are ' +\n \"owned by the Solana key (m/44'/501'/0'/0'). Ensure the optional \" +\n 'Solana derivation deps are installed.'\n );\n }\n const sdk = await (deps.loadArns ?? defaultLoadArns)({\n mode,\n solanaSecretKey: derived.solana.secretKey,\n solanaPublicKey: solanaAddress,\n network,\n ...(processId !== undefined ? { processId } : {}),\n });\n const nostrSecretKey = deriveNostrKeyFromMnemonic(\n resolved.mnemonic,\n resolved.accountIndex\n ).secretKey;\n return { identity, solanaAddress, network, processId, sdk, nostrSecretKey };\n}\n\n// ---------------------------------------------------------------------------\n// Parsed flags\n// ---------------------------------------------------------------------------\n\ninterface NameFlags {\n years?: number;\n permabuy: boolean;\n undername?: string;\n ttl: number;\n network: ArioNetwork;\n processId?: string;\n /** Brokered buy: the DVM endpoint to submit the kind:5095 job to. */\n via?: string;\n /**\n * Opt out of the devnet default `--via` DVM: force the direct wallet-paid\n * path even when both networks resolve to devnet.\n */\n direct: boolean;\n /**\n * `set` only: the Arweave txId as an explicit option, so it never has to\n * sit in the hyphen-ambiguous positional slot — Arweave txids are\n * base64url and roughly 1 in 32 lead with `-` or `_`, which Node's\n * `parseArgs` (strict by default) misreads as an unknown flag (#399).\n */\n txId?: string;\n yes: boolean;\n json: boolean;\n}\n\nfunction parseNameFlags(\n args: string[],\n env: NodeJS.ProcessEnv\n): {\n positionals: string[];\n flags: NameFlags;\n} {\n const { values, positionals } = parseArgs({\n args,\n allowPositionals: true,\n options: {\n years: { type: 'string' },\n permabuy: { type: 'boolean', default: false },\n undername: { type: 'string' },\n ttl: { type: 'string' },\n network: { type: 'string' },\n 'process-id': { type: 'string' },\n via: { type: 'string' },\n direct: { type: 'boolean', default: false },\n 'tx-id': { 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 return {\n positionals: ['--help'],\n flags: {\n permabuy: false,\n ttl: 0,\n network: 'mainnet',\n direct: false,\n yes: false,\n json: false,\n },\n };\n }\n\n let years: number | undefined;\n if (values.years !== undefined) {\n years = Number(values.years);\n if (!Number.isInteger(years) || years <= 0) {\n throw new Error(\n `--years must be a positive integer, got ${JSON.stringify(values.years)}`\n );\n }\n }\n if (years !== undefined && values.permabuy) {\n throw new Error('--years and --permabuy are mutually exclusive');\n }\n\n let ttl = DEFAULT_TTL_SECONDS;\n if (values.ttl !== undefined) {\n ttl = Number(values.ttl);\n if (!Number.isInteger(ttl) || ttl <= 0) {\n throw new Error(\n `--ttl must be a positive integer number of seconds, got ${JSON.stringify(values.ttl)}`\n );\n }\n }\n\n const networkRaw = values.network ?? env['RIG_ARIO_NETWORK'] ?? 'mainnet';\n if (!NETWORKS.includes(networkRaw as ArioNetwork)) {\n throw new Error(\n `--network must be one of ${NETWORKS.join(' | ')}, got ${JSON.stringify(networkRaw)}`\n );\n }\n const processId = values['process-id'] ?? env['RIG_ARIO_PROCESS_ID'];\n\n if (values.direct && values.via !== undefined) {\n throw new Error(\n '--direct and --via are mutually exclusive: --direct forces the ' +\n 'wallet-paid path, --via brokers through a DVM'\n );\n }\n // --direct beats the ambient env var too (explicit opt-out).\n // `RIG_ARNS_DVM_URL` is the pre-#101 spelling, still read so an existing\n // environment keeps working, but it now carries a destination.\n const viaRaw = values.direct\n ? undefined\n : (values.via ??\n env['RIG_ARNS_DVM_DESTINATION'] ??\n env['RIG_ARNS_DVM_URL']);\n let via: string | undefined;\n if (viaRaw !== undefined) {\n // #101: `--via` names an ILP DESTINATION, not an HTTP endpoint. The store\n // sits behind the connector's payment termination and no connector serves\n // a public `/store`, so a URL here is a leftover from the broken direct\n // path rather than a usable value — reject it with the fix rather than\n // letting it fail later as an unroutable address.\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(viaRaw)) {\n throw new Error(\n `--via names an ILP destination, not a URL (got ${JSON.stringify(viaRaw)}). ` +\n `Brokered ArNS jobs travel as paid packets to a store node, e.g. ` +\n `--via ${DEVNET_DVM_DESTINATION}. The node's endpoint, price and ` +\n `payment channel are discovered from its own announce.`\n );\n }\n if (!/^g\\.[a-z0-9]+(\\.[a-z0-9-]+)*$/i.test(viaRaw)) {\n throw new Error(\n `--via must be an ILP destination like ${DEVNET_DVM_DESTINATION}, ` +\n `got ${JSON.stringify(viaRaw)}`\n );\n }\n via = viaRaw;\n }\n\n return {\n positionals,\n flags: {\n ...(years !== undefined ? { years } : {}),\n permabuy: values.permabuy ?? false,\n ...(values.undername !== undefined\n ? { undername: values.undername }\n : {}),\n ttl,\n network: networkRaw as ArioNetwork,\n ...(processId !== undefined ? { processId } : {}),\n ...(via !== undefined ? { via } : {}),\n direct: values.direct ?? false,\n ...(values['tx-id'] !== undefined ? { txId: values['tx-id'] } : {}),\n yes: values.yes ?? false,\n json: values.json ?? false,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// buy\n// ---------------------------------------------------------------------------\n\ninterface NameBuyJson {\n command: 'name';\n action: 'buy';\n name: string;\n type: NameType;\n years: number | null;\n network: ArioNetwork;\n processId: string | null;\n /** Brokered buy: the DVM endpoint the kind:5095 job goes to (else null). */\n via: string | null;\n identity: IdentityReport;\n solanaAddress: string;\n /** The mARIO quote (base units, string) + a human ARIO figure. */\n quote: { mARIO: string; ARIO: string };\n /** How the purchase settles — always Solana/registry, never ILP. */\n payment: string;\n executed: boolean;\n hint?: string;\n /**\n * The ANT this identity spawned and owns (execute only) — both the\n * brokered and direct paths spawn one (#79).\n */\n spawn?: { processId: string; signature: string };\n result?: {\n registryTxId: string;\n antProcessId: string | null;\n /** Brokered buy: the DVM's permissionless trait reconcile tx, if any. */\n syncAttributesTxId?: string | null;\n /** Brokered buy: the mARIO the DVM reported paying, if any. */\n dvmQuotedMario?: string | null;\n };\n}\n\nasync function runBuy(\n name: string,\n flags: NameFlags,\n deps: NameDeps\n): Promise<number> {\n const { io } = deps;\n const type: NameType = flags.permabuy ? 'permabuy' : 'lease';\n const years = type === 'lease' ? (flags.years ?? DEFAULT_LEASE_YEARS) : null;\n\n // Signerless context: the quote is a FREE read (#376); write plumbing is\n // built only after the confirm gate, right before money moves.\n const ctx = await resolveNameContext(\n deps,\n flags.network,\n flags.processId,\n 'read'\n );\n\n // ── Estimate (quote the mARIO cost) ──────────────────────────────────────\n const mario = await ctx.sdk.getTokenCost({\n intent: 'Buy-Name',\n name,\n type,\n ...(years !== null ? { years } : {}),\n });\n const quote = {\n mARIO: mario.toString(),\n ARIO: formatUnits(mario.toString(), ARIO_DECIMALS),\n };\n\n const via = flags.via ?? null;\n const paymentNote = via === null ? MARIO_PAYMENT_NOTE : DVM_PAYMENT_NOTE;\n\n const buildJson = (\n executed: boolean,\n extra: Partial<NameBuyJson> = {}\n ): NameBuyJson => ({\n command: 'name',\n action: 'buy',\n name,\n type,\n years,\n network: ctx.network,\n processId: ctx.processId ?? null,\n via,\n identity: ctx.identity,\n solanaAddress: ctx.solanaAddress,\n quote,\n payment: paymentNote,\n executed,\n ...extra,\n });\n\n // ── Human estimate table ─────────────────────────────────────────────────\n if (!flags.json) {\n io.out(\n `Buy ArNS name \"${name}\" — ${type}` +\n (years !== null ? ` (${years} year${years === 1 ? '' : 's'})` : '') +\n ` on ${ctx.network}` +\n (via !== null ? ` — brokered via DVM ${via}` : '')\n );\n io.out(\n via === null\n ? ` Cost: ${renderMario(mario)}`\n : ` Name cost (paid by the DVM): ${renderMario(mario)}`\n );\n io.out(` Solana wallet: ${ctx.solanaAddress}`);\n io.out(` ${paymentNote}`);\n io.out(renderIdentityLine(ctx.identity));\n }\n\n // ── Confirm gate ─────────────────────────────────────────────────────────\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson(\n buildJson(false, {\n hint:\n via === null\n ? 'estimate only — re-run with --yes to buy (spends mARIO on Solana, non-refundable)'\n : 'estimate only — re-run with --yes to spawn your ANT and submit the kind:5095 buy job to the DVM',\n })\n );\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n via === null\n ? 'refusing to spend mARIO without confirmation in a non-interactive ' +\n 'session — re-run with --yes (or use --json for a pure estimate)'\n : 'refusing to spawn an ANT and submit a paid DVM job without ' +\n 'confirmation in a non-interactive session — re-run with --yes ' +\n '(or use --json for a pure estimate)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n via === null\n ? `Proceed — buy \"${name}\" for ${renderMario(mario)} from your Solana wallet? [y/N] `\n : `Proceed — spawn your ANT and have the DVM at ${via} buy \"${name}\" ` +\n `for ${renderMario(mario)} from ITS wallet? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was bought or paid.');\n return 1;\n }\n }\n\n // ── Execute — build the signed SDK (write mode) only now, confirmed ──────\n const signed = await resolveNameContext(\n deps,\n flags.network,\n flags.processId,\n 'write'\n );\n\n if (via !== null) {\n // ── Brokered (\"buyfor\"): spawn OUR ANT, then the DVM buys for it ───────\n // 1. ANT.spawn with this identity's Solana key — the client owns the ANT\n // (and therefore the name, from inception). Costs dust SOL, no $ARIO.\n const spawn = await signed.sdk.spawnAnt({ name });\n if (!flags.json) {\n io.out(`Spawned ANT ${spawn.processId} (tx ${spawn.signature})`);\n }\n // 2. Submit the kind:5095 job carrying OUR processId; the DVM executes\n // buyRecord with ITS funded signer. The job rides a PAID ILP packet to\n // the store node `--via` names (#101), so a session is opened for it and\n // closed whatever happens — it holds the identity lock.\n const submit = deps.submitDvmBuyJob ?? defaultSubmitDvmBuyJob;\n const session = await openStoreJobSession(deps, via);\n let receipt;\n try {\n receipt = await submit({\n destination: via,\n name,\n type,\n years,\n processId: spawn.processId,\n submit: session.submit,\n });\n } finally {\n await session.stop();\n }\n const result = {\n registryTxId: receipt.registryTxId,\n antProcessId: spawn.processId,\n syncAttributesTxId: receipt.syncAttributesTxId,\n dvmQuotedMario: receipt.quotedMario,\n };\n\n if (flags.json) {\n io.emitJson(\n buildJson(true, {\n spawn: { processId: spawn.processId, signature: spawn.signature },\n result,\n })\n );\n } else {\n io.out(\n `Registered \"${name}\" via the DVM — registry tx ${result.registryTxId}`\n );\n io.out(` ANT process (owned by YOU): ${spawn.processId}`);\n if (receipt.syncAttributesTxId) {\n io.out(` Trait sync: ${receipt.syncAttributesTxId}`);\n } else {\n // Proven on devnet: the deployed ario-ant program gates SyncAttributes\n // to the NFT holder, so the DVM cannot reconcile the traits — you can.\n io.out(\n ' Trait sync: not run by the DVM (holder-gated on this ' +\n 'deployment) — as the ANT holder you can reconcile with ' +\n 'syncAttributes later; resolution works regardless.'\n );\n }\n io.out(\n `Point it at content with \\`rig name set ${name} <txId>\\`, then it ` +\n `resolves at https://${name}.<gateway>/`\n );\n }\n return 0;\n }\n\n // ── Direct: register with our own funded wallet (the #367 path) ──────────\n // #79: this identity spawns ITS OWN ANT first (dust SOL, same as the\n // brokered path) and passes its processId into buyRecord, so the name is\n // bound to a real ANT from inception instead of collapsing to the\n // registry's all-ones placeholder.\n const spawn = await signed.sdk.spawnAnt({ name });\n if (!flags.json) {\n io.out(`Spawned ANT ${spawn.processId} (tx ${spawn.signature})`);\n }\n const receipt = await signed.sdk.buyRecord({\n name,\n type,\n ...(years !== null ? { years } : {}),\n processId: spawn.processId,\n });\n // The ANT actually bound: the SDK's echo when it returns one, otherwise the\n // id we asked it to attach (4.0.3's Solana `buyRecord` resolves to `{ id }`\n // alone, so in practice this is the ANT we just spawned). Normalized like\n // every other ANT id, so the placeholder reads as \"no ANT\" here too.\n const antProcessId = antProcessIdOf(receipt.processId ?? spawn.processId);\n const result = { registryTxId: receipt.id, antProcessId };\n const spawnInfo = { processId: spawn.processId, signature: spawn.signature };\n\n if (antProcessId === null) {\n // The purchase went through — the spend is real and on-chain — but no\n // ANT is attached, so the name cannot resolve. Exit non-zero and surface\n // the registry tx either way: never exit 0 on a null ANT (#79), and\n // never lose the tx that makes the spend recoverable.\n const hint =\n `bought \"${name}\" (registry tx ${result.registryTxId}) but no ANT is ` +\n 'attached — the spend is on-chain and recoverable, but the name ' +\n 'cannot resolve until an ANT is attached to it';\n if (flags.json) {\n io.emitJson(buildJson(true, { spawn: spawnInfo, result, hint }));\n } else {\n io.err(hint);\n }\n return 1;\n }\n\n if (flags.json) {\n io.emitJson(buildJson(true, { spawn: spawnInfo, result }));\n } else {\n io.out(`Registered \"${name}\" — registry tx ${result.registryTxId}`);\n io.out(` ANT process: ${result.antProcessId}`);\n io.out(\n `Point it at content with \\`rig name set ${name} <txId>\\`, then it ` +\n `resolves at https://${name}.<gateway>/`\n );\n }\n return 0;\n}\n\n// ---------------------------------------------------------------------------\n// set\n// ---------------------------------------------------------------------------\n\ninterface NameSetJson {\n command: 'name';\n action: 'set';\n name: string;\n undername: string | null;\n txId: string;\n ttl: number;\n network: ArioNetwork;\n processId: string | null;\n /** Gas-station path: the DVM endpoint the kind:5096 job goes to. */\n via: string | null;\n identity: IdentityReport;\n solanaAddress: string;\n antProcessId: string;\n executed: boolean;\n hint?: string;\n /** Gas-station path: the quote the DVM enforced. */\n gasStation?: {\n quoteId: string;\n feePayer: string;\n maxLamports: string;\n expiresAt: number;\n feeLamportsActual: string | null;\n };\n result?: { messageId: string };\n}\n\nasync function runSet(\n name: string,\n txId: string,\n flags: NameFlags,\n deps: NameDeps\n): Promise<number> {\n const { io } = deps;\n // Signerless context: the record lookup / preview is a FREE read (#376);\n // write plumbing is built only after the confirm gate.\n const ctx = await resolveNameContext(\n deps,\n flags.network,\n flags.processId,\n 'read'\n );\n\n const record = await ctx.sdk.getArNSRecord({ name });\n if (!record) {\n throw new Error(\n `no ArNS record for \"${name}\" on ${ctx.network} — buy it first with ` +\n `\\`rig name buy ${name}\\` (or check \\`rig name status ${name}\\`)`\n );\n }\n const antProcessId = antProcessIdOf(record.processId);\n if (antProcessId === null) {\n // #79 AC4: the placeholder is \"no ANT\", not a process id. Signing a\n // record update against it would target the Solana System Program and\n // cannot succeed, so refuse here rather than build and sign a doomed tx.\n throw new Error(\n `\"${name}\" is registered on ${ctx.network} but has NO ANT attached ` +\n `(the registry placeholder ${ARNS_NULL_PROCESS_ID}) — \\`rig name set\\` ` +\n `needs a real ANT process, so there is nothing to write to. Check ` +\n `\\`rig name status ${name}\\`; the name has to be re-bound to an ANT ` +\n `before it can resolve.`\n );\n }\n const undername = flags.undername ?? null;\n const via = flags.via ?? null;\n\n const buildJson = (\n executed: boolean,\n extra: Partial<NameSetJson> = {}\n ): NameSetJson => ({\n command: 'name',\n action: 'set',\n name,\n undername,\n txId,\n ttl: flags.ttl,\n network: ctx.network,\n processId: ctx.processId ?? null,\n via,\n identity: ctx.identity,\n solanaAddress: ctx.solanaAddress,\n antProcessId,\n executed,\n ...extra,\n });\n\n const targetLabel = undername\n ? `undername \"${undername}_${name}\"`\n : `base name \"${name}\"`;\n\n if (!flags.json) {\n io.out(\n `Set ${targetLabel} → txId ${txId} (ttl ${flags.ttl}s) on ${ctx.network}` +\n (via !== null ? ` — gas paid by the DVM at ${via} (kind:5096)` : '')\n );\n io.out(` ANT process: ${antProcessId}`);\n io.out(` Signed by the identity's Solana key (${ctx.solanaAddress}).`);\n if (via !== null) {\n io.out(\n ' Gas station: you author + partial-sign the record update; the ' +\n 'DVM co-signs as fee payer and pays the lamports (toon-meta#163). ' +\n 'Direct backend targeting stubs the job payment (dev/e2e).'\n );\n }\n io.out(renderIdentityLine(ctx.identity));\n }\n\n // ── Confirm gate (a signed ANT record update) ────────────────────────────\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson(\n buildJson(false, {\n hint:\n via === null\n ? 'estimate only — re-run with --yes to write the ANT record'\n : 'estimate only — re-run with --yes to quote the gas-station and write the ANT record (DVM pays the gas)',\n })\n );\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n 'refusing to write an ANT record without confirmation in a ' +\n 'non-interactive session — re-run with --yes (or --json to preview)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Proceed — point ${targetLabel} at ${txId}?` +\n (via !== null ? ' (the DVM pays the gas)' : '') +\n ' [y/N] '\n );\n if (!proceed) {\n io.err('aborted — the ANT record was not changed.');\n return 1;\n }\n }\n\n // ── Execute (sign + submit the ANT record update) ────────────────────────\n // Only now — confirmed — build the signed SDK (write mode).\n const signed = await resolveNameContext(\n deps,\n flags.network,\n flags.processId,\n 'write'\n );\n\n if (via !== null) {\n // ── Gas-station path (toon-meta#163): author + partial-sign locally,\n // the DVM co-signs as fee payer and broadcasts. ────────────────────\n const gas = deps.gasStation ?? defaultGasStationClient;\n // Both phases ride PAID ILP packets to the store node `--via` names\n // (#101). One session covers the pair: the quote's blockhash deadline\n // makes re-opening between them a way to expire your own quote.\n const session = await openStoreJobSession(deps, via);\n let quote: GasStationQuote;\n let executed: GasStationExecuteResult;\n try {\n // Quote: learn the fee payer + the quoted blockhash (merged deadline).\n quote = await gas.quote({\n destination: via,\n submit: session.submit,\n });\n // Build + partial-sign against exactly the quoted blockhash.\n const wireTx = await signed.sdk.buildSetRecordTransaction({\n antProcessId,\n undername: undername ?? '@',\n transactionId: txId,\n ttlSeconds: flags.ttl,\n feePayer: quote.feePayer,\n recentBlockhash: quote.recentBlockhash,\n });\n executed = await gas.execute({\n destination: via,\n transaction: wireTx,\n quoteId: quote.quoteId,\n idempotencyKey: randomUUID(),\n submit: session.submit,\n });\n } finally {\n await session.stop();\n }\n const gasStation = {\n quoteId: quote.quoteId,\n feePayer: quote.feePayer,\n maxLamports: quote.maxLamports,\n expiresAt: quote.expiresAt,\n feeLamportsActual: executed.feeLamportsActual,\n };\n const result = { messageId: executed.signature };\n\n if (flags.json) {\n io.emitJson(buildJson(true, { gasStation, result }));\n } else {\n io.out(\n `Updated — record-set tx ${executed.signature} (gas paid by ${quote.feePayer})`\n );\n const host = undername ? `${undername}_${name}` : name;\n io.out(\n ` Resolves at https://${host}.<gateway>/ (allow for gateway cache/TTL).`\n );\n }\n return 0;\n }\n\n const ant = await signed.sdk.ant(antProcessId);\n const receipt = undername\n ? await ant.setUndernameRecord({\n undername,\n transactionId: txId,\n ttlSeconds: flags.ttl,\n })\n : await ant.setBaseNameRecord({\n transactionId: txId,\n ttlSeconds: flags.ttl,\n });\n const result = { messageId: receipt.id };\n\n if (flags.json) {\n io.emitJson(buildJson(true, { result }));\n } else {\n io.out(`Updated — ANT message ${result.messageId}`);\n const host = undername ? `${undername}_${name}` : name;\n io.out(\n ` Resolves at https://${host}.<gateway>/ (allow for gateway cache/TTL).`\n );\n }\n return 0;\n}\n\n// ---------------------------------------------------------------------------\n// status (FREE)\n// ---------------------------------------------------------------------------\n\ninterface NameStatusJson {\n command: 'name';\n action: 'status';\n name: string;\n network: ArioNetwork;\n processId: string | null;\n registered: boolean;\n /**\n * #79 AC4: the name is registered but no ANT is attached (the registry's\n * all-ones placeholder) — it cannot resolve, and `rig name set` cannot fix\n * it. Never reported as success: status also exits non-zero in this case.\n */\n antMissing: boolean;\n identity: IdentityReport;\n solanaAddress: string;\n record: {\n antProcessId: string | null;\n type: NameType | null;\n startTimestamp: number | null;\n endTimestamp: number | null;\n undernameLimit: number | null;\n } | null;\n /** ANT record targets keyed by undername (`@` = base name). */\n targets: Record<string, AntRecordTarget> | null;\n /** Set when the status is not a clean bill of health (`antMissing`). */\n hint?: string;\n}\n\nasync function runStatus(\n name: string,\n flags: NameFlags,\n deps: NameDeps\n): Promise<number> {\n const { io } = deps;\n // FREE read: signerless SDK — a status lookup must never need write plumbing.\n const ctx = await resolveNameContext(\n deps,\n flags.network,\n flags.processId,\n 'read'\n );\n\n const record = await ctx.sdk.getArNSRecord({ name });\n // #79 AC4: never report the registry's placeholder as the name's ANT. A\n // registered name with no ANT attached cannot resolve, so it is a failure\n // to be diagnosed — not a healthy registration.\n const antProcessId = antProcessIdOf(record?.processId);\n const antMissing = record !== null && antProcessId === null;\n const antMissingHint =\n `\"${name}\" is registered on ${ctx.network} but has NO ANT attached ` +\n `(the registry placeholder ${ARNS_NULL_PROCESS_ID}) — it cannot resolve, ` +\n `and \\`rig name set\\` cannot write records against it. The name has to be ` +\n `re-bound to an ANT.`;\n let targets: Record<string, AntRecordTarget> | null = null;\n if (antProcessId !== null) {\n const ant = await ctx.sdk.ant(antProcessId);\n targets = await ant.getRecords();\n }\n\n if (flags.json) {\n io.emitJson({\n command: 'name',\n action: 'status',\n name,\n network: ctx.network,\n processId: ctx.processId ?? null,\n registered: record !== null,\n antMissing,\n identity: ctx.identity,\n solanaAddress: ctx.solanaAddress,\n record: record\n ? {\n antProcessId,\n type: record.type,\n startTimestamp: record.startTimestamp ?? null,\n endTimestamp: record.endTimestamp ?? null,\n undernameLimit: record.undernameLimit ?? null,\n }\n : null,\n targets,\n ...(antMissing ? { hint: antMissingHint } : {}),\n } satisfies NameStatusJson);\n return antMissing ? 1 : 0;\n }\n\n io.out(`ArNS name \"${name}\" on ${ctx.network}:`);\n if (!record) {\n io.out(' not registered — available to `rig name buy`.');\n io.out(renderIdentityLine(ctx.identity));\n return 0;\n }\n io.out(` ANT process: ${antProcessId ?? 'NONE — no ANT is attached'}`);\n io.out(` Type: ${record.type ?? '(unknown)'}`);\n if (record.type === 'permabuy') {\n io.out(' Expiry: never (permabuy)');\n } else if (record.endTimestamp !== undefined) {\n io.out(` Expiry: ${new Date(record.endTimestamp).toISOString()}`);\n }\n if (record.undernameLimit !== undefined) {\n io.out(` Undernames included: ${record.undernameLimit}`);\n }\n if (targets && Object.keys(targets).length > 0) {\n io.out(' Records:');\n for (const [under, target] of Object.entries(targets)) {\n const label = under === '@' ? '(base)' : `${under}_${name}`;\n io.out(\n ` ${label} → ${target.transactionId} (ttl ${target.ttlSeconds}s)`\n );\n }\n } else if (antMissing) {\n io.out(' Records: none — there is no ANT to hold them.');\n } else {\n io.out(' Records: none set — point one with `rig name set`.');\n }\n io.out(renderIdentityLine(ctx.identity));\n if (antMissing) {\n io.err(antMissingHint);\n return 1;\n }\n return 0;\n}\n\n// ---------------------------------------------------------------------------\n// Dispatch\n// ---------------------------------------------------------------------------\n\n/** Run `rig name <sub> …`; returns the process exit code. */\nexport async function runName(args: string[], deps: NameDeps): Promise<number> {\n const { io } = deps;\n const sub = args[0];\n\n if (sub === undefined) {\n // Usage error → stderr + exit 2 (matches every other rig-owned command).\n io.err(NAME_USAGE);\n return 2;\n }\n if (sub === '--help' || sub === '-h' || sub === 'help') {\n io.out(NAME_USAGE);\n return 0;\n }\n if (!['buy', 'set', 'status'].includes(sub)) {\n io.err(`unknown \\`rig name\\` subcommand: ${JSON.stringify(sub)}`);\n io.err(NAME_USAGE);\n return 2;\n }\n\n let positionals: string[];\n let flags: NameFlags;\n try {\n const parsed = parseNameFlags(args.slice(1), deps.env);\n positionals = parsed.positionals;\n flags = parsed.flags;\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(NAME_USAGE);\n return 2;\n }\n if (positionals[0] === '--help') {\n io.out(NAME_USAGE);\n return 0;\n }\n\n const name = positionals[0];\n if (name === undefined) {\n io.err(`\\`rig name ${sub}\\` needs a <name>`);\n io.err(NAME_USAGE);\n return 2;\n }\n\n // Default `--via` DVM on the shared devnet (#demo): buy/set broker through\n // the deployed store DVM when the user neither named a DVM (--via /\n // RIG_ARNS_DVM_URL) nor opted out (--direct). Hard-gated BOTH ways: the\n // ArNS `--network` must be devnet (a mainnet purchase must never silently\n // switch payment paths) AND the TOON network must resolve to devnet (same\n // inference `rig fund` drips on — explicit config, devnet origin, or the\n // genesis-seed fresh install).\n if (\n (sub === 'buy' || sub === 'set') &&\n !flags.direct &&\n flags.via === undefined &&\n flags.network === 'devnet'\n ) {\n let toonDevnet = false;\n try {\n const resolved = await (\n deps.resolveToonNetwork ?? resolveEffectiveNetwork\n )({ env: deps.env, cwd: deps.cwd });\n toonDevnet = resolved.effectiveNetwork === 'devnet';\n } catch {\n // Unreadable client config — leave the wallet-paid path untouched.\n }\n if (toonDevnet) {\n flags = { ...flags, via: DEVNET_DVM_DESTINATION };\n io.err(\n `Brokering via the devnet store DVM ${DEVNET_DVM_DESTINATION} ` +\n `(no --via given; pass --direct for a wallet-paid ${sub}).`\n );\n }\n }\n\n try {\n if (sub === 'buy') return await runBuy(name, flags, deps);\n if (sub === 'status') return await runStatus(name, flags, deps);\n // set: `rig name set <name> <txId>` — or `rig name set <name> --tx-id\n // <id>` (#399: a positional txId leading with `-`/`_` is hyphen-\n // ambiguous with Node's strict `parseArgs`).\n if (flags.txId !== undefined && positionals[1] !== undefined) {\n io.err('`--tx-id` and a positional <txId> are mutually exclusive');\n io.err(NAME_USAGE);\n return 2;\n }\n const txId = flags.txId ?? positionals[1];\n if (txId === undefined) {\n io.err(\n '`rig name set` needs a <txId> (the Arweave transaction to point at) ' +\n '— as a positional or via --tx-id'\n );\n io.err(NAME_USAGE);\n return 2;\n }\n return await runSet(name, txId, flags, deps);\n } catch (err) {\n return emitCliError(io, flags.json, 'name', err);\n }\n}\n","/**\n * `rig payout set|clear|show` (rig#92, part of the payout epic\n * toon-protocol/toon-meta#391) — manage the declared payout pointer on a\n * repo's kind:30617 announcement.\n *\n * The payout pointer is the ONLY thing that turns on a serving node's\n * node-declared `ownerFeeShare` split on repo-scoped paid writes\n * (toon-meta#391 decision 2): no pointer on the announcement → no split, the\n * node keeps 100%. v1 accepts exactly one chain, `evm` — the payout accrual\n * ledger is EVM-only today (`crates/connector-client-edge/src/btp.rs:270-272`)\n * — but the tag shape (`['payout', '<chain>', '<address>']`) carries the\n * chain label so nothing re-shapes later.\n *\n * show FREE relay read — print the pointer or \"none\"\n * set <address> PAID — republish the 30617 with the payout tag set to\n * `evm <checksummed address>`\n * clear PAID — republish the 30617 with the payout tag removed\n *\n * set/clear republish the WHOLE announcement (a replaceable event keyed by\n * author + `d` tag), so they preserve the existing name/description/\n * maintainers and only mutate the payout pointer — mirrors `rig maintainers`\n * exactly (`./maintainers.ts:1-23`). Because the 30617 is addressed by its\n * author, only the OWNER's republish is authoritative, so a non-owner\n * republish is refused (same shape as maintainers.ts:344-351), as is a\n * republish on an unannounced repo (maintainers.ts:369-377). The daemon has\n * no announcement route, so this always runs the embedded standalone\n * publisher; the confirm gate matches every other paid write (`--yes` skips;\n * a non-TTY without it refuses; `--json` without `--yes` is a pure\n * estimate).\n */\n\nimport { parseArgs } from 'node:util';\nimport { getAddress } from 'viem';\nimport {\n isValidEvmPayoutAddress,\n type PayoutPointer,\n} from '../nip34-events.js';\nimport {\n amendRepoAnnouncement,\n conformanceEdits,\n diffAnnouncementTags,\n} from '../repo-announcement.js';\nimport { fetchRemoteState } from '../remote-state.js';\nimport { serializeEventReceipt, type GitEventResponse } from '../routes.js';\nimport type { EventCommandDeps } from './events.js';\nimport { emitCliError, InvalidRelayUrlError } from './errors.js';\nimport type { IdentityReport } from './push.js';\nimport { describeAnnouncementDiff, feeLabel } from './render.js';\nimport {\n openAnnouncementRepublish,\n pickRepoCommandFlags,\n REPO_COMMAND_OPTIONS,\n resolveRepoContext,\n WS_URL_RE,\n type RepoCommandFlags,\n} from './repo-command.js';\nimport type { StandaloneContext } from './standalone-context.js';\n\nexport const PAYOUT_USAGE = `Usage: rig payout <set|clear|show> [<address>] [options]\n\nManage a repo's declared payout pointer (rig#92, part of the payout epic\ntoon-protocol/toon-meta#391). No pointer on the kind:30617 announcement means\na serving node keeps 100% of repo-scoped write fees; a pointer opts the repo\ninto that node's declared ownerFeeShare split.\n\nSubcommands:\n show show the declared payout pointer — FREE (relay read)\n set <address> declare the payout pointer (EVM address, EIP-55\n checksummed or all-lowercase) — PAID: republishes the\n kind:30617 (permanent, non-refundable). v1 accepts evm\n addresses only.\n clear remove the payout pointer — PAID: republishes the\n kind:30617\n\nset/clear must run under the repo OWNER's identity (only the owner's\nannouncement is authoritative).\n\nOptions:\n --repo-id <id> repository id / NIP-34 d-tag (default: git config)\n --owner <pubkey> repository owner (npub or hex; default: git config)\n --remote <name> publish/read via this configured git remote (default: origin)\n --relay <url> ad-hoc relay override (exactly one for set/clear)\n --yes skip the fee confirmation (required when not a TTY)\n --json machine-readable envelope\n -h, --help show this help`;\n\n/** Run `rig payout …`; returns the process exit code. */\nexport async function runPayout(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n switch (sub) {\n case 'show':\n return runShow(rest, deps);\n case 'set':\n return runMutate('set', rest, deps);\n case 'clear':\n return runMutate('clear', rest, deps);\n case '--help':\n case '-h':\n case 'help':\n io.out(PAYOUT_USAGE);\n return 0;\n default:\n io.err(\n sub === undefined\n ? 'missing subcommand: rig payout <set|clear|show>'\n : `unknown rig payout subcommand: ${sub}`\n );\n io.err(PAYOUT_USAGE);\n return 2;\n }\n}\n\n// ---------------------------------------------------------------------------\n// show (FREE)\n// ---------------------------------------------------------------------------\n\nasync function runShow(\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n let flags: RepoCommandFlags;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: REPO_COMMAND_OPTIONS,\n allowPositionals: true,\n });\n if (positionals.length > 0) {\n throw new Error('rig payout show takes no positional arguments');\n }\n flags = pickRepoCommandFlags(values);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(PAYOUT_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(PAYOUT_USAGE);\n return 0;\n }\n\n try {\n const ctx = await resolveRepoContext(flags, deps);\n const wsRelays = ctx.relays.filter((url) => WS_URL_RE.test(url));\n if (wsRelays.length === 0) {\n throw new InvalidRelayUrlError(\n ctx.relays[0] ?? '',\n 'reads need a ws:// or wss:// relay'\n );\n }\n const remote = await fetchRemoteState({\n relayUrls: wsRelays,\n ownerPubkey: ctx.owner,\n repoId: ctx.repoId,\n ...(deps.webSocketFactory\n ? { webSocketFactory: deps.webSocketFactory }\n : {}),\n });\n const payout = remote.payout;\n if (flags.json) {\n io.emitJson({\n command: 'payout show',\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n announced: remote.announced,\n payout,\n });\n return 0;\n }\n io.out(`Repo: 30617:${ctx.owner}:${ctx.repoId}`);\n if (!remote.announced) {\n io.out('No kind:30617 announcement found — no payout pointer.');\n return 0;\n }\n io.out(\n payout === null\n ? 'Payout: none (the serving node keeps 100% of repo-scoped write fees)'\n : `Payout: ${payout.chain} ${payout.address}`\n );\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, 'payout show', err);\n }\n}\n\n// ---------------------------------------------------------------------------\n// set / clear (PAID — republish the 30617 under the owner's identity)\n// ---------------------------------------------------------------------------\n\ninterface PayoutJsonOutput {\n command: 'payout set' | 'payout clear';\n repoAddr: { ownerPubkey: string; repoId: string };\n identity: IdentityReport;\n executed: boolean;\n feeEstimate: string | null;\n payout: PayoutPointer | null;\n /**\n * Every tag the republish adds and drops (#158) — the payout edit plus the\n * conformance backfill. A `--json` consumer sees exactly what the fee buys,\n * the same as the human confirmation does.\n */\n changes: { added: string[][]; removed: string[][] };\n result?: GitEventResponse;\n hint?: string;\n}\n\nasync function runMutate(\n op: 'set' | 'clear',\n args: string[],\n deps: EventCommandDeps\n): Promise<number> {\n const { io } = deps;\n const command = `payout ${op}` as 'payout set' | 'payout clear';\n\n let flags: RepoCommandFlags;\n /** The pointer this run publishes: validated for `set`, `null` for `clear`. */\n let nextPayout: PayoutPointer | null = null;\n try {\n const { values, positionals } = parseArgs({\n args,\n options: REPO_COMMAND_OPTIONS,\n allowPositionals: true,\n });\n flags = pickRepoCommandFlags(values);\n if (flags.help) {\n io.out(PAYOUT_USAGE);\n return 0;\n }\n if (op === 'set') {\n if (positionals.length !== 1) {\n throw new Error('expected exactly one <address> to set');\n }\n const raw = positionals[0] as string;\n if (!isValidEvmPayoutAddress(raw)) {\n throw new Error(\n `<address> must be a valid EVM address (0x + 40 hex chars, ` +\n `correctly EIP-55 checksummed if mixed-case) — got ` +\n `${JSON.stringify(raw)}. See toon-meta#391 (payout epic): v1 ` +\n 'accepts evm addresses only.'\n );\n }\n nextPayout = { chain: 'evm', address: getAddress(raw) };\n } else if (positionals.length !== 0) {\n throw new Error('rig payout clear takes no positional arguments');\n }\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(PAYOUT_USAGE);\n return 2;\n }\n\n let standaloneCtx: StandaloneContext | undefined;\n try {\n // Every money-safety refusal a paid republish must clear — one relay, the\n // embedded publisher, owner-only, and no phantom 30617 on an unannounced\n // repo — lives in ./repo-command.ts, shared with maintainers and refresh.\n const opened = await openAnnouncementRepublish({\n deps,\n flags,\n what: 'change the payout pointer',\n before: 'before managing the payout pointer',\n });\n standaloneCtx = opened.standalone;\n if (!opened.ok) return opened.exitCode;\n const { ctx, relayUrl, identity, remote, facts } = opened;\n\n const current = remote.payout;\n if (\n nextPayout !== null &&\n current !== null &&\n current.chain === nextPayout.chain &&\n current.address === nextPayout.address\n ) {\n io.err(\n `rig: payout is already set to ${current.chain} ${current.address} — nothing to do (not published).`\n );\n return 0;\n }\n if (op === 'clear' && current === null) {\n io.err('rig: no payout pointer is set — nothing to do (not published).');\n return 0;\n }\n\n // Amend rather than rebuild (#154): `payout` is the ONLY field this\n // command edits, so name, description, the maintainers tag and every tag\n // rig does not model survive the replaceable write verbatim instead of\n // being destroyed by it. Passing a field here would rewrite it.\n // #158: an owner-initiated republish also BACKFILLS the conformance tags\n // (`relays`, `web`, and the `euc` when the announcement has none).\n const event = amendRepoAnnouncement(remote.announceEvent, {\n repoId: ctx.repoId,\n payout: nextPayout,\n ...conformanceEdits(remote.announceEvent, facts),\n });\n const diff = diffAnnouncementTags(remote.announceEvent, event);\n const changes = { added: diff.added, removed: diff.removed };\n const fee = (\n await opened.standalone.publisher.getFeeRates()\n ).eventFee.toString();\n const action = nextPayout\n ? `kind:30617 payout set ${nextPayout.chain} ${nextPayout.address}`\n : 'kind:30617 payout clear';\n\n // ── Confirm gate ────────────────────────────────────────────────────────\n if (!flags.json) {\n io.out(`Republish ${action}`);\n io.out(`Repo: 30617:${ctx.owner}:${ctx.repoId}`);\n io.out(\n `Payout after: ${nextPayout ? `${nextPayout.chain} ${nextPayout.address}` : '(none)'}`\n );\n if (!diff.unchanged) {\n io.out('Tags changed:');\n for (const line of describeAnnouncementDiff(diff)) io.out(line);\n }\n io.out(`Fee: ${feeLabel(fee)}. Writes are permanent and non-refundable.`);\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n identity,\n executed: false,\n feeEstimate: fee,\n payout: nextPayout,\n changes,\n hint: 'estimate only — re-run with --yes to publish (permanent, non-refundable)',\n } satisfies PayoutJsonOutput);\n return 0;\n }\n if (!io.isInteractive) {\n io.err(\n 'refusing to spend channel funds without confirmation in a non-interactive ' +\n 'session — re-run with --yes (or use --json for an estimate)'\n );\n return 1;\n }\n const proceed = await io.confirm(\n `Proceed with paid republish (${feeLabel(fee)})? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was published.');\n return 1;\n }\n }\n\n // ── Execute ───────────────────────────────────────────────────────────────\n const receipt = await opened.standalone.publisher.publishEvent(event, [\n relayUrl,\n ]);\n const result = serializeEventReceipt(event.kind, receipt);\n\n if (flags.json) {\n io.emitJson({\n command,\n repoAddr: { ownerPubkey: ctx.owner, repoId: ctx.repoId },\n identity,\n executed: true,\n feeEstimate: fee,\n payout: nextPayout,\n changes,\n result,\n } satisfies PayoutJsonOutput);\n } else {\n io.out(\n `Published ${action}: ${result.eventId} paid ${result.feePaid} base units`\n );\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, command, err);\n } finally {\n if (standaloneCtx) {\n try {\n await standaloneCtx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n","/**\n * `rig site publish [ref]` + `rig site url [ref]` — a pushed repo as a\n * permaweb site (#368).\n *\n * Every `rig push` already stores a repo's raw blob bytes on Arweave and, with\n * #368's per-file Content-Type, a gateway serves each blob as its real media\n * type. `rig site publish` adds the last piece: it walks a ref's root tree,\n * joins each file path to the Arweave txId the cumulative kind:30618 `arweave`\n * map already records for that blob (no GraphQL, no re-upload), builds the\n * ar.io path manifest, and uploads THAT as one paid store write. The manifest\n * txId is the site's canonical URL: `https://<gateway>/<txid>/`. Point an ArNS\n * name at it (#367, `rig name set`) for a stable, human name.\n *\n * PAID DISCIPLINE (mirrors `rig push`): estimate → confirm → execute, strict\n * `--json` (one document on stdout), `--yes` required to spend in a non-TTY.\n * Without `--yes`, `--json` is a pure estimate (nothing uploaded, exit 0).\n *\n * `--force-reupload` re-pays to upload the ref's blobs THROUGH the #368\n * mime-typed path before building the manifest, for repos pushed before\n * per-file Content-Type existed (whose blobs would otherwise serve as\n * `application/octet-stream`). Content-addressed dedupe means a plain re-push\n * would skip them, so this is the explicit escape hatch.\n *\n * `rig site url [ref]` is FREE: it reads the manifest txId the last publish\n * recorded locally (../cli/site-record.ts) and prints the URL — no client\n * start, no relay query, no payment.\n */\n\nimport { uploadChargeFor } from '../publisher.js';\nimport { PREFERRED_GATEWAY } from '../gateway-preference.js';\nimport { parseArgs } from 'node:util';\nimport {\n buildArweaveManifest,\n type ManifestEntry,\n} from '../arweave-manifest.js';\nimport { resolveConflictingPath } from '../mime.js';\nimport { GitRepoReader } from '../repo-reader.js';\nimport type { RemoteState } from '../remote-state.js';\nimport {\n defaultLoadStandalone,\n identityReport,\n selectRefspecs,\n type IdentityReport,\n type PushDeps,\n} from './push.js';\nimport { emitCliError, UnconfiguredRepoAddressError } from './errors.js';\nimport { readToonConfig, resolveRepoRoot } from './git-config.js';\nimport { renderIdentityLine } from './render.js';\nimport { resolveRelays, singleRelayRefusal } from './remote.js';\nimport { readSiteRecord, writeSiteRecord } from './site-record.js';\nimport type { StandaloneContext } from './standalone-context.js';\n\n/** The ar.io path-manifest media type (spec-mandated `output` tag value). */\nexport const MANIFEST_CONTENT_TYPE = 'application/x.arweave-manifest+json';\n\n/**\n * Default Arweave/ar.io gateway the printed site URL uses: the shared list's\n * first MAINNET gateway ({@link PREFERRED_GATEWAY}), so this and `rig push`\n * cannot drift apart. A site is ONE manifest txid, so only the primary is\n * printed here — pass `--gateway` (or `RIG_ARWEAVE_GATEWAY`) to re-print\n * against another when one is down.\n */\nexport const DEFAULT_GATEWAY = PREFERRED_GATEWAY;\n\nexport const SITE_USAGE = `Usage: rig site <publish|url> [ref] [options]\n\nServe a pushed repo as a permanent, path-routed website. \\`rig push\\` already\nstored the file bytes on Arweave; \\`rig site publish\\` builds the ar.io path\nmanifest (paths → Arweave txids, index → index.html) and uploads it as ONE\npaid store write, printing the site URL. \\`rig site url\\` re-prints the URL of\nthe last publish for free.\n\nThe repo must be set up with \\`rig init\\`; the relay is the \"origin\" remote\n(\\`rig push\\` reads the same). \\`ref\\` defaults to the current branch.\n\nCommands:\n publish [ref] build + upload the path manifest (paid); prints the URL and\n a \\`rig name set\\` suggestion (#367)\n url [ref] print the last-published site URL for a ref (free)\n\nOptions (publish):\n --index <path> path served at / (default: index.html)\n --spa single-page app: serve index for any unknown path\n (sets the manifest \\`fallback\\` to the index txid)\n --fallback <path> explicit fallback path for unknown routes (overrides\n --spa); must be one of the site's files\n --force-reupload re-pay to re-upload the ref's blobs with #368 per-file\n Content-Type before building the manifest — for repos\n pushed before mime-typing existed (else they serve as\n application/octet-stream)\n --gateway <url> gateway base for the printed URL (default: ${DEFAULT_GATEWAY};\n env RIG_ARWEAVE_GATEWAY also sets it)\n --relay <url> ad-hoc relay override (bypasses configured remotes)\n --repo-id <id> repository id (default: git config toon.repoid)\n --yes skip the fee confirmation (required when not a TTY)\n --json machine-readable envelope; without --yes it is a pure\n estimate (nothing uploaded)\n -h, --help show this help`;\n\n/** Deps for `rig site` — the same seam `rig push` uses (tests inject fakes). */\nexport type SiteDeps = PushDeps;\n\n// ---------------------------------------------------------------------------\n// Arg parsing\n// ---------------------------------------------------------------------------\n\ninterface SiteFlags {\n index: string;\n spa: boolean;\n fallback?: string;\n forceReupload: boolean;\n gateway?: string;\n relay: string[];\n repoId?: string;\n yes: boolean;\n json: boolean;\n help: boolean;\n positionals: string[];\n}\n\nfunction parseSiteArgs(args: string[]): SiteFlags {\n const { values, positionals } = parseArgs({\n args,\n options: {\n index: { type: 'string' },\n spa: { type: 'boolean', default: false },\n fallback: { type: 'string' },\n 'force-reupload': { type: 'boolean', default: false },\n gateway: { type: 'string' },\n relay: { type: 'string', multiple: true },\n 'repo-id': { type: 'string' },\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 const flags: SiteFlags = {\n index: values.index ?? 'index.html',\n spa: values.spa ?? false,\n forceReupload: values['force-reupload'] ?? false,\n relay: values.relay ?? [],\n yes: values.yes ?? false,\n json: values.json ?? false,\n help: values.help ?? false,\n positionals,\n };\n if (values.fallback !== undefined) flags.fallback = values.fallback;\n if (values.gateway !== undefined) flags.gateway = values.gateway;\n if (values['repo-id'] !== undefined) flags.repoId = values['repo-id'];\n return flags;\n}\n\n// ---------------------------------------------------------------------------\n// JSON envelopes\n// ---------------------------------------------------------------------------\n\ninterface SitePublishJson {\n command: 'site publish';\n repoId: string;\n ref: string;\n identity: IdentityReport;\n executed: boolean;\n forceReupload: boolean;\n /** Number of files the manifest routes. */\n fileCount: number;\n index: string;\n fallback?: string;\n estimate: {\n manifestBytes: number;\n reuploadBytes: number;\n /** Total fee to spend, base units (string — bigint is not JSON-safe). */\n totalFee: string;\n };\n manifest?: { txId: string; url: string };\n nameHint?: string;\n hint?: string;\n}\n\ninterface SiteUrlJson {\n command: 'site url';\n repoId: string;\n ref: string;\n found: boolean;\n manifestTxId?: string;\n url?: string;\n updatedAt?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction normalizeGateway(gateway: string): string {\n return gateway.replace(/\\/+$/, '');\n}\n\nfunction siteUrl(gateway: string, manifestTxId: string): string {\n return `${normalizeGateway(gateway)}/${manifestTxId}/`;\n}\n\n/** A 43-char placeholder txId for accurate manifest-size estimation. */\nconst PLACEHOLDER_TX = 'A'.repeat(43);\n\n// ---------------------------------------------------------------------------\n// Command\n// ---------------------------------------------------------------------------\n\n/** Route `rig site <sub>`; returns the process exit code. */\nexport async function runSite(args: string[], deps: SiteDeps): Promise<number> {\n const { io } = deps;\n const [sub, ...rest] = args;\n\n if (sub === 'publish') return runSitePublish(rest, deps);\n if (sub === 'url') return runSiteUrl(rest, deps);\n if (sub === undefined || sub === '-h' || sub === '--help' || sub === 'help') {\n io.out(SITE_USAGE);\n return sub === undefined ? 2 : 0;\n }\n io.err(`unknown site subcommand ${JSON.stringify(sub)}`);\n io.err(SITE_USAGE);\n return 2;\n}\n\n// ---------------------------------------------------------------------------\n// site publish\n// ---------------------------------------------------------------------------\n\nasync function runSitePublish(args: string[], deps: SiteDeps): Promise<number> {\n const { io } = deps;\n\n let flags: SiteFlags;\n try {\n flags = parseSiteArgs(args);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(SITE_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(SITE_USAGE);\n return 0;\n }\n\n let ctx: StandaloneContext | undefined;\n try {\n // ── Repo + config ──────────────────────────────────────────────────────\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 // ── Ref selection (single ref; default current branch) ─────────────────\n const selected = await selectRefspecs(\n reader,\n flags.positionals,\n false,\n false\n );\n if (selected.length !== 1) {\n throw new Error(\n `rig site publish builds ONE ref into a site — got ${selected.length} ` +\n `(${selected.join(', ')}); pass a single branch or tag`\n );\n }\n const ref = selected[0] as string;\n\n // ── Relay resolution (origin default; same path as push) ───────────────\n const resolved = await resolveRelays({\n relayFlags: flags.relay,\n remoteName: undefined,\n repoRoot,\n toonRelays: toonConfig.relays,\n });\n if (resolved.nudge !== undefined) io.err(resolved.nudge);\n const relaysUsed = resolved.relays;\n if (relaysUsed.length > 1) {\n io.err(singleRelayRefusal(resolved, 'Nothing was uploaded or paid.'));\n return 1;\n }\n\n // ── Standalone session (identity + publisher) ──────────────────────────\n ctx = await (deps.loadStandalone ?? defaultLoadStandalone)({\n env: deps.env,\n cwd: deps.cwd,\n warn: (line) => io.err(line),\n ...(relaysUsed[0] !== undefined ? { relayUrl: relaysUsed[0] } : {}),\n });\n const identity = identityReport(ctx);\n if (!ctx.publisher.uploadBlob) {\n throw new Error(\n 'the active publisher cannot upload a raw manifest blob ' +\n '(uploadBlob unavailable) — `rig site` requires the standalone publisher'\n );\n }\n\n // ── Files + the known sha→txId map from the cumulative refs event ──────\n const blobs = await reader.listBlobs(ref);\n if (blobs.length === 0) {\n throw new Error(`ref ${JSON.stringify(ref)} has no files to serve`);\n }\n const shaToPaths = new Map<string, string[]>();\n for (const { path, sha } of blobs) {\n const paths = shaToPaths.get(sha) ?? [];\n paths.push(path);\n shaToPaths.set(sha, paths);\n }\n const uniqueShas = [...shaToPaths.keys()];\n\n const remoteState: RemoteState = await ctx.fetchRemote({\n ownerPubkey: ctx.ownerPubkey,\n repoId,\n relayUrls: relaysUsed,\n });\n const known = new Map(remoteState.shaToTxId);\n // Resolve any sha the refs event didn't carry (GraphQL fallback) — free.\n const gaps = uniqueShas.filter((sha) => !known.has(sha));\n if (gaps.length > 0) {\n const found = await remoteState.resolveMissing(gaps);\n for (const [sha, txId] of found) known.set(sha, txId);\n }\n\n // ── Fallback (SPA) path resolution ─────────────────────────────────────\n const fallbackPath =\n flags.fallback ?? (flags.spa ? flags.index : undefined);\n const pathSet = new Set(blobs.map((b) => b.path));\n if (fallbackPath !== undefined && !pathSet.has(fallbackPath)) {\n throw new Error(\n `fallback path ${JSON.stringify(fallbackPath)} is not one of the ` +\n \"site's files — pick an existing path (or the --index file for --spa)\"\n );\n }\n if (!pathSet.has(flags.index)) {\n io.err(\n `warning: no ${JSON.stringify(flags.index)} in this ref — the site ` +\n 'will 404 at / until you add one (or pass --index <path>)'\n );\n }\n\n // ── Without --force-reupload every file must already be on Arweave ──────\n if (!flags.forceReupload) {\n const unpublished = uniqueShas.filter((sha) => !known.has(sha));\n if (unpublished.length > 0) {\n const paths = unpublished\n .flatMap((sha) => shaToPaths.get(sha) ?? [])\n .slice(0, 10);\n throw new Error(\n `${unpublished.length} file(s) in ${ref} are not on Arweave yet ` +\n `(e.g. ${paths.join(', ')}) — run \\`rig push\\` first, or ` +\n '`rig site publish --force-reupload` to upload them now (paid).'\n );\n }\n }\n\n // ── Fee estimate ───────────────────────────────────────────────────────\n // An upload costs the store route's schedule for its size (ADR 0065) —\n // the same rule the publisher's claim follows.\n const feeRates = await ctx.publisher.getFeeRates();\n // Preview manifest with known/placeholder 43-char txids: byte-accurate for\n // the fee (every txid is 43 chars, so the real manifest is the same size).\n const previewEntries: ManifestEntry[] = blobs.map((b) => ({\n path: b.path,\n txId: known.get(b.sha) ?? PLACEHOLDER_TX,\n }));\n const previewManifest = buildArweaveManifest(\n previewEntries,\n flags.index,\n fallbackPath ? PLACEHOLDER_TX : undefined\n );\n const manifestBytes = Buffer.byteLength(JSON.stringify(previewManifest));\n\n let reuploadBytes = 0;\n let reuploadFee = 0n;\n if (flags.forceReupload) {\n const { objects } = await reader.statObjects(uniqueShas);\n reuploadBytes = objects.reduce((sum, o) => sum + o.size, 0);\n reuploadFee = objects.reduce(\n (sum, o) => sum + uploadChargeFor(feeRates, o.size),\n 0n\n );\n }\n const manifestFee = uploadChargeFor(feeRates, manifestBytes);\n const totalFee = manifestFee + reuploadFee;\n\n const gateway =\n flags.gateway ?? deps.env['RIG_ARWEAVE_GATEWAY'] ?? DEFAULT_GATEWAY;\n\n const baseJson = (): Omit<SitePublishJson, 'executed'> => ({\n command: 'site publish',\n repoId,\n ref,\n identity,\n forceReupload: flags.forceReupload,\n fileCount: blobs.length,\n index: flags.index,\n ...(fallbackPath ? { fallback: fallbackPath } : {}),\n estimate: {\n manifestBytes,\n reuploadBytes,\n totalFee: totalFee.toString(),\n },\n });\n\n // ── Confirm gate ───────────────────────────────────────────────────────\n if (!flags.json) {\n io.out(`Site publish plan for ${ref} (repo ${repoId}):`);\n io.out(` files: ${blobs.length}`);\n io.out(\n ` index: ${flags.index}${pathSet.has(flags.index) ? '' : ' (missing!)'}`\n );\n if (fallbackPath) io.out(` fallback: ${fallbackPath}`);\n if (flags.forceReupload) {\n io.out(\n ` re-upload ${uniqueShas.length} blob(s), ${reuploadBytes} bytes (paid)`\n );\n }\n io.out(` manifest: ${manifestBytes} bytes`);\n io.out(` total fee: ${totalFee} base units`);\n io.out(renderIdentityLine(identity));\n }\n if (!flags.yes) {\n if (flags.json) {\n io.emitJson({\n ...baseJson(),\n executed: false,\n hint: 'estimate only — re-run with --yes to upload the manifest (permanent, non-refundable)',\n } satisfies SitePublishJson);\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 site publish (total ${totalFee} base units)? [y/N] `\n );\n if (!proceed) {\n io.err('aborted — nothing was uploaded.');\n return 1;\n }\n }\n\n // ── Execute ────────────────────────────────────────────────────────────\n // #368 force-reupload: re-pay to upload each blob THROUGH the mime-typed\n // git-object path so the store tags it with the right Content-Type; the\n // returned (fresh) txids feed the manifest.\n if (flags.forceReupload) {\n const { objects, missing } = await reader.readObjects(uniqueShas);\n if (missing.length > 0) {\n throw new Error(\n `objects vanished from the local repository: ${missing.join(', ')}`\n );\n }\n const bodyBySha = new Map(objects.map((o) => [o.sha, o.body]));\n for (const sha of uniqueShas) {\n const body = bodyBySha.get(sha);\n if (!body) throw new Error(`internal: no body for ${sha}`);\n // A blob reached by conflicting-extension paths uploads as\n // octet-stream (deterministic, no arbitrary favoring); otherwise its\n // single content type.\n const uploadPath = resolveConflictingPath(shaToPaths.get(sha) ?? []);\n const receipt = await ctx.publisher.uploadGitObject({\n sha,\n type: 'blob',\n body,\n repoId,\n ...(uploadPath ? { path: uploadPath } : {}),\n });\n known.set(sha, receipt.txId);\n }\n }\n\n const entries: ManifestEntry[] = blobs.map((b) => {\n const txId = known.get(b.sha);\n if (!txId) {\n throw new Error(`internal: no Arweave txid for ${b.path} (${b.sha})`);\n }\n return { path: b.path, txId };\n });\n const fallbackTxId =\n fallbackPath !== undefined\n ? entries.find((e) => e.path === fallbackPath)?.txId\n : undefined;\n const manifest = buildArweaveManifest(entries, flags.index, fallbackTxId);\n const manifestBody = Buffer.from(JSON.stringify(manifest), 'utf8');\n\n const receipt = await ctx.publisher.uploadBlob({\n body: manifestBody,\n contentType: MANIFEST_CONTENT_TYPE,\n repoId,\n });\n const url = siteUrl(gateway, receipt.txId);\n writeSiteRecord(deps.env, {\n repoId,\n ref,\n owner: ctx.ownerPubkey,\n manifestTxId: receipt.txId,\n gateway: normalizeGateway(gateway),\n updatedAt: Date.now(),\n });\n\n const nameHint = `Point a name at it (see #367): rig name set <name> ${receipt.txId}`;\n if (flags.json) {\n io.emitJson({\n ...baseJson(),\n executed: true,\n manifest: { txId: receipt.txId, url },\n nameHint,\n } satisfies SitePublishJson);\n } else {\n io.out(`Site published: ${url}`);\n io.out(nameHint);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, 'site publish', err);\n } finally {\n if (ctx) {\n try {\n await ctx.stop();\n } catch {\n // best-effort teardown\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// site url (free)\n// ---------------------------------------------------------------------------\n\nasync function runSiteUrl(args: string[], deps: SiteDeps): Promise<number> {\n const { io } = deps;\n\n let flags: SiteFlags;\n try {\n flags = parseSiteArgs(args);\n } catch (err) {\n io.err(err instanceof Error ? err.message : String(err));\n io.err(SITE_USAGE);\n return 2;\n }\n if (flags.help) {\n io.out(SITE_USAGE);\n return 0;\n }\n\n try {\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 const selected = await selectRefspecs(\n reader,\n flags.positionals,\n false,\n false\n );\n if (selected.length !== 1) {\n throw new Error(\n `rig site url takes ONE ref — got ${selected.length} (${selected.join(', ')})`\n );\n }\n const ref = selected[0] as string;\n\n const record = readSiteRecord(deps.env, repoId, ref);\n if (!record) {\n const detail =\n `no site published for ${ref} (repo ${repoId}) yet — run ` +\n '`rig site publish` first (the manifest txid is only known after a paid publish)';\n if (flags.json) {\n io.emitJson({\n command: 'site url',\n repoId,\n ref,\n found: false,\n } satisfies SiteUrlJson);\n }\n io.err(detail);\n return 1;\n }\n\n const url = siteUrl(record.gateway, record.manifestTxId);\n if (flags.json) {\n io.emitJson({\n command: 'site url',\n repoId,\n ref,\n found: true,\n manifestTxId: record.manifestTxId,\n url,\n updatedAt: record.updatedAt,\n } satisfies SiteUrlJson);\n } else {\n io.out(url);\n }\n return 0;\n } catch (err) {\n return emitCliError(io, flags.json, 'site url', err);\n }\n}\n","/**\n * Arweave path manifest builder for `rig site` permaweb deploys (#368).\n *\n * MIRROR of `@toon-protocol/rig-web`'s\n * `packages/rig-web/src/web/deploy-manifest.ts` — copied rather than imported\n * because `rig` (a CLI) must not take a runtime dependency on `rig-web` (a\n * browser-only frontend). The two are intentionally kept in sync; this copy\n * additionally supports the manifest spec's optional `fallback` field (SPA\n * routing), which the site verb needs but the rig-web deploy script does not.\n *\n * Generates the JSON manifest ar.io gateways use to serve a multi-file\n * Arweave deployment as a virtual path-routed site: one manifest transaction\n * whose id becomes the site's canonical `https://<gateway>/<txid>/` URL.\n *\n * spec: https://specs.ar.io/arweave-standards/ao/index-1/manifest\n */\n\nexport interface ArweaveManifest {\n manifest: 'arweave/paths';\n version: '0.2.0';\n /**\n * Omitted when `indexPath` isn't one of the manifest's `paths` — an `index`\n * pointing at a path the manifest doesn't carry makes gateways 404 the site\n * root (indistinguishable from ArNS propagation lag; see #398).\n */\n index?: { path: string };\n /**\n * Optional SPA fallback: the transaction served for any path not present in\n * `paths` (e.g. client-routed `/about` on a single-page app). Omitted for a\n * plain static site.\n */\n fallback?: { id: string };\n paths: Record<string, { id: string }>;\n}\n\nexport interface ManifestEntry {\n /** Relative URL path, e.g. `index.html` or `assets/main.js`. */\n path: string;\n /** Arweave transaction id the file's bytes are stored under. */\n txId: string;\n}\n\nconst DEFAULT_INDEX = 'index.html';\n\n/**\n * Build an Arweave path manifest from a list of uploaded files.\n *\n * Each entry maps a relative URL path to the Arweave transaction id where\n * that file was uploaded. The resulting manifest is uploaded as its own\n * Arweave transaction; its id becomes the canonical URL for the deployment.\n *\n * @param entries path → txId for every file the site serves.\n * @param indexPath the path served at `/` (default `index.html`).\n * @param fallbackTxId optional SPA fallback transaction id (spec `fallback`).\n */\nexport function buildArweaveManifest(\n entries: ManifestEntry[],\n indexPath = DEFAULT_INDEX,\n fallbackTxId?: string\n): ArweaveManifest {\n const paths: Record<string, { id: string }> = {};\n for (const { path, txId } of entries) {\n paths[path] = { id: txId };\n }\n return {\n manifest: 'arweave/paths',\n version: '0.2.0',\n ...(Object.hasOwn(paths, indexPath) ? { index: { path: indexPath } } : {}),\n ...(fallbackTxId ? { fallback: { id: fallbackTxId } } : {}),\n paths,\n };\n}\n","/**\n * Local record of the last-published site manifest per (repo, ref) — the\n * lookup `rig site url` reads for FREE (#368).\n *\n * A site manifest's txId is only knowable AFTER the paid manifest upload (it\n * is the hash of the signed Arweave data item), and it changes every publish.\n * There is no free network lookup for \"the current manifest of this repo\"\n * until an ArNS name points at it (#367). So `rig site publish` records what\n * it just published here, and `rig site url` reads it back — no client start,\n * no relay query, no payment.\n *\n * Stored under `TOON_CLIENT_HOME` (default `~/.toon-client`) as\n * `site-manifests.json`, keyed by `<repoId>\\0<ref>` (local, single-user\n * scope — the owner pubkey is stored as a field, not part of the key). A\n * corrupt/unreadable file is treated as empty for reads and overwritten on\n * write, never fatal to a free lookup.\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nexport const SITE_MANIFEST_FILENAME = 'site-manifests.json';\n\n/** One recorded site publish. */\nexport interface SiteManifestRecord {\n repoId: string;\n /** Full refname the site was built from, e.g. `refs/heads/main`. */\n ref: string;\n /** Owner pubkey (hex) the manifest was published under. */\n owner: string;\n /** The manifest transaction id (43-char base64url). */\n manifestTxId: string;\n /** Gateway base the printed URL used, e.g. `https://arweave.net`. */\n gateway: string;\n /** Unix milliseconds of the publish. */\n updatedAt: number;\n}\n\ntype SiteManifestFile = Record<string, SiteManifestRecord>;\n\nfunction storeDir(env: NodeJS.ProcessEnv): string {\n return env['TOON_CLIENT_HOME'] ?? join(homedir(), '.toon-client');\n}\n\nfunction storePath(env: NodeJS.ProcessEnv): string {\n return join(storeDir(env), SITE_MANIFEST_FILENAME);\n}\n\nfunction keyOf(repoId: string, ref: string): string {\n return `${repoId}\\0${ref}`;\n}\n\nfunction readFile(env: NodeJS.ProcessEnv): SiteManifestFile {\n try {\n const parsed = JSON.parse(readFileSync(storePath(env), 'utf8')) as unknown;\n if (parsed && typeof parsed === 'object') return parsed as SiteManifestFile;\n return {};\n } catch {\n // Missing or corrupt → empty (a free lookup must never throw on this).\n return {};\n }\n}\n\n/** The recorded manifest for (repoId, ref), or `undefined` if none. */\nexport function readSiteRecord(\n env: NodeJS.ProcessEnv,\n repoId: string,\n ref: string\n): SiteManifestRecord | undefined {\n return readFile(env)[keyOf(repoId, ref)];\n}\n\n/** Record (or overwrite) the manifest just published for (repoId, ref). */\nexport function writeSiteRecord(\n env: NodeJS.ProcessEnv,\n record: SiteManifestRecord\n): void {\n const dir = storeDir(env);\n mkdirSync(dir, { recursive: true });\n const file = readFile(env);\n file[keyOf(record.repoId, record.ref)] = record;\n writeFileSync(storePath(env), `${JSON.stringify(file, null, 2)}\\n`, 'utf8');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBO,SAAS,yBAAyB,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AO,eAAe,MAAM,IAAI;AAAA,IAClC,KAAK;AACH,aAAO,UAAU,MAAM,IAAI;AAAA,IAC7B,KAAK;AACH,aAAO,WAAW,MAAM,IAAI;AAAA,IAC9B,KAAK;AACH,aAAO,WAAW,MAAM,IAAI;AAAA,IAC9B,KAAK;AAGH,aAAO;AAAA,QACL,KAAK,CAAC,MAAM,UAAa,CAAC,KAAK,CAAC,EAAE,WAAW,GAAG,IAC5C,OACA,CAAC,QAAQ,GAAG,IAAI;AAAA,QACpB;AAAA,MACF;AAAA,IACF,KAAK;AACH,aAAO,QAAQ,MAAM,IAAI;AAAA,IAC3B,KAAK;AACH,aAAO,WAAW,MAAM,IAAI;AAAA,IAC9B,KAAK;AACH,aAAO,SAAS,MAAM,IAAI;AAAA,IAC5B,KAAK;AACH,aAAO,SAAS,MAAM,IAAI;AAAA,IAC5B,KAAK;AACH,aAAO,QAAQ,MAAM,IAAI;AAAA,IAC3B,KAAK;AAGH,aAAO,MAAM,MAAM,IAAI;AAAA,IACzB,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,SAAG,IAAI,KAAK;AACZ,SAAG,IAAI,EAAE;AACT,SAAG,IAAI,UAAU;AACjB,aAAO;AAAA,IACT,KAAK;AACH,SAAG,IAAI,OAAO,WAAW,CAAC,EAAE;AAC5B,aAAO;AAAA,IACT,KAAK;AACH,SAAG,IAAI,KAAK;AACZ,aAAO;AAAA,IACT;AAGE,cAAQ,KAAK,UAAU,mBAAmB,MAAM;AAAA,QAC9C,KAAK,KAAK;AAAA,QACV,KAAK,KAAK;AAAA,QACV,KAAK,CAAC,SAAS,GAAG,IAAI,IAAI;AAAA,MAC5B,CAAC;AAAA,EACL;AACF;","names":["rigPage","parseArgs","parseArgs","mkdirSync","readFileSync","writeFileSync","homedir","join","parseArgs","join","homedir","readFileSync","mkdirSync","writeFileSync","removed","parseArgs","parseArgs","parseArgs","result","parseArgs","parseArgs","resolve","dirname","join","parseArgs","WS_URL_RE","parseArgs","dirname","join","parseArgs","STATUS_APPLIED_KIND","STATUS_CLOSED_KIND","STATUS_DRAFT_KIND","STATUS_OPEN_KIND","parseArgs","HEX64_RE","WS_URL_RE","defaultWebSocketFactory","repoATag","parseArgs","defaultReadStdin","COMMON_FLAGS_USAGE","HEX64_RE","COMMON_OPTIONS","pickCommon","parseArgs","STATUS_OPEN_KIND","STATUS_APPLIED_KIND","STATUS_CLOSED_KIND","STATUS_DRAFT_KIND","args","mkdirSync","readFileSync","writeFileSync","homedir","dirname","join","parseArgs","configPathFor","join","homedir","readFileSync","mkdirSync","dirname","writeFileSync","parseArgs","state","parseArgs","WS_URL_RE","parseArgs","readFileSync","homedir","join","parseArgs","CHAIN_ARG_LIST","join","homedir","readFileSync","parseArgs","resolve","mkdirSync","dirname","parseArgs","mkdirSync","dirname","parseArgs","basename","parseArgs","defaultWebSocketFactory","parseArgs","isWebSocketRelay","resolve","basename","parseArgs","HEX64_RE","runList","parseArgs","parseArgs","parseArgs","changes","parseArgs","spawn","parseArgs","spawn","receipt","result","parseArgs","runShow","runMutate","parseArgs","parseArgs","mkdirSync","readFileSync","writeFileSync","homedir","join","storeDir","storePath","readFile","parseArgs","receipt","require"]}
|