* Add Bugbot consensus review context Document the validation-state and sub-epoch-summary invariant so automated PR review has the same consensus context as local agents. * Route Bugbot to repository context docs Keep Bugbot guidance focused on subsystem context routing so automated reviews use the same module map as local agents. * Add generated repository context docs Include the expanded module context map and route Bugbot to the same subsystem docs used by local agents. * Add EDC agent context pointer Include the generated EDC agent guidance alongside the Cursor agent context docs. * Fold EDC guidance into AGENTS Keep agent context entrypoints consolidated in AGENTS.md and remove the separate EDC pointer. * Remove generator name from agent guidance Keep AGENTS.md focused on repository context locations rather than the tooling used to produce them. * Consolidate context corpus into one source-verified canonical set - Normalize all subsystem docs to canonical names without chia- prefix, removing the split between old and new-dominant corpora. - Merge new-dominant content into consensus.md, full-node.md, wallet.md; split networking.md into server.md, protocols.md, apis.md; add types.md. - Rename 15 genuinely-new subsystem docs; fold chia-root.md into architecture-overview.md. - Remove filter-branch leakage (filter_challenge, predictable filter, protocol 0.0.38) from types.md, protocols.md, harvester.md. - Correct factual inaccuracies: /push_tx vs wallet queue semantics, Err sign/ban policy, protocol import-time coverage, server peer-serving, address-manager mutation rule, wallet tx-store rollback, ValidationState speculative advancement, block-creation default, MempoolItem fallback. - Replace unreachable verification SHA with PR-head commit. - Consolidate test guidance into one small router plus 12 on-demand testing/ docs; remove duplicate auto-attached test guides. - Make INDEX.md the authoritative routing manifest; update BUGBOT.md, AGENTS.md, and context-routing.mdc to reference one canonical corpus. - Replace context-chia-*.mdc rules with canonical narrow rules; remove recursive .cursor/** rule and consolidate duplicate tooling rules. - Tighten clvm-execution.md: remove stale cost_calculator.py reference, fix block-creation default, replace opcode catalogue with pointer. * Trim redundant context and testing docs after value audit - Trim benchmarks.md: remove per-script Workload Groups narration that is obvious from opening each script; keep fidelity, coupling, and fragility sections. - Trim testing/patterns.md: slim to the module-by-module setup map and layered-assertion list; remove block/tx/assertion how-to that duplicates per-area testing docs. - Trim testing/full-node.md: slim to starter template and sync-convergence tip; remove fixture list and assertion patterns duplicated by patterns.md and architecture.md. - Fold testing/service-wiring.md per-cluster correlation details into testing/architecture.md; delete service-wiring.md (high overlap with architecture.md). - Fix protocols.md: correct NewSignagePointHarvester2 message-ID wording (ID reassigned to 66, not literally the same ID). - Update INDEX.md and testing-guide.mdc router to reflect service-wiring.md removal. * Fix verification SHA to reference the main source baseline The docs were verified against source at PR base24db9ad390(origin/main), nota5647a9327(the original PR head, which only adds context docs and is not a meaningful source baseline). The chia/ source tree is identical across both commits since the PR changes no production code. * Fix remaining V2 filter-branch leakage in harvester.md and types.md - harvester.md: replace calculate_effective_plot_filter_bits() and calculate_min_plot_strength() (filter-branch-only) with the actual main source path: calculate_prefix_bits() with NUMBER_ZERO_BITS_PLOT_FILTER_V2 and height adjustments, then passes_plot_filter(); strength bounds checked by check_plot_param() against MIN_PLOT_STRENGTH/MAX_PLOT_STRENGTH. - harvester.md: use meta_group (actual PartialProofsData field name) instead of "meta group". - types.md: correct that candidate height feeds prefix-bit reductions for both V1 and V2, not just V1; calculate_prefix_bits() branches on V1/V2 constants and height thresholds.
10 KiB
Chia Cmds Module Context
Verified: 2026-07-12 against 24db9ad390. If source contradicts this doc, trust source and update the doc.
chia/cmds/ is the user-facing CLI adapter layer. It owns command-line parsing,
local config/keychain setup, service/RPC client selection, terminal formatting,
and orchestration of daemon/service commands. It should not be treated as a
business-logic authority: most durable state, spend construction, consensus
validation, network behavior, and service lifecycles live in sibling modules and
are reached through config, keychain, daemon, and RPC boundaries.
When To Read This
Read this for CLI command parsing, Click/dataclass command wiring, config/keychain setup from commands, RPC-client selection, transaction-output files, service start/stop commands, and terminal-facing behavior. For endpoint side effects, also read the concrete service context.
Implementation Authority
chia.pyis the root Click command tree. It createsChiaCliContext, recordsroot_pathandkeys_root_path, configures the keyring root, optionally reads/caches a keyring passphrase, runs SSL permission checks, and registers every top-level command group.ChiaCliContextis the in-process CLI context authority. Commands read root paths, key paths, expected address prefix caches, RPC ports, and selected fingerprints from this object through Click'sctx.obj; avoid side channels for values that belong there.cmd_classes.pyis the newer dataclass-command DSL.@chia_commandfreezes a command class, turnsoption()fields into Click options, recursively expands@command_helperfields, injectsChiaCliContextonly for fields namedcontext, and runs sync or asyncrun()methods viaasyncio.run().- Plain Click modules remain common. Many commands are thin parser wrappers that
import their
*_funcsimplementation lazily and dispatch withasyncio.run(). This split is intentional for import cost and dependency isolation, but it means behavior can be split between a parser file and a sibling funcs file. cmds_util.get_any_service_client()is the generic RPC-client boundary for farmer, wallet, full node, harvester, data layer, simulator, and solver RPC clients. It loads config, chooses default ports, opens SSL or non-SSL clients, callshealthz(), and normalizes common connection/RPC errors for CLI output.start_funcs.pyandstop.pycross into the daemon websocket authority. The CLI launcheschia run_daemon --wait-for-unlock, unlocks the daemon keyring when needed, and starts/stops service names resolved fromchia.util.service_groups.
Command Execution Model
- Top-level options are applied before subcommand execution. Any code that needs
the selected root path, key root, or cached address prefix should read
ChiaCliContext.set_default(ctx)rather than re-resolving defaults. - Async commands assume no running event loop in the CLI process. Both plain
Click commands and dataclass commands generally use
asyncio.run()at the command boundary; nested event-loop ownership belongs below RPC/service code, not inside command parsing. - Parser modules should do CLI-specific validation and conversion only:
command-line shape, Click option types, basic argument consistency, user
prompts, file input/output, and terminal messages. Wallet, full-node, pool,
data-layer, DB, and keychain semantics should stay in sibling modules or the
*_funcs.pycommand implementation files. - Several commands deliberately lazy-import heavy dependencies inside functions. Moving imports to module scope can change CLI startup time, optional dependency failures, and command help behavior.
rpc.pyis an escape-hatch client. It dynamically adds one command per service, accepts raw endpoint names plus JSON request data, and bypasses typed service-specific command helpers. Treat it as an operational tool, not the canonical API contract.
Data Conversion Contracts
param_types.pyis the CLI conversion authority for fees, wallet amounts, addresses,bytes32, anduint64. Fees are decimal XCH strings capped at a source-defined XCH cap and converted to mojos; wallet amounts are stored asCliAmountuntil the target wallet unit is known.AddressParamTypevalidates the selected network prefix for XCH/TXCH addresses by consultingChiaCliContext.expected_prefixor loadingconfig.yaml. Non-XCH address families are mapped throughAddressType. Reusing it outside Click must account for possible config reads.CMDTXConfigLoaderandCMDCoinSelectionConfigLoaderbridge CLI amount/coin filters to walletTXConfigandCoinSelectionConfig, autofilling with consensus constants and wallet config/fingerprint data.tx_out_cmd()andTransactionEndpointare the transaction-output boundary. They add--push/--no-push, optional transaction-file output, coin-selection options, and absolute timelocks, then serializeTransactionRecordlists as aTransactionBundle. Commands that create wallet transactions should either use this path or explicitly document why their RPC shape is incompatible.TransactionEndpoint.__post_init__()enforces that subclasses decoraterun()with@transaction_endpoint_runner; this keeps file-output handling from being silently skipped in dataclass-style transaction commands.
Service And State Coupling
- Wallet commands are the widest surface.
wallet.py,coins.py,plotnft.py, andsigner.pyparse user intent, whilewallet_funcs.py,coin_funcs.py, andplotnft_funcs.pycallWalletRpcClient, format balances/transactions, resolve wallet units, and handle offer/NFT/DID/VC/notification flows. NeedsWalletRPC.wallet_rpc()centralizes wallet RPC selection and login. If no fingerprint is supplied,get_wallet()may query the keychain, inspect the wallet's logged-in key and sync state, prompt the user, then call walletlog_in(). This is observable behavior, not a trivial client factory.- Data-layer commands use
DataLayerRpcClientthroughdata_funcs.get_client()and can also log into the wallet by fingerprint. Some DataLayer transaction endpoints are not wired through the generic transaction-output decorators due to API peculiarities; observer-only/offline transaction behavior is therefore uneven across command groups. init_funcs.py,configure.py, and DB commands mutate local files. Config edits must uselock_and_load_config()for read-modify-write safety, and DB upgrade/backup/validate commands derive default paths fromfull_nodeselected-network config.- Key commands operate on local key custody.
keys_funcs.pyunlocks the keyring, adds private or observer keys, displays derived keys/addresses, signs and verifies messages, and updates config reward targets throughinit_funcs. Treat--show-mnemonic-seedand file-based key input/output as sensitive terminal/file surfaces. - Pool/plot NFT commands cross three authorities: wallet RPC, farmer RPC, and external pool HTTPS endpoints. Mainnet pool joins enforce HTTPS and pool protocol/relative-lock-height checks before wallet RPC submission.
Fragility Hotspots
- Mixed command frameworks create duplication: old Click decorators, helper
decorators in
cmds_util.py, and dataclass helpers incmd_helpers.pycan express similar options with subtly different defaults, names, and timelock visibility. get_any_service_client()consumes many errors by printing and not re-raising unlessconsume_errors=False. Tests rely on this distinction; callers that need programmatic failure must opt out of consumption.- CLI-facing validation is often user-experience oriented rather than complete domain validation. Do not rely on parser checks as wallet, consensus, or DB safety checks.
- Several commands use
sys.exit(),print(),input(), andclick.Abortdirectly. This is expected for terminal UX but makes library reuse and tests sensitive to stdout/stderr and prompting behavior. - Address-prefix caching in
ChiaCliContextis per Click invocation. Changes that bypass context can re-read config repeatedly or validate against the wrong network. - DB upgrade and config commands perform irreversible-looking filesystem operations, but usually leave original DBs untouched or require explicit output paths. Preserve those guardrails and user confirmations when changing operational commands.
Test And Audit Strategy
- CLI tests usually use
click.testing.CliRunner, temporary Chia roots, and monkeypatched RPC client factories fromchia/_tests/cmds/cmd_test_utils.py. Prefer mocked RPC clients for command parsing/dispatch tests over simulator harnesses unless the behavior truly depends on chain state. test_cmd_framework.pyprotects dataclass parsing, helper recursion, context injection, optional/sequence type handling, and transaction-endpoint invariants. Extend these when changingcmd_classes.pyorcmd_helpers.py.test_click_types.pyprotects amount/fee/address/bytes32/uint64 conversion, including network-prefix validation and decimal precision. Any change toparam_types.pyshould update these cases before broad wallet command tests.test_cmds_util.pyprotects RPC-client creation and error-consumption semantics. Changes to connection handling should test both consumed and propagated error modes.- Wallet command tests assert RPC request shapes and terminal output using test
RPC clients. When adding transaction-producing wallet commands, include both
--push/--no-pushand transaction-file behavior if the command participates in the standard transaction-output path.
Source Pointers
- Root CLI and command context:
chia/cmds/chia.py,chia/cmds/cmd_classes.py,chia/cmds/cmd_helpers.py. - Common RPC/config/keychain helpers:
chia/cmds/cmds_util.py,chia/cmds/init_funcs.py,chia/cmds/configure.py. - Wallet and transaction command surfaces:
chia/cmds/wallet.py,chia/cmds/wallet_funcs.py,chia/cmds/coin_funcs.py,chia/cmds/param_types.py. - Service control commands:
chia/cmds/start_funcs.py,chia/cmds/stop.py,chia/cmds/rpc.py.