Skip to content

Ledger 9 and the beta engine (draft, for CI) - #10

Merged
nel349 merged 88 commits into
mainfrom
merge/ledger-9-main
Nov 12, 2026
Merged

nel349 merged 88 commits into
mainfrom
merge/ledger-9-main

Conversation

@nel349

@nel349 nel349 commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Draft, not for merging: opened so CI runs on this branch.

This branch brings the ledger-9 line onto main's history and adds a second SDK engine:

  • Two SDK engines. @kuiralabs/midnight-engine-rc (preprod, preview, undeployed) and @kuiralabs/midnight-engine-beta (stagenet). The network picks the engine; mn config set sdk-set <rc|beta> [--network] overrides it.
  • Wallet session. One interface for addresses, balances, balancing, swaps, signing and submitting, used by mn serve, grants and outside programs.
  • Stagenet. Reads, Dust registration, transfers, contract deploy and calls (compactc 0.33), verified live.
  • Release. The published package ships an npm-shrinkwrap.json built from package-lock.json, so a user install gets the tree the tests ran on. Each engine refuses to load if its SDK packages reach more than one ledger copy (MIXED_SDK_LAYOUT).
  • CI. Runs the rc and beta test suites as separate steps.

https://claude.ai/code/session_01XQWkwdzqCkXVWeFrvJZ8RQ

nel349 added 30 commits November 1, 2026 15:33
Cancelling a contract deploy or call, a paying grant command, dev's
deploy or a test run's prep did nothing while the paying wallet was
checked, synced or served: the call kept syncing (minutes of Dust on a
hosted network) and held the serve's port until the script step.

The Payer's methods take the paying call's signal. The funds check
passes it to the repository's reads; the serve and the in-process
connector pass it to the Dust warm-up, the facade sync and the Dust
wait, stop what they started, and fail with CancelledError. Test prep
starts no step after a cancel and hands the signal to its waits.
Commands and libraries threw a plain Error carrying the cancellation
message, which only came out as CANCELLED because the exit-code
classifier matched its text. They throw CancelledError now (its code is
CANCELLED); grant's own copy of the check is gone. The runner's and the
subscription's tests ask for the type, not the text.
The check reported the shell's and the MCP server's imports but failed
on none of them, a deferral that waited for the command registry, and
nothing ran the check but a hand. The shell may import every package
and the MCP server; the MCP server may import core, the shell's host
and runner, and connect's serve payer, and nothing else. No package may
import either. The suite now runs the check, with tests of the rules;
--all, which only failed the deferred imports too, is gone.
The shell kept help's order as a list of every command's name, a second
list of commands next to the registry. Each definition now holds its
place, as its intro line and its tools already do, and the registry
refuses two commands in one place; a plugin's command takes its own.
Help, the manual and the snapshot are unchanged.

The manual's config keys and help --json's global flags stay prose, now
with tests that fail when config accepts a key the manual doesn't
describe, or the shell a global flag help doesn't list.
captureCommand ignored the outcome a handler returns, so a command that
fails by returning an exit code instead of throwing (a test run whose
tests failed, a status that finds a network down) would reach an agent
as a success. It throws CommandFailedError now, with the code and the
result the command wrote. No tool runs such a command today.
Source comments, test names and script comments cited internal
planning IDs and documents that readers of this repository can't
see. Each now says what the reference meant, or drops it where the
sentence stands alone.

Also corrects stale comments: verbose is per call, not process-wide;
status is dispatched only to be refused while it is reworked; the
wallet migration comment sits by its call; the MCP server exposes the
installed commands' tools, not every command.

Three test constants named after plan steps are renamed to say
"before the registry". No behaviour changes.
Only two of the nine confirmed tools were run through the real server,
and the registry test checked a type, so dropping a confirmation from
transfer, contract or grant left the suite green. Each confirmed tool
now answers its first call with a token and its exact description,
leaving the home as it was, and the registry pins the set of confirmed
tools.
The refusal was tested as a function only. These run the CLI's entry
point: an unknown flag is exit 2 with INVALID_ARGS before the command
runs, known flags reach the command, and --help skips the refusal.
captureCommand fell back to a router of its own when no SDK warnings
were passed, so a host that stopped passing its own would lose every
SDK warning of its calls with nothing failing. The warnings are now a
required part of the run; tests that run a command outside a host pass
a router of its own explicitly.
A cancelled contract state fell back to the raw-state query instead of
stopping, and that query, which takes no signal, waited for ever on an
indexer that never answered. A cancelled call now ends there, and the
fallback stops waiting when the call is cancelled.

New tests cancel transfer (both kinds), airdrop, dust register and
status, contract deploy, call and state, grant deposit and serve while
their first network read hangs, and expect CANCELLED well inside the
time limits they would otherwise wait out.
Nothing compared a command's --json fields with the ones its definition
declares. For the commands that need no network, every field written
must now be one help names. wallet and generate write fields their help
predates; those are listed in the test, exactly, until help is
corrected, so the drift can't grow unnoticed.
It swallowed both calls' errors, so it passed if the quiet call failed
before the point where a verbose call writes its first diagnostic. Both
calls' failures are now checked, and the verbose one's diagnostic.
…confirmed

Over MCP, wallet_generate with force replaced a wallet's seed with no
confirmation, and force "false" counted as force: any value but false
set the flag. airdrop's shielded and dust status's no-cache were strings
the same way, so "false" switched them on.

- force, shielded and no-cache are booleans in their tools' schemas, and
  the server refuses a parameter whose value isn't its schema's type
  (INVALID_ARGS): a boolean must be true or false, a string a string or
  a number, a listed value one of the list.
- A tool's confirmation may say which calls need it (when). Generate
  asks only with force: true; the text says whether a wallet is replaced.
- trueStrings goes: no tool reads a switch as a string any more.
- Deleted, approved: toolPassThroughFlags (superseded by the schema),
  help.ts's unused INDEXER_GRAPHQL_WS_PATH import, and OutputSink, which
  was CallOutput again.
- Guidance tells agents shielded: true.
The text a user confirms named the network but not an endpoint given
as a parameter or set with config, so a transfer's proof could go to a
host the user never saw. Each endpoint other than the network's own is
named now: given ones as given, configured ones marked "set with
config". A tool that takes no endpoints reads as before.
It showed the general help, and on a subcommand line (mn wallet
generate --help) asked help for "generate", which isn't a command.
Now it shows what mn help <command> shows, whatever else is on the
line; --help alone, after an unknown command or with --json (the
manifest) reads as before.
mn dust register --seed x ran and ignored the seed; the MCP server
already refused it. The shell now refuses, before the command runs, a
flag the command accepts but its subcommand doesn't read, naming the
subcommands it is for (INVALID_ARGS, exit 2).

The definitions' scopes are made to match what the handlers read: wallet
list and info read --network, test results reads --suite, and test's
--network and --path are read by create only (run and results find the
dApp from the working directory, so --path there was silently ignored).
A definition may name its subcommands' aliases (wallet's ls and rm).
help --json and the agent manual described fewer fields than wallet
writes (addresses, seed, file, createdAt, …), and named two generate
doesn't write (address, network). Both now list what each subcommand
writes, and the test that listed the gap checks there is none, with
wallet seed, remove and protect added to its runs.
skill/full said every CLI command is an MCP tool and pointed to
mn status, which isn't a command; both skills named other packages'
tools as examples and told agents only transfers are confirmed.

- The confirmed tools (both skills' safety rules and the manual's
  confirmation flow) and the commands no tool runs come from the
  registry.
- What each package does, the localnet refusal and the WASM Dust note
  are the packages' own lines, gone with the package.
- A package may add sections of its own to the three texts, each after
  one the text has (or another package added).
- References name mn help --json instead of mn status.
It lacked grant. It is now written between markers by npm run
readme-commands, one row per command help lists, with its help's usage
and description, and a test fails when the README differs. The table
says less than the hand-written one did (per-subcommand rows, flag
notes); mn help <command> and mn manual carry those.
The wallet SDK reports a refused transaction as "Transaction submission
error" and keeps the node's words only among its causes, inside an
Effect FiberFailure; mn reported UNKNOWN (exit 1), and the reason
(an invalid Dust proof) was only in the node's log.

The CLI and the MCP server now report such an error as a
TransactionRefusedError, "The node refused the transaction: <reason>",
classified by the reason when a rule knows it (Custom error: 170 is
INVALID_DUST_PROOF, 115 STALE_UTXO) and as TX_REJECTED (exit 6)
otherwise. Retry logic still sees the SDK's own error.
Phase E's first step: everything that touches the SDK moves behind one
engine interface, reached through the engine for a network's SDK set.

- lib/engine.ts (core, SDK-free): the interface, which grows area by
  area, and the loader. engineFor(network) loads the network's engine
  on first use, one per process; anyEngine() is for work every set does
  alike. One set today, rc.
- engine/rc: the rc engine. Key and address derivation moved into it.
- Wallet creation and loading derive addresses through the engine, so
  createWallet, loadWalletConfig, listWallets and their callers are now
  async. The address commands and localnet use the engine.
- The layering check gives the engine its own home: only core's loader
  reaches it, it reaches only core and chain, and only an engine may
  import the SDK. The modules that still do are listed, and a test pins
  the list so it only shrinks.

No behaviour changes: the suite passes and the snapshot is unchanged.
- The block limits in a chain's ledger parameters are the engine's
  (ledger.blockLimits); chain-params only reads the bytes from the
  indexer, and inspect-cost asks the engine for the chain's set.
- The fee-only check and the transaction summary for approval prompts
  move into the rc engine as they are: only the connector and the sign
  recipe use them, and both move behind the engine later.

Four modules leave the pending list. No behaviour changes: the suite
passes and the snapshot is unchanged.
- mn's own Dust and shielded readers, their caches, the Dust collapse
  and the native sidecar's glue move into the rc engine. So does the
  unused direct Dust balance reader, as it is (deleting it is for the
  owner to approve).
- Where the readers keep their caches, and clearing them, needs no SDK:
  it is reader-cache-files.ts in core, beside wallet-cache.ts and
  cache-indexer.ts, which the engine uses and which move to core with it.
  mn cache clear names caches through the engine's keys
  (dustPublicKeyHex, shieldedCoinPublicKeyHex), and so do dust export
  and wallet protect.

Seven modules leave the pending list. No behaviour changes: the suite
passes and the snapshot is unchanged.
- contract state's raw fallback asks the engine (contracts.rawState),
  which reads it with its own midnight-js provider and returns plain
  JSON; the raw-state reader and the provider move into the engine.
- A transfer's recipient is checked by the engine (keys.assertAddress);
  the transfer command still decodes it with the engine's own function
  until the transfer moves.
- grant's private-state password is drawn until the engine's policy
  (midnight-js's) accepts it, instead of grant importing midnight-js.
- test prep reads NIGHT's token id from the engine.
- The connector's wire types (error codes, APIError) are owned by its
  transport, with a test keeping them equal to the DApp Connector API's.

Five modules leave the pending list (twelve left). No behaviour
changes: the suite passes and the snapshot is unchanged.
The scripts mn runs in a dApp's folder (deploy, call, state) and the
packages they import are set-specific: they move into the rc engine,
with the packages found from the engine's own install. What every
set's script shares (the failure prelude, mn serve's RPC client, the
argument and secret helpers, the witness locations, the indexer's
environment names) stays with the runner and reaches the engine as
ScriptParts. The runner asks the network's engine for the script and
links that engine's packages into the dApp, so its options now name
the network.

The runner leaves the pending list (eleven left). No behaviour
changes: the suite passes and the snapshot is unchanged.
Before the wallet core moves behind the engine, what it uses that needs
no SDK becomes reachable from an engine (which may use only core and
chain):

- The connector's wire protocol (the API's errors, the handler types,
  createApiError) is connector-api.ts in core; ws-rpc keeps the
  WebSocket server and re-exports them.
- The approval prompt, fee limits, transaction hex, data signing, the
  Dust wait and the Dust balancing and registration plans depend only on
  core, and now sit there; the transaction segments' reader sits in
  chain.
- dust.ts loses three imports it never used (the ledger, the Dust seed
  and the Dust key helper), which is all that kept it on the pending
  list (ten left).

No behaviour changes: the suite passes and the snapshot is unchanged.
…he engine

balance takes its addresses, NIGHT's token id and the shielded balance
(readers.shieldedBalance, mn's own reader, now on the engine) from the
engine for its network, and imports no SDK. Nine modules left on the
pending list. No behaviour changes: suite and snapshot unchanged.
… the SDK

The wallet core moves into the rc engine: the facade, the Dust wallet,
the fork schedule, transfers, the sign recipe, the DApp connector, the
wallet repository, Dust registration and export, and the genesis
airdrop. Everything else reaches it through engine.wallet, whose
methods take and return mn's own types:

- balances (unshieldedBalance, dustBalance), transfer, airdrop,
  registerDust, exportDust: the functions that existed, behind the
  interface;
- shieldedTransfer: the shielded flow transfer and airdrop each ran
  themselves, once, with their own messages passed in;
- prepNightBalance and prepDust: test prep's quick-sync checks;
- openConnector: serve-manager's connector for mn's own commands;
- serveWallet: mn serve's strictly synced wallet, with its Dust wait,
  its save (skipped while transactions are pending) and its connector.

The wallet's public types (transfer and Dust parameters and results,
balance views, the connector's shape and callbacks) are the interface's,
in core. The pending list is empty and gone: the layering check now
refuses an SDK import anywhere but an engine.

No behaviour changes: the suite passes and the snapshot is unchanged.
core's engineFor loaded the rc engine by relative path, which a core
package can't. Now the host installs a loader at start, as it does the
settings and the state root: the shell's installed-engines.ts lists the
engines this build ships, and only it may import one. Tests install the
same loader. No behaviour changes: suite and snapshot unchanged.
An engine is its own package (Y32) and uses core, which has to be one
copy shared with the shell (Y33). So core's modules (arguments, typed
errors and exit codes, JSON output, config and its command, the state
root, network endpoints, terminal formatting, the registry contract, the
payer and the engine interface) move to packages/cli-core, a workspace
package mn depends on, 0.1.0-rc.0. Everything else imports them by name.

- In this repository the package runs from its source, under the
  midnight-cli-source export condition (tsc, vitest, and NODE_OPTIONS for
  what tests start; the tsx scripts pass it). Published, its exports
  resolve to its build (tsc to dist, with declarations), which mn's build
  makes first.
- The layering and process-safety checks read the package's source as
  they read src/, and refuse a relative import out of a package.
- The clean-install check packs the workspace packages mn depends on,
  installs them with it, and checks there is one copy of each.
- The SDK-free checks no longer count our own packages as SDK.
- A stale path in scripts/measure-preprod-dust.ts is fixed.

No behaviour changes: suite (2255) and snapshot unchanged, clean
install works. Publishing @kuiralabs/midnight-cli-core comes before the
next mn release.
nel349 added 26 commits November 3, 2026 09:15
Each failure a message rule used to classify now carries its code
from where it is thrown: WalletNotFoundError, InsufficientBalanceError
and DustRequiredError (the engines throw the balance one too), and in
chain SyncTimeoutError from the readiness probes and NetworkError or
IndexerUnreachableError when a node or indexer can't be reached. A
timed-out program keeps NETWORK_ERROR through its code.

Approved changes: thirteen bad-argument sites throw UsageError (Y52),
shown as yellow "Usage"; a wallet with no NIGHT reports
INSUFFICIENT_BALANCE, an unreachable indexer or node NETWORK_ERROR
whatever its text, and a failed test-run prep step keeps its step's
code (Y53). Each site has a parity row checked by code alone.

Snapshot unchanged against baseline-3c2; suite 2657, beta 172.
…6 of 8)

The engine contract in core recognises the SDK's and the node's text
in one place (toEngineError) and turns it into typed errors: proof
timeout and failure, stale UTXO (refusal 115), invalid Dust proof
(170), stale wallet state, Dust shortage and insufficient funds; a
refused transaction carries a code chosen from the node's reason.
Only the engines and core's wallet session use it. Both engines'
wallet methods raise typed errors after their own retries.

Across process and wire boundaries the code travels with the error:
the contract script writes {message, code} on its failure line and
the runner rebuilds it; the connector's RPC carries mn's code as
data.mnCode beside the connector API's own code, which dApps read and
which is unchanged. grant reads the error's code.

Approved (Y54): a ZK proof that times out reports PROOF_TIMEOUT, and
a contract script's refused transaction TX_REJECTED (or the stale-UTXO
or Dust-proof code) whatever the node's wording, as in-process does.

Suite 2702, beta 180; snapshot unchanged; fresh install; scratch
chain final pass 84/84 in a clean runner (the rig's MCP tool count
updated to 44), swap 30/30, MCP swap 12/12, tx 25/25; stagenet reads.
The message fallback is gone: classifyError looks the error's code up
in the installed packages' registry, and an error with none is
UNKNOWN. What still had to be read from text is read once, at the
boundary that meets it: transport failures (refused, not found, timed
out, fetch failed) become NETWORK_ERROR at the engine boundary, inside
a contract script and in grant. A test fails if classification reads
an error's message.

Every code definition carries its recovery and order, and each
package's agent-manual and skill rows, the manual's exit-code list and
docs/JSON_CONTRACT.md's table are generated from them.

Approved: errors whose code came only from an accident of wording now
report UNKNOWN (Y52); an unreachable service reached through the
engine or a contract script reports NETWORK_ERROR (Y55); the code
tables are generated (Y52).

Suite 2732, beta 180; snapshot changes only in the three generated
tables; scratch chain final pass 84/84 in a clean runner, swap 30/30,
MCP swap 12/12, tx 25/25; stagenet reads.
Each command definition declares the error codes it can end with,
its own and named sets each package exports (network, wallet,
engine, sync, paying, offers, chain), and outcomes it returns without
an error; its exit codes follow from the registry. The registry
refuses a code no installed package defines.

scripts/code-reach.mjs walks each command's handler and what it
imports and collects every code it can throw; declared-codes.test.ts
fails when a reachable code is undeclared or a declared one can't be
reached. The command-running tests also check each error a command
ends with is declared.

Shown (approved, Y56): mn help <cmd> and the manual's command pages
list the command's own codes and name its sets; help --json carries
errorCodes, exitCodes and errorSets; the agent manual and the full
skill list the sets once; each MCP tool's description ends with its
own codes and set names (7 to 18 words).

Suite 2758, beta 180; fresh install; the snapshot changes only in
help, help --json, the manuals and the MCP descriptions.
A program calls what a command does with plain values: shared shapes
in core (networkTargetOf from a network choice, ProgressEvent and the
spinner adapter, WalletSource as a wallet name or path or a seed,
seedOf) and chain's transactionStatus; then readAddressBalance and
readWalletBalance, and readDustStatus, registerDust and
exportDustSnapshot in src/lib/wallet/. The balance, dust and tx
handlers only parse, call and print. Amounts are bigint.

Small changes in edge cases: balance through MCP now sends progress
notifications on the wallet path (its result is unchanged); an
invalid --seed together with an invalid --network reports the seed
first; dust register --no-cache is refused before the wallet unlocks
(the shell already refuses that flag there).

Suite 2798, beta 180; snapshot unchanged; fresh install; scratch
chain swap 30/30 and tx 25/25 (dust register with its receipt);
stagenet balance and Dust status read.
transferNight and airdropNight in src/lib/wallet/ do what the
transfer and airdrop commands did, with plain values, a progress
callback and the receipt; the handlers only parse, call and print.
transferNight keeps the domain's rule itself: a shielded transfer on
preview, preprod or stagenet is refused unless forced, before the
wallet unlocks (one check, shared with the CLI and MCP confirmation).

Amounts are exact bigints end to end (Y58): parseAmount reads the
decimal into the smallest unit without a JS number, and the engine
contract's transfer and airdrop amounts are bigint in both engines.
An amount that was refused as too many digits to handle exactly is
now taken exactly (grant deposit too). The --json amount stays a
number, as before.

Suite 2838, beta 184; snapshot unchanged; fresh install; scratch
chain swap 30/30 and tx 25/25 (transfers and airdrops, shielded and
not, with receipts), after the scratch node was restarted when
Docker's disk filled.
…f 8)

deployContract, callContract and readContractState take the host, a
plain request (contractDeployRequest / contractCallRequest; no
library reads the working directory), a payer and a progress
callback, and do the runtime check themselves; mn dev deploys through
the same builders instead of a made-up argv. makeSwapOffer,
inspectSwapOffer, takeSwapOffer, cancelSwapOffer and listSwapOffers
take offer text and give file text; take and cancel wait for the
receipt. The session-level makeOffer, takeOffer and cancelOffer stay
public. A test holds every in-scope handler to its library calls,
with no engine, payer or receipt calls of its own.

Edge cases that changed: a bad --args JSON is reported before a
missing contract; in swap, a bad network after bad terms or a missing
offer file, and NO_PAYER before the heading; dev deploy refuses a
contract built for another runtime before checking the wallet; the
swap's "Opening the wallet" step ends with its tick line; --json and
MCP progress include each step's first message.

Suite 2892, beta 184; snapshot unchanged; fresh install; scratch
chain final pass 84/84 in a clean runner, mn dev 8/8, swap 30/30, MCP
swap 12/12, tx 25/25; stagenet reads.
Each public package states its API through named entry points, and
the open "./*" goes: core "." (the library API), "./engine" (for
engine implementors), "./ui" and "./commands"; chain "." and
"./commands"; each engine "." only. Every importer uses them.

Tests of a package's internals moved into that package (core 37,
chain 12, engine-rc 24, engine-beta 6 test files), so no name is
public only because a test needed it; suites both engines run, and
the test host and stand-ins, sit in test-support/, which imports
packages only by entry point. Published manifests carry no source
paths: scripts/publish-manifest.mjs strips the development
condition, and the release job publishes the tarball. The layering
check resolves imports through exports maps and refuses a deep
import across packages, in code, tests and scripts; the code scan
and the API reports follow the entry points' re-exports.

scripts/measure-preprod-dust.ts is removed (with the owner's word):
it had not run since before phase 3.

Suite 2911, beta 184; snapshot unchanged; fresh install, where a
deep path into core, chain or an engine is refused
(ERR_PACKAGE_PATH_NOT_EXPORTED); scratch chain final pass 84/84 in a
clean runner, swap 30/30, MCP swap 12/12, tx 25/25; stagenet reads.
@kuiralabs/midnight-wallet holds the wallet commands (wallet,
generate, address, genesis-address, info, balance, transfer, airdrop,
dust, cache) and swap, their codes and guidance, and the wallet
libraries: passphrase, seeds, wallet files, the 3E library functions
and swap offers. Its entry points: "." (the library API, 99 names)
and "./commands" (the definitions, codes, guidance and showPaidStep).
mn's registry keeps its entries and order, so help and the manuals are
unchanged.

Dependencies, as approved (Y59): the wallet package declares core,
chain and @scure/bip39 (moved from mn's root, same range); mn's root
declares the wallet package instead. The lockfile keeps every other
entry's resolution and integrity.

wallet remove's confirmation imports readline statically (a require
worked only inside the bundle).

Suite 2916, beta 184; snapshot unchanged; fresh install (one copy,
both entry points load, a deep path refused); scratch chain swap
30/30, MCP swap 12/12, tx 25/25; stagenet reads.
@kuiralabs/midnight-connect holds serve, the serve manager, the serve
payer and the RPC server; @kuiralabs/midnight-contract holds contract
and inspect-cost, the runner and the 3E contract functions;
@kuiralabs/midnight-dev holds dev, test and localnet. Each has "." and
"./commands"; mn's registry keeps its order, so help and the manuals
are unchanged. connect comes before contract: a contract test of a
script failing at mn serve needs connect's RPC server.

Dependencies, as approved (Y59): connect declares ws (moved from mn's
root, same range); contract and dev declare the workspace packages
they import; mn's root declares the three packages. Every other
lockfile entry keeps its resolution and integrity.

The clean-install check now runs the installed contract package's
runner on a compiled fixture for each engine: every script package
is found by name and the script loads the dApp's contract.

Suite 2933, beta 184; snapshot unchanged; fresh install; scratch
chain final pass 84/84 in a clean runner, mn serve probe (reads,
signData, a transfer submitted, refusals), mn dev 8/8, swap 30/30,
MCP swap 12/12, tx 25/25; stagenet reads.
@kuiralabs/midnight-grant holds grant and its accounts, with "." (the
account protector, its errors and record paths) and "./commands". Its
error classes sit in a module with no SDK, so wallet list, which
loads grant's protector entry, still loads no SDK. Dependencies as
approved (Y59): grant declares @kuiralabs/midnight-account and
-account-chain (moved from mn's root, same versions) and ships its
own shrinkwrap, which pins the rc engine's SDK copies; the lockfile
keeps every other entry.

Closing: the release job publishes every package in dependency order
(core, chain, the engines, wallet, connect, contract, dev, grant,
then mn); the clean-install check proves every public package
installs, has no source paths, and refuses a deep import; the
package metadata and API report tests cover all of them.

Suite 2960, beta 184; snapshot unchanged; fresh install 111 checks;
live gate from a fresh runner (fresh.sh): final pass 84/84, mn dev
8/8, stagenet pass 18/18, mn serve on stagenet (a transfer, bob
116 to 123 NIGHT).
Each engine declares @kuiralabs/midnight-account-chain (one package
for both SDK sets, its SDK as peer dependencies, as approved in Y60)
and exposes it as engine.account(); grant reaches it only through the
network's engine, so each engine's copy resolves to that engine's SDK
set: the rc copy loads the Account build (caller pin), the beta copy
the AccountStagenet build (none). The workspace lockfile nests the
beta copy under engine-beta; each engine's load refuses a shared copy
(MIXED_SDK_LAYOUT), and the clean-install check proves each copy
resolves its own engine's ledger and runtimes.

A grant request that names a caller is refused on stagenet before any
transaction: CALLER_PIN_UNSUPPORTED, exit 2, declared on grant (the
package's own CallerPinUnsupportedError classifies the same).
Grant's network check, help and MCP enum now name stagenet.

Pinned at 0.3.0-rc.1, whose stagenet build ships without its proving
keys; stagenet grants complete when 0.3.0-rc.2 and its key release are
out (part 2).

Suite 2973, beta 193; fresh install 130 checks; scratch chain: final
pass 84/84 from a fresh runner, and a grant account deployed and
activated with the installed build (185d1177…1442).
Core gains "./process", the only package code that touches the
process, and only when a host calls it: installSdkProcessGuard (the
guard against the wallet SDK's transient rejections during sync, with
its console filter as an option; a rejection no call listens to is
reported by default, and mn keeps exiting) and syncHeapAdvice /
syncHeapTargetMb (the heap a cold sync needs). mn's shell uses them;
no package source may import it. openWalletSession is exported from
core's "." with an sdkWarnings option, listening until close().

Both engines now let a program end after session.close(): the facade
opens its node submission client only on the first submit (a node
that is down kept a never-submitting session reconnecting forever),
and stopping the facade clears its 5 s race timer. Child-process
tests hang before and end in about 40 ms after.

packages/cli-core/README.md, "Your process", shows a program's setup
and what mn's shell does that a program must do; a test runs its
setup block. A child-process test proves a floating Wallet.Sync
rejection kills a program without the guard and not with it, on Node
and bun.

Suite 3000, beta 195; snapshot unchanged; fresh install (an outside
program loads ./process); live gate from a fresh runner: final pass
84/84, mn dev 8/8, stagenet pass 18/18.
Both engines pin @kuiralabs/midnight-account-chain 0.3.0-rc.2, whose
stagenet build ships its proving keys (release build-a5c87559dc483e58
on kuiralabs/midnight-account-artifacts). The beta engine keeps its
own nested copy (npm dedupes it away on install; the lockfile entry
is restored and each engine's load refuses a shared copy).

Suite 3000; fresh install: each engine's copy resolves its own ledger
and runtimes. Live on stagenet (beta engine), wallet stage2: grant
deploy activated, status and list answer, the artefacts fetched are
the stagenet build's.
grant deposit takes --token <type> (the raw shielded token type, 64
hex, as mn balance lists it): the amount is then in the token's
smallest unit, read exactly as a bigint, and the account package's
deposit gets the type's 32 bytes as its color. Without --token it is
NIGHT, exactly as before. The pre-check reads the chosen token's
shielded balance and names it when short. MCP's
midnight_grant_deposit takes an optional token.

Fix: a deposit now asks its wallet for the shielded side synced, as
swap does. On stagenet the wallet skips the shielded sync by default,
so a deposit read 0 of every shielded token and refused (regression
test fails without the fix).

Suite 3021; live on stagenet: 5 of test token bb2e…8cdb deposited
into stage2's account (block 1165106), which then holds 5.
mn grant on stagenet, grant deposit of any shielded token, mn split
into packages with named entry points and library functions, error
codes owned per package, the host passed in, and engines that let a
program end. Every @kuiralabs workspace package moves to the shared
0.1.0-rc.2; mn to 0.6.0-rc.13.
…ion (3H, part 1)

A program that mounts our commands in its own command line or MCP server
had to copy mn's glue. core now exports it (Y63):

- runCommand(definition, args, run): what mn's shell does around a handler.
  It refuses an unavailable command, writes its notice, loads its handler,
  gives the payer or protectors (a value or a loader) only when the
  definition asks, and runs it as one call of the host.
- captureCommand(definition, args, run): the MCP form, in --json and
  agent-slim mode. The result is kept per call, the person's text goes to
  run.text, and a non-zero exit becomes COMMAND_FAILED.
- toolDescription(registry, tool): a tool's description with its codes.
  listedNames moves to agent-guidance.

mn's dispatch and MCP tools now call these, and src/lib/run-command.ts is
gone. The generic tests moved to core. Behaviour snapshot unchanged
against rc.13 (new baseline recorded); suite green.
…art 2)

- Each public package has a README (Y63): install, entry points, what you
  call, its codes, and one example that mounts its commands (an engine's
  shows loading). Core's README adds "Mounting commands in your program",
  and mn's README a section for programs.
- The codes tables are generated (npm run package-readmes) and checked.
  package-readmes.test.ts runs every example as written, in a child
  process with its own home: config under ~/.my-app, a generated wallet,
  and typed errors (WALLET_NOT_FOUND, NETWORK_ERROR, CONTRACT_NOT_COMPILED,
  NO_TEST_CONFIG, NO_ACCOUNT), plus each engine loaded by its network's set.
- Each package's ./commands exports its registry entry: coreCommands,
  chainCommands, walletCommands, swapCommands, contractCommands,
  connectCommands, devCommands, grantCommands. mn's registry is built from
  them. The README test found that a registry needs the entries of the
  packages a package builds on, which the examples now show.
- Y64: "No compiled contract found" is now CONTRACT_NOT_COMPILED
  (contract, dev, test), and "No dapp.test.json found" is NO_TEST_CONFIG
  (test); both were UNKNOWN. Exported as ContractNotCompiledError and
  NoTestConfigError, with regression rows in error-code-parity.

Suite 3058 green, beta 195. The snapshot against rc.13 differs only by the
two codes.
Found by the consumer project: a mounted command run without --json drew
its spinners on the process's stderr, whatever output the program gave
runCommand. createProgress and start now take where to draw, and a call's
progress draws through the call's output.stderr. mn's shell output is the
process's stderr, so mn draws the same bytes (snapshot unchanged). The
regression test in core's run-command tests fails without the fix.
Found by the consumer project: on bun, a contract deploy from a program
failed because the Node-run script couldn't import ws. bun answers
require.resolve('ws') with its own module, not a file, so the engine
linked no ws into the dApp. packageFolder (both engines) now looks in
the node_modules folders above the engine when the runtime answers with
something that isn't a file, which is where Node's resolution finds it.
The bun regression test fails without the fix. Node is unchanged.
Both engines pin @kuiralabs/midnight-account-chain 0.3.0-rc.3 (batched
inbox appends: one transaction for up to four entries), and grant pins
@kuiralabs/midnight-account 0.2.0-rc.1, the version rc.3 depends on, so
one copy is installed. The beta engine's nested copy is restored in the
lockfile and the tree, as before (npm dedupes it away).

An account deployed with rc.2 has the older contract; rc.3 needs a new one.
Suite 3060, beta 195. The only snapshot change is contract inspect of the
account contract itself, which lists rc.3's circuits.
Y65 (option B): install with npm, run with Node or bun. bun's installer
ignores each engine's npm-shrinkwrap.json and resolves the ranges again;
its peer resolution differs too (graphql-tag shares graphql 17). The SDK
then fails as it loads, intermittently, before the engine's ledger-copy
check runs.

- core's shippedTreeDrift / assertInstalledAsShipped walks the engine's
  dependency graph. Each dependency is resolved as Node resolves it from
  where its requirer sits and compared with the shrinkwrap's version. A
  tree npm nests (a program) or hoists (mn's own install) passes, and one
  resolved again fails with NotInstalledAsShippedError (MIXED_SDK_LAYOUT):
  the first drift, why, and the npm command. A checkout ships no
  shrinkwrap and is not checked.
- Each engine's entry (index.ts) runs it, then loads the engine
  (<set>-engine.ts). code-reach follows the assembler there.
- MIXED_SDK_LAYOUT's summary now says what it covers. The READMEs say bun
  runs what npm installed.

Measured on the spike's trees: npm (nested) 0 drift, mn's global install
(hoisted) 0, bun installs 36 to 78. Suite 3066, beta 195.
CI's fresh-install check now also installs the packed packages with bun
(CI sets bun up from .bun-version) and checks that each engine refuses to
load, under Node and under bun, with MIXED_SDK_LAYOUT naming npm. Where bun
isn't installed, the step says so and is skipped. Locally: a fresh install
works, the four refusals included.
An open offer holds every coin it spends, and the shielded wallet spends the
smallest coin first, seeing an open offer's coins as free: a second offer of
the same token was refused with OFFER_COINS_IN_USE.

- Each engine builds its shielded wallet with mn's coin picker (the SDKs'
  public builders): it skips the coins of the wallet's open offers, except in
  their cancel, and takes a coin of the exact amount when there is one. When
  only offers' coins could pay, OFFER_COINS_IN_USE comes before proving.
- swap make: when no free coin is worth exactly what it gives, it first
  splits one (a transfer to itself, a fee in Dust), waits for the receipt and
  for the wallet to hold the new coin, then makes the offer from it. Its JSON
  gains `split` (txHash and receipt).
- swap cancel spends exactly the offer's coins, so the wallet's other open
  offers stay live.
- The picker derives its keys for each nullifier and clears them: a coin
  secret key held on its own is cleared by the ledger once its keys are
  collected (regression test under --expose-gc).
Several open swap offers of one token (swap make splits a coin; spends
leave open offers' coins alone), mounting mn's commands from core, a
README per package, two typed codes, bun runs what npm installed (a bun
install refused), account-chain 0.3.0-rc.3, and two fixes found by the
consumer project. Every @kuiralabs workspace package moves to
0.1.0-rc.3; mn to 0.6.0-rc.14.
rc.14's release job stopped before publishing: it installs the latest npm,
and npm 12 (4 Nov) prints `npm pack --json` as an object keyed by name and
`npm view --json` as an array, and neither reads nor packs
npm-shrinkwrap.json, which each engine, grant and mn ship (Y32).

- publish-manifest.mjs reads the tarball name from either pack shape
  (packedFilename); make-shrinkwrap.mjs reads either view shape
  (viewedField). Under npm 12 the old code threw in pack, and registryDist
  returned {}: a shrinkwrap with no tarballs or integrity. Regression tests
  for both; the pack tests fail under npm 12 without the fix.
- The release job installs npm@11 (trusted publishing needs 11.5.1+).
- MIXED_SDK_LAYOUT names npm 12 with bun's installer, and says to install
  with npm 11 or older (npx -y npm@11 install ... under npm 12); the READMEs
  and the changelog say so. Checked: under npm 12 an install of rc.14 lays
  out 4 ledger-v9 copies and both engines refuse; through npx npm@11 it
  lays out 2 and mn runs on both engines.
@nel349
nel349 force-pushed the merge/ledger-9-main branch from a6d8ab3 to 09cb445 Compare November 12, 2026 06:18
@nel349
nel349 merged commit 09cb445 into main Nov 12, 2026
3 checks passed
@nel349
nel349 deleted the merge/ledger-9-main branch November 12, 2026 21:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant