diff --git a/README.md b/README.md index f9e0760..8580f7b 100644 --- a/README.md +++ b/README.md @@ -209,14 +209,14 @@ Run any of these with `npx ethagent`. Commands marked interactive need a termina | `storage [--set \| --forget] [--json]` | Where snapshots are pinned and whether a credential is set. `--set` saves a Pinata JWT read from stdin; `--forget` removes it after a preview. | Read-only; `--set` and `--forget` write secrets | | `create --name --network [--description ] [--advanced] [--import] [--replace] [--yes] [--json]` | Mint a new agent with its first snapshot. `--advanced` continues into a Vault in the same tab; `--replace` is needed when this machine already has an agent. Previews until `--yes`. | Opens your wallet | | `restore [ \| ] [--network ] [--operator] [--yes] [--json]` | Rebuild an agent on this machine, or with no target pull the newest onchain snapshot into the vault. Previews until `--yes`. | Opens your wallet, or none with `--operator` | -| `restore --owner [--json]` | List the agents a wallet holds or operates. | Goes online | +| `restore --owner [--json]` | List the agents a wallet holds or operates, including ones it deposited into a Vault. When the RPC can't serve the log history to check, it says so and exits 1 instead of listing nothing; point `ETHAGENT_RPC_URL` at a fuller RPC and pass `--network`. | Goes online | | `profile [--name ] [--description ] [--image ] [--operator] [--yes] [--json]` | Show the public profile, or change it and publish in one save. Previews until `--yes`. | Opens your wallet, or none with `--operator` | | `custody [--json]` | Custody mode, the Vault and its build, whether it holds the token, the Vault-level owner, and the approved operators. | Goes online | | `custody --verify [--json]` | Also simulates, sending nothing: the owner withdrawing and changing an operator, the operator rotating the agent URI, and the operator and a stranger being refused. Exits 4 on a mismatch. | Goes online | | `ens [--json]` | The linked name, its records, the two-way check, the resolver, who controls the name, and whether the operator key could sign for it. | Goes online | | `ens [--operator] [--yes] [--json]` | Point the agent at a name: create it under a parent the signer controls, write the agent records, clear them on the old name, then publish the name. Previews until `--yes`. | Opens your wallet | | `ens --unlink [--operator] [--yes] [--json]` | Clear the agent records on the linked name, then publish it unlinked. Previews until `--yes`. | Opens your wallet | -| `ens --delete [--yes] [--json]` | Unlink as above, then remove the subname from its parent. Signed by the wallet that manages the parent. Previews until `--yes`. | Opens your wallet | +| `ens --delete [--operator] [--yes] [--json]` | Unlink as above, then remove the subname from its parent. Signed by the wallet that manages the parent, which may be the operator key. Previews until `--yes`. | Opens your wallet | | `ens --set = --clear [--operator] [--yes] [--json]` | Write every record change in one transaction. No save needed. Previews until `--yes`. | Opens your wallet, or none with `--operator` | | `custody --advanced [--yes] [--json]` | Deploy a Vault (or reuse one), deposit the token, and save. Previews until `--yes`. | Opens your wallet | | `custody --simple [--yes] [--json]` | Revoke the Vault's operators, withdraw the token, and save. Previews until `--yes`. | Opens your wallet | @@ -231,13 +231,13 @@ Run any of these with `npx ethagent`. Commands marked interactive need a termina 1. It pulls in any edits from your tools. 2. If nothing changed since the last snapshot, it stops there. 3. Otherwise it prints a link and opens your wallet in the browser. You sign one message and approve one transaction. -4. ethagent encrypts everything, pins it to IPFS, points your token at it, and checks that the pointer landed. +4. ethagent encrypts everything, pins it to IPFS, points your token at it, and checks that the pointer landed (`verification` in the JSON: `verified`, `mismatch`, or `unknown`). | Flag | Effect | | --- | --- | | `--json` | Print the result as JSON. | | `--no-open` | Print the wallet link without opening the browser. | -| `--operator` | Save with no popup, signed by an approved operator key (Advanced custody), read from `ETHAGENT_OPERATOR_KEY`. | +| `--operator` | Save with no popup, signed by an approved operator key (Advanced custody), read from `ETHAGENT_OPERATOR_KEY`. It skips when nothing changed and checks the pointer the same way. | | Exit code | Meaning | | --- | --- | @@ -253,8 +253,8 @@ Run any of these with `npx ethagent`. Commands marked interactive need a termina - **Previews.** ENS changes preview by default. They list every transaction, simulate the ones that can run now from the signer, and send nothing. Rerun with `--yes` to send. - **Signers.** ENS transactions are signed in your browser wallet, in one tab for the whole change. With `--operator`, the operator key signs them with no popup instead. Run it as `keychain exec ethagent -- ethagent ens --operator`. -- **What the operator key may do.** It only writes text records and creates subnames under a parent it controls. It never sets `addr` on an existing name and never changes ownership. -- **Deleting.** `ens --delete` clears the records, removes the subname from its parent, then publishes the agent unlinked. Only the wallet that manages the parent can sign it, never the operator key. Whoever manages the parent can create the name again, unless its fuses forbid that. A run stopped after the removal finishes when run again. +- **What the operator key may do.** It only writes text records, and creates or deletes subnames under a parent it controls. It never sets `addr` on an existing name and never changes ownership. +- **Deleting.** `ens --delete` clears the records, removes the subname from its parent, then publishes the agent unlinked. Only the wallet that manages the parent can sign it; that is the operator key when the key manages the parent, which could already remove the name at the ENS contracts. Whoever manages the parent can create the name again, unless its fuses forbid that. A run stopped after the removal finishes when run again. - **Publishing.** Changing, unlinking, or deleting the name always ends with one owner-signed save. A stolen operator key therefore can't point your agent at a name it registered. Local state takes the new name only after that save lands. - **Control check.** Before anything is sent, the command refuses unless the signer controls the name: as its owner, its NameWrapper owner, or a delegate approved on its resolver. diff --git a/commands/ethagent.md b/commands/ethagent.md index e5916cb..a750d0f 100644 --- a/commands/ethagent.md +++ b/commands/ethagent.md @@ -62,13 +62,13 @@ Both commands take `--json` (same `schema: 1` envelope) and `--help`. - `custody` (read-only, safe anytime) shows the custody mode, the Vault address and its build, whether it holds the agent token, the Vault-level owner, and the approved operators. `custody --verify` also simulates with `eth_call`, sending nothing: the owner withdrawing, the owner changing an operator, the operator rotating the agent URI, and the operator and a stranger being refused. It exits 4 when a result differs from what the Vault should do. - `custody --advanced`, `custody --simple`, `custody --add-operator [
]`, `--remove-operator
`, and `--activate-operator
` change custody. They are planned from chain state, so running one again after it stopped part way (exit 4, or 3 if a prompt was cancelled) finishes it. `custody --add-operator --operator` lets the injected operator key sign its own proof. - `ens` (read-only, safe anytime) shows the linked name, its live records, the two-way check, the resolver, who controls the name, and whether the operator key could sign for it. -- `ens `, `ens --unlink`, `ens --delete` (also removes the subname from its parent; never the operator key), and `ens --set = --clear ` change ENS. Without `--yes` they only preview: they list every transaction, simulate the ones that can run now, and send nothing (JSON `applied: false`). You may run previews yourself. Anything with `--yes` sends transactions and costs gas, so it stays the user's to run; show them the preview and the command. -- ENS transactions are signed in the browser wallet by default, or by the operator key with `--operator` (run through `keychain exec ethagent -- ethagent ens --operator`; exit 3 without a key, 2 for an invalid one). The operator key only writes text records and creates subnames under a parent it controls. Publishing a name change (`ens `, `ens --unlink`) always ends with one owner-signed save in the browser. +- `ens `, `ens --unlink`, `ens --delete` (also removes the subname from its parent; the operator key may sign it only when it manages the parent), and `ens --set = --clear ` change ENS. Without `--yes` they only preview: they list every transaction, simulate the ones that can run now, and send nothing (JSON `applied: false`). You may run previews yourself. Anything with `--yes` sends transactions and costs gas, so it stays the user's to run; show them the preview and the command. +- ENS transactions are signed in the browser wallet by default, or by the operator key with `--operator` (run through `keychain exec ethagent -- ethagent ens --operator`; exit 3 without a key, 2 for an invalid one). The operator key only writes text records, and creates or deletes subnames under a parent it controls. Publishing a name change (`ens `, `ens --unlink`) always ends with one owner-signed save in the browser. Setting up and moving an agent (all take `--json` and `--help`; anything that signs or sends previews until `--yes`, and the `--yes` run is the user's): - `profile` (read-only) shows the public name, description, and image; `profile --name --description --image ` changes them in one save. With `--operator` the operator key signs, when advanced custody with a linked ENS name allows it. -- `restore --owner ` (read-only) lists the agents a wallet holds. `restore --network ` or `restore ` rebuilds an agent on this machine; `restore` with no target pulls the newest onchain snapshot into the vault. `restore --operator --yes` decrypts with the operator key and opens no browser, so you may run it yourself when the user asks you to restore or refresh the agent (through `keychain exec ethagent -- ...`). It checkpoints the vault first; `rollback --undo --yes` reverses it. +- `restore --owner ` (read-only) lists the agents a wallet holds, including ones in its Vault. If it exits 1 because the RPC couldn't scan the history, pass the `` directly or point `ETHAGENT_RPC_URL` at a fuller RPC. `restore --network ` or `restore ` rebuilds an agent on this machine; `restore` with no target pulls the newest onchain snapshot into the vault. `restore --operator --yes` decrypts with the operator key and opens no browser, so you may run it yourself when the user asks you to restore or refresh the agent (through `keychain exec ethagent -- ...`). It checkpoints the vault first; `rollback --undo --yes` reverses it. - `create --name --network ` mints a new agent; `--advanced` continues into a Vault. It costs gas: preview it, then leave `--yes` to the user. - `transfer ` re-encrypts the agent for a new owner; both wallets sign in the user's browser, and the user sends the token afterwards. - `storage` (read-only) says whether IPFS storage is set up; `storage --set` reads a Pinata JWT from stdin. Never put the JWT in a command line. diff --git a/src/cli/daemon.ts b/src/cli/daemon.ts index ce3d842..9ffcf6a 100644 --- a/src/cli/daemon.ts +++ b/src/cli/daemon.ts @@ -66,9 +66,40 @@ export function isPidAlive(pid: number): boolean { } } -export function daemonStatus(): { running: boolean; pid: number | null } { +// The daemon touches its pid file every DAEMON_HEARTBEAT_MS. A pid file left quiet for +// longer than DAEMON_STALE_MS belongs to a daemon that is gone, even when the operating +// system has since handed its pid to some other process. +export const DAEMON_HEARTBEAT_MS = 30_000 +export const DAEMON_STALE_MS = 120_000 + +function heartbeatFresh(): boolean { + try { + return Date.now() - fs.statSync(daemonPidPath()).mtimeMs < DAEMON_STALE_MS + } catch { + return false + } +} + +// The pid of a daemon that is alive and still beating, or null. +function liveDaemonPid(): number | null { const pid = readDaemonPid() - return pid && isPidAlive(pid) ? { running: true, pid } : { running: false, pid: null } + return pid && isPidAlive(pid) && heartbeatFresh() ? pid : null +} + +export function touchDaemonPid(): void { + if (readDaemonPid() !== process.pid) return + try { + const now = new Date() + fs.utimesSync(daemonPidPath(), now, now) + } catch {} +} + +export function daemonStatus(): { running: boolean; pid: number | null } { + const pid = liveDaemonPid() + if (pid) return { running: true, pid } + // A leftover file would otherwise read as running the moment its pid is reused. + if (readDaemonPid() !== null) clearDaemonPid() + return { running: false, pid: null } } export function writeDaemonPid(): void { @@ -129,9 +160,10 @@ export function ensureDaemon(): boolean { } export function stopDaemon(): boolean { - const pid = readDaemonPid() + // Only a pid that is still beating is ours to signal; a stale one may be anything now. + const pid = liveDaemonPid() let stopped = false - if (pid && isPidAlive(pid)) { + if (pid) { try { process.kill(pid, 'SIGTERM') stopped = true diff --git a/src/cli/onchain/ens.ts b/src/cli/onchain/ens.ts index b83f5a4..498c723 100644 --- a/src/cli/onchain/ens.ts +++ b/src/cli/onchain/ens.ts @@ -1,7 +1,7 @@ import { getAddress, type Address, type PublicClient } from 'viem' import type { EthagentConfig, EthagentIdentity } from '../../storage/config.js' import { saveConfig } from '../../storage/config.js' -import { createMainnetClient, validateAgentEnsLink } from '../../identity/ens/ensLookup.js' +import { createMainnetClient, normalizeEthDomain, splitSubdomainName, validateAgentEnsLink } from '../../identity/ens/ensLookup.js' import { readAddressRecord, readTextRecords } from '../../identity/ens/ensAutomation/read.js' import { resolveRegistryForIdentity } from '../../identity/registry/registryConfig.js' import { DEFAULT_ETHEREUM_RPC_URL, type Erc8004RegistryConfig } from '../../identity/registry/erc8004.js' @@ -59,9 +59,10 @@ const HELP = [ ' ethagent ens --unlink clear the agent records on the linked name, then publish', ' the unlinked state in one owner-signed save.', ' ethagent ens --delete unlink as above, then remove the subname from its parent.', - ' Signed by the wallet that manages the parent, never the', - ' operator key. The parent can recreate it, unless its fuses', - ' forbid that.', + ' Signed by the wallet that manages the parent: the browser', + ' wallet, or with --operator the operator key when it is the', + ' parent\'s manager. The parent can recreate it, unless its', + ' fuses forbid that.', ' ethagent ens --set = --clear ', ' write every record change on the linked name in one', ' resolver multicall. No save is needed.', @@ -69,7 +70,7 @@ const HELP = [ 'Writes preview first and send nothing without --yes. ENS transactions are signed by the', 'browser wallet, or with --operator by the operator key (run through `keychain exec ethagent', '-- ethagent ens --operator`, which injects ' + OPERATOR_KEY_ENV + '). The operator key only', - 'writes text records and creates subnames under a parent it controls. Publishing a name', + 'writes text records, and creates or deletes subnames under a parent it controls. Publishing a name', 'change always needs the owner wallet.', '', ].join('\n') @@ -175,6 +176,13 @@ async function readView(identity: EthagentIdentity, registry: Erc8004RegistryCon operator = { address: getAddress(key.address), canSign: Boolean(how), via: how } } else if (key && !key.ok && key.reason === 'invalid') { operator = { error: INVALID_OPERATOR_KEY_MESSAGE } + } else { + // No key in this shell: still say whether the agent's active operator could sign. + const active = readIdentityStateString(state, 'activeOperatorAddress') + if (active) { + const how = await signerControlOf(client, control, getAddress(active)) + operator = { address: getAddress(active), canSign: Boolean(how), via: how, keyAvailable: false } + } } return { name: control.name, @@ -203,9 +211,9 @@ function printView(view: Record): string { for (const [key, value] of entries) lines.push(` ${key} = ${value}`) lines.push(` resolver: ${String(view.resolver ?? 'none')}`) lines.push(` controlled by: ${control.owner ?? 'nobody'}${control.wrapped ? ' (wrapped)' : ''}`) - const operator = view.operator as { address?: string; canSign?: boolean; via?: string; error?: string } | null + const operator = view.operator as { address?: string; canSign?: boolean; via?: string; error?: string; keyAvailable?: boolean } | null if (operator?.error) lines.push(` operator key: ${operator.error}`) - else if (operator) lines.push(` operator key ${operator.address}: ${operator.canSign ? `can sign (${operator.via})` : 'cannot sign for this name'}`) + else if (operator) lines.push(` operator key ${operator.address}: ${operator.canSign ? `can sign (${operator.via})` : 'cannot sign for this name'}${operator.keyAvailable === false ? ' ยท key not in this shell' : ''}`) else lines.push(' operator key: not available in this shell') return `${lines.join('\n')}\n` } @@ -240,9 +248,6 @@ export async function runEnsCommand(args: string[], deps: HistoryDeps, seams: En if (!identity.agentId) throw new HistoryError(1, 'This identity has no agent token ID yet.', 'Mint one with `ethagent create`, or bring one back with `ethagent restore `.') const owner = getAddress(humanOwnerAddress(identity)) - if (mode.kind === 'delete' && values.operator) { - throw new HistoryError(2, '--delete is signed by the wallet that manages the parent name, never the operator key.', 'Drop --operator; `ethagent ens --unlink --operator` clears the records instead.') - } const signer = chooseSigner(deps, Boolean(values.operator), owner) const client = seams.readClient() const currentName = readIdentityStateString(identity.state as Record | undefined, 'ensName') @@ -280,6 +285,8 @@ export async function runEnsCommand(args: string[], deps: HistoryDeps, seams: En summary = { action: 'unlink', name: plan.name, records: plan.current } } else if (mode.kind === 'delete') { if (!currentName) throw new HistoryError(1, 'No ENS name is linked, so there is nothing to delete.') + // Only the parent's manager can remove a subname. When that is the agent's operator + // key, it may sign: it could already remove the name at the ENS contracts directly. const plan = await planEnsDelete({ client, name: currentName, @@ -287,6 +294,14 @@ export async function runEnsCommand(args: string[], deps: HistoryDeps, seams: En signerRole: signer.role, identityRegistryAddress: registry.identityRegistryAddress, agentId: identity.agentId, + }).catch(async (err: unknown) => { + if (!(err instanceof EnsPlanRefusal) || signer.kind === 'operator') throw err + const operator = readIdentityStateString(identity.state as Record | undefined, 'activeOperatorAddress') + const parent = splitSubdomainName(normalizeEthDomain(currentName))?.parent + if (!operator || !parent) throw err + const control = await readNameControl(client, parent).catch(() => null) + if (!control?.owner || control.owner.toLowerCase() !== operator.toLowerCase()) throw err + throw new EnsPlanRefusal(err.message, `The operator key ${getAddress(operator)} manages ${parent}: run it through \`keychain exec ethagent -- ethagent ens --delete --operator\`.`) }) transactions = plan.transactions publishName = '' diff --git a/src/cli/onchain/restore.ts b/src/cli/onchain/restore.ts index 9735f6e..fd4ced8 100644 --- a/src/cli/onchain/restore.ts +++ b/src/cli/onchain/restore.ts @@ -3,6 +3,7 @@ import type { EthagentConfig, EthagentIdentity } from '../../storage/config.js' import { saveConfig } from '../../storage/config.js' import { DEFAULT_IPFS_API_URL } from '../../identity/storage/ipfs.js' import { + AgentTokenIdRequiredError, chainIdForNetwork, discoverOwnedAgentBackupByTokenId, discoverOwnedAgentBackups, @@ -204,7 +205,18 @@ export async function runRestoreCommand(args: string[], deps: HistoryDeps, seams if (target) throw new HistoryError(2, 'choose either a target or --owner', `usage: ${RESTORE_USAGE}`) const owner = values.owner.trim() if (!isAddress(owner) && !/^([a-z0-9-]+\.)+eth$/i.test(owner)) throw new HistoryError(2, '--owner expects an address or a .eth name') - const candidates = await seams.discoverOwner(owner, network ? registryForNetwork(network) : undefined) + let candidates: Erc8004AgentCandidate[] + try { + candidates = await seams.discoverOwner(owner, network ? registryForNetwork(network) : undefined) + } catch (err: unknown) { + if (!(err instanceof AgentTokenIdRequiredError)) throw err + // Never an empty list: the scan did not finish, so say why and how to get past it. + throw new HistoryError( + 1, + `${err.message}${err.detail ? ` ${err.detail}` : ''}`, + `Point ETHAGENT_RPC_URL at a ${network ?? ''} RPC that serves full log history and pass --network, or restore directly with \`ethagent restore --network ${network ?? ''}\`.`, + ) + } const rows = candidates.map(candidateJson) if (json) { await emitJson(deps.io, { owner, agents: rows }) diff --git a/src/cli/operatorSave.ts b/src/cli/operatorSave.ts index 97bccce..800ce09 100644 --- a/src/cli/operatorSave.ts +++ b/src/cli/operatorSave.ts @@ -1,7 +1,9 @@ import { stdout, stderr } from 'node:process' import { loadConfig, saveConfig, type EthagentIdentity } from '../storage/config.js' import { resolveRegistryForIdentity } from '../identity/registry/registryConfig.js' -import { continuityVaultStatus } from '../identity/continuity/storage/status.js' +import { continuityVaultStatus, continuityWorkingTreeStatus } from '../identity/continuity/storage/status.js' +import { listPublishedContinuitySnapshots } from '../identity/continuity/snapshots.js' +import { discoverOwnedAgentBackupByTokenId } from '../identity/registry/erc8004/discovery.js' import { resolveValidatedPinataJwt } from '../identity/storage/pinataJwt.js' import { resolveVaultAddress } from '../identity/manager/custody/transactions.js' import { runOperatorWalletRebackup } from '../identity/manager/continuity/vault.js' @@ -11,23 +13,53 @@ import { createLocalKeySignAndTransaction } from '../identity/wallet/localKeyWal import type { EffectCallbacks } from '../identity/manager/shared/effects/types.js' import type { Step } from '../identity/manager/reducer.js' import { INVALID_OPERATOR_KEY_MESSAGE, OPERATOR_KEY_ENV, readOperatorKey } from './operatorKey.js' +import { pullHarnessSoulMemoryIntoVault } from './sync.js' +import { nothingToSave, saveJson, verifyPublished } from './saveVerify.js' -export async function runOperatorSave(args: string[] = []): Promise { +export type RunOperatorSaveDeps = { + readOperatorKey: typeof readOperatorKey + loadConfig: typeof loadConfig + saveConfig: typeof saveConfig + resolveValidatedPinataJwt: typeof resolveValidatedPinataJwt + continuityVaultStatus: typeof continuityVaultStatus + continuityWorkingTreeStatus: typeof continuityWorkingTreeStatus + listPublishedContinuitySnapshots: typeof listPublishedContinuitySnapshots + pullHarnessSoulMemoryIntoVault: typeof pullHarnessSoulMemoryIntoVault + runOperatorWalletRebackup: typeof runOperatorWalletRebackup + createSigner: typeof createLocalKeySignAndTransaction + discoverOwnedAgentBackupByTokenId: typeof discoverOwnedAgentBackupByTokenId +} + +const defaultDeps: RunOperatorSaveDeps = { + readOperatorKey, + loadConfig, + saveConfig, + resolveValidatedPinataJwt, + continuityVaultStatus, + continuityWorkingTreeStatus, + listPublishedContinuitySnapshots, + pullHarnessSoulMemoryIntoVault, + runOperatorWalletRebackup, + createSigner: createLocalKeySignAndTransaction, + discoverOwnedAgentBackupByTokenId, +} + +export async function runOperatorSave(args: string[] = [], deps: RunOperatorSaveDeps = defaultDeps): Promise { const json = args.includes('--json') const fail = (code: number, message: string): number => { - if (json) stdout.write(JSON.stringify({ ok: false, code, error: message }) + '\n') + if (json) stdout.write(saveJson({ ok: false, code, error: message })) else stderr.write(message + '\n') return code } - const operatorKey = readOperatorKey() + const operatorKey = deps.readOperatorKey() if (!operatorKey.ok && operatorKey.reason === 'missing') { return fail(3, `No operator key available. The os-keychain skill injects ${OPERATOR_KEY_ENV}; run this via \`keychain operator-save\` (set the key first with \`keychain set ethagent/operator_key\`).`) } if (!operatorKey.ok) return fail(2, INVALID_OPERATOR_KEY_MESSAGE) const privateKey = operatorKey.key - const config = await loadConfig().catch(() => null) + const config = await deps.loadConfig().catch(() => null) if (!config?.identity) return fail(1, 'No agent identity yet. Mint one with `ethagent create`, or bring one back with `ethagent restore `.') const identity = config.identity if (!identity.agentId) return fail(1, 'This identity has no agent token ID yet. Mint one with `ethagent create`, or bring one back with `ethagent restore `.') @@ -35,7 +67,7 @@ export async function runOperatorSave(args: string[] = []): Promise { const registry = resolveRegistryForIdentity(identity, config) if (!registry) return fail(1, 'No agent registry configured for this identity. `ethagent restore ` records it.') - const vault = await continuityVaultStatus(identity).catch(() => ({ ready: false })) + const vault = await deps.continuityVaultStatus(identity).catch(() => ({ ready: false })) if (!vault.ready) return fail(1, 'Local continuity files are not restored. Bring them back with `ethagent restore --operator` before saving a snapshot.') const role = snapshotSaveWalletRole(identity, undefined) @@ -48,9 +80,17 @@ export async function runOperatorSave(args: string[] = []): Promise { return fail(1, 'Advanced custody is configured but the operator vault address could not be resolved. `ethagent custody` shows where the token is held, and `ethagent custody --advanced` previews the repair.') } + // Same as `save`: take in the tools' edits, and send nothing when nothing changed. + await deps.pullHarnessSoulMemoryIntoVault(identity).catch(() => []) + if (await nothingToSave(identity, deps)) { + if (json) stdout.write(saveJson({ ok: true, skipped: true, reason: 'no-local-changes' })) + else stdout.write('No local changes since the last snapshot; nothing to save.\n') + return 0 + } + let jwt: string | undefined try { - jwt = await resolveValidatedPinataJwt() + jwt = await deps.resolveValidatedPinataJwt() } catch (err) { const detail = err instanceof Error ? err.message : String(err) return fail(3, `The configured Pinata JWT is invalid or unreachable (${detail}). Replace it with \`ethagent storage --set\` (reads the JWT from stdin), then retry.`) @@ -61,7 +101,7 @@ export async function runOperatorSave(args: string[] = []): Promise { let signAndTransaction try { - signAndTransaction = createLocalKeySignAndTransaction({ privateKey, rpcUrl: registry.rpcUrl, chainId: registry.chainId }) + signAndTransaction = deps.createSigner({ privateKey, rpcUrl: registry.rpcUrl, chainId: registry.chainId }) } catch (err) { return fail(1, `Could not initialize the local-key signer: ${err instanceof Error ? err.message : String(err)}`) } @@ -71,7 +111,7 @@ export async function runOperatorSave(args: string[] = []): Promise { onStep: () => {}, onWalletReady: () => {}, onIdentityComplete: async (nextIdentity: EthagentIdentity) => { - await saveConfig({ ...config, identity: nextIdentity }) + await deps.saveConfig({ ...config, identity: nextIdentity }) savedIdentity = nextIdentity }, } @@ -86,7 +126,7 @@ export async function runOperatorSave(args: string[] = []): Promise { } try { - await runOperatorWalletRebackup({ + await deps.runOperatorWalletRebackup({ step, callbacks, walletPurpose: 'rotate-agent-uri-vault-operator', @@ -104,13 +144,19 @@ export async function runOperatorSave(args: string[] = []): Promise { const agentUri = ni.agentUri ?? ni.backup?.agentUri ?? null const published = Boolean(txHash || ni.backup?.metadataCid) + const verification = published + ? await verifyPublished({ saved: ni, agentId: identity.agentId, registry, discover: deps.discoverOwnedAgentBackupByTokenId }) + : undefined + if (json) { - stdout.write(JSON.stringify({ ok: true, published, cid, txHash, agentUri }) + '\n') + stdout.write(saveJson({ ok: true, published, ...(verification ? { verification } : {}), cid, txHash, agentUri })) } else if (published) { stdout.write('Snapshot published onchain via operator key (no wallet popup).\n') if (cid) stdout.write(` CID: ${cid}\n`) if (txHash) stdout.write(` tx: ${txHash}\n`) if (agentUri) stdout.write(` agentURI: ${agentUri}\n`) + if (verification === 'verified') stdout.write(' verified: onchain pointer resolves to this snapshot.\n') + else if (verification === 'mismatch') stderr.write(' warning: the onchain pointer does not yet resolve to this snapshot (propagation delay?).\n') } else { stdout.write('Snapshot pinned locally, but the onchain pointer was not rotated. Retry, or publish it with the owner wallet through `ethagent save`.\n') if (cid) stdout.write(` pinned CID: ${cid}\n`) diff --git a/src/cli/save.ts b/src/cli/save.ts index b66f908..b133b0b 100644 --- a/src/cli/save.ts +++ b/src/cli/save.ts @@ -11,10 +11,8 @@ import type { Step } from '../identity/manager/reducer.js' import { openExternalUrl } from '../utils/openExternal.js' import { pullHarnessSoulMemoryIntoVault } from './sync.js' import { discoverOwnedAgentBackupByTokenId } from '../identity/registry/erc8004/discovery.js' -import { DEFAULT_IPFS_API_URL } from '../identity/storage/ipfs.js' import { resolveVaultAddress } from '../identity/manager/custody/transactions.js' -import { hasPendingPublish } from '../identity/manager/continuity/state.js' -import { getAddress } from 'viem' +import { nothingToSave, saveJson, verifyPublished } from './saveVerify.js' export type RunSaveDeps = { loadConfig: typeof loadConfig @@ -56,7 +54,7 @@ export async function runSave(args: string[] = [], deps: RunSaveDeps = defaultDe } const fail = (code: number, message: string): number => { - if (json) stdout.write(JSON.stringify({ ok: false, code, error: message }) + '\n') + if (json) stdout.write(saveJson({ ok: false, code, error: message })) else stderr.write(message + '\n') return code } @@ -84,16 +82,8 @@ export async function runSave(args: string[] = [], deps: RunSaveDeps = defaultDe await deps.pullHarnessSoulMemoryIntoVault(identity).catch(() => []) - let publishState: string | undefined - try { - const [latest] = await deps.listPublishedContinuitySnapshots(identity, 1) - const tree = await deps.continuityWorkingTreeStatus(identity, latest) - publishState = tree.publishState - } catch { - publishState = undefined - } - if (publishState === 'published' && !hasPendingPublish(identity)) { - if (json) stdout.write(JSON.stringify({ ok: true, skipped: true, reason: 'no-local-changes' }) + '\n') + if (await nothingToSave(identity, deps)) { + if (json) stdout.write(saveJson({ ok: true, skipped: true, reason: 'no-local-changes' })) else stdout.write('No local changes since the last snapshot; nothing to save.\n') return 0 } @@ -158,21 +148,9 @@ export async function runSave(args: string[] = [], deps: RunSaveDeps = defaultDe const published = Boolean(ni.backup?.txHash || ni.backup?.metadataCid) if (published) { - let verification: 'verified' | 'mismatch' | 'unknown' = 'unknown' - try { - const candidate = await deps.discoverOwnedAgentBackupByTokenId({ - ...registry, - ownerHandle: getAddress(ni.ownerAddress ?? ni.address), - tokenId: BigInt(identity.agentId), - ipfsApiUrl: ni.backup?.ipfsApiUrl ?? DEFAULT_IPFS_API_URL, - }) - const onchainCid = candidate.backup?.cid ?? null - verification = onchainCid ? (onchainCid === cid ? 'verified' : 'mismatch') : 'unknown' - } catch { - verification = 'unknown' - } + const verification = await verifyPublished({ saved: ni, agentId: identity.agentId, registry, discover: deps.discoverOwnedAgentBackupByTokenId }) if (json) { - stdout.write(JSON.stringify({ ok: true, published: true, verification, cid, txHash: ni.backup?.txHash ?? null, agentUri: ni.agentUri ?? null }) + '\n') + stdout.write(saveJson({ ok: true, published: true, verification, cid, txHash: ni.backup?.txHash ?? null, agentUri: ni.agentUri ?? null })) } else { stdout.write('Snapshot published onchain.\n') if (cid) stdout.write(` CID: ${cid}\n`) @@ -186,7 +164,7 @@ export async function runSave(args: string[] = [], deps: RunSaveDeps = defaultDe const detail = completionMessage || 'Snapshot saved locally. The owner wallet still needs to publish to rotate the onchain pointer.' if (json) { - stdout.write(JSON.stringify({ ok: true, published: false, pending: 'owner-publish', cid, message: detail }) + '\n') + stdout.write(saveJson({ ok: true, published: false, pending: 'owner-publish', cid, message: detail })) } else { stdout.write(`${detail}\n`) if (cid) stdout.write(` pinned CID: ${cid}\n`) diff --git a/src/cli/saveVerify.ts b/src/cli/saveVerify.ts new file mode 100644 index 0000000..dc1c023 --- /dev/null +++ b/src/cli/saveVerify.ts @@ -0,0 +1,61 @@ +import { getAddress } from 'viem' +import type { EthagentIdentity } from '../storage/config.js' +import type { continuityWorkingTreeStatus } from '../identity/continuity/storage/status.js' +import type { listPublishedContinuitySnapshots } from '../identity/continuity/snapshots.js' +import type { discoverOwnedAgentBackupByTokenId } from '../identity/registry/erc8004/discovery.js' +import type { Erc8004RegistryConfig } from '../identity/registry/erc8004.js' +import { DEFAULT_IPFS_API_URL } from '../identity/storage/ipfs.js' +import { hasPendingPublish } from '../identity/manager/continuity/state.js' + +// Shared by `save` and `save --operator`: the no-changes check that keeps a save from +// pinning and sending when nothing changed, the read-back of the onchain pointer, and +// the JSON envelope. + +export type SaveJsonValue = Record + +export function saveJson(value: SaveJsonValue): string { + return `${JSON.stringify({ schema: 1, ...value })}\n` +} + +// True only when the vault matches the latest published snapshot and nothing pinned is +// waiting to publish. An unreadable state is never "nothing to save". +export async function nothingToSave( + identity: EthagentIdentity, + deps: { + listPublishedContinuitySnapshots: typeof listPublishedContinuitySnapshots + continuityWorkingTreeStatus: typeof continuityWorkingTreeStatus + }, +): Promise { + try { + const [latest] = await deps.listPublishedContinuitySnapshots(identity, 1) + const tree = await deps.continuityWorkingTreeStatus(identity, latest) + return tree.publishState === 'published' && !hasPendingPublish(identity) + } catch { + return false + } +} + +export type Verification = 'verified' | 'mismatch' | 'unknown' + +// Reads the token back from the registry and compares its snapshot CID with the one +// just published. +export async function verifyPublished(args: { + saved: EthagentIdentity + agentId: string + registry: Erc8004RegistryConfig + discover: typeof discoverOwnedAgentBackupByTokenId +}): Promise { + const cid = args.saved.backup?.cid ?? null + try { + const candidate = await args.discover({ + ...args.registry, + ownerHandle: getAddress(args.saved.ownerAddress ?? args.saved.address), + tokenId: BigInt(args.agentId), + ipfsApiUrl: args.saved.backup?.ipfsApiUrl ?? DEFAULT_IPFS_API_URL, + }) + const onchainCid = candidate.backup?.cid ?? null + return onchainCid ? (onchainCid === cid ? 'verified' : 'mismatch') : 'unknown' + } catch { + return 'unknown' + } +} diff --git a/src/cli/watch.ts b/src/cli/watch.ts index 705df5b..3684ff4 100644 --- a/src/cli/watch.ts +++ b/src/cli/watch.ts @@ -9,7 +9,9 @@ import { daemonDisabled, daemonLogPath, daemonStatus, + DAEMON_HEARTBEAT_MS, stopDaemon, + touchDaemonPid, tryClaimDaemonPid, } from './daemon.js' @@ -113,6 +115,7 @@ export async function runWatch(argv: string[]): Promise { return 0 } + const heartbeat = setInterval(touchDaemonPid, DAEMON_HEARTBEAT_MS) let rescan: NodeJS.Timeout | null = null let timer: NodeJS.Timeout | null = null let syncing = false @@ -129,6 +132,7 @@ export async function runWatch(argv: string[]): Promise { const cleanup = (): void => { stopped = true + clearInterval(heartbeat) if (rescan) clearTimeout(rescan) if (timer) clearTimeout(timer) for (const watcher of watched.values()) { try { watcher.close() } catch {} } diff --git a/src/identity/manager/shared/reconciliation/agentReconciliation/run.ts b/src/identity/manager/shared/reconciliation/agentReconciliation/run.ts index 534ff12..570706e 100644 --- a/src/identity/manager/shared/reconciliation/agentReconciliation/run.ts +++ b/src/identity/manager/shared/reconciliation/agentReconciliation/run.ts @@ -9,6 +9,8 @@ import { isAgentInVault, resolveConfiguredVaultAddress, vaultBuildForCode, type import type { EthagentConfig, EthagentIdentity } from '../../../../../storage/config.js' import { readVaultAddressField } from '../../../../identityCompat.js' import { readCustodyMode } from '../../../custody/state.js' +import { hasPendingPublish } from '../../../continuity/state.js' +import { ERC8004_ABI } from '../../../../registry/erc8004/abi.js' import { continuityWorkingTreeStatus, type ContinuityWorkingTreeStatus } from '../../../../continuity/storage.js' import { listPublishedContinuitySnapshots } from '../../../../continuity/snapshots.js' import type { AgentReconciliation } from './types.js' @@ -150,7 +152,10 @@ function fallbackToken(): TokenProbe { type CustodyProbe = { kind: 'simple' | 'advanced' | 'withdrawn' | 'mid-flow-uri-pending' | 'unknown' } -async function probeCustody(args: { +// Mid-flow is the token sitting in the Vault while this machine has not yet saved the +// switch to Advanced. A differing agent URI alone is not it: another machine saving +// changes the URI too. +export async function probeCustody(args: { client: PublicClient registry: Erc8004RegistryConfig agentId: bigint @@ -167,23 +172,8 @@ async function probeCustody(args: { agentId: args.agentId, }) if (!status.inVault) return { kind: 'withdrawn' } - const localUri = args.identity.agentUri ?? args.identity.backup?.agentUri - if (localUri) { - try { - const onChain = await args.client.readContract({ - address: args.registry.identityRegistryAddress, - abi: ERC8004_AGENT_URI_ABI, - functionName: 'agentURI', - args: [args.agentId], - }) as string - if (onChain && onChain !== localUri) { - return { kind: 'mid-flow-uri-pending' } - } - } catch { - } - } - if (status.ownerAddress?.toLowerCase() === args.expectedOwner.toLowerCase()) { - return { kind: 'advanced' } + if (readCustodyMode(args.identity.state as Record | undefined) !== 'advanced') { + return { kind: 'mid-flow-uri-pending' } } return { kind: 'advanced' } } catch { @@ -193,17 +183,10 @@ async function probeCustody(args: { type AgentUriProbe = { kind: 'in-sync' | 'chain-newer' | 'local-newer' | 'unknown' } -const ERC8004_AGENT_URI_ABI = [ - { - type: 'function', - name: 'agentURI', - stateMutability: 'view', - inputs: [{ name: 'agentId', type: 'uint256' }], - outputs: [{ name: '', type: 'string' }], - }, -] as const - -async function probeAgentUri(args: { +// The registry's tokenURI is the onchain pointer; agentURI is not part of its ABI and +// reverts. A difference is this machine's when it has a pinned snapshot waiting to +// publish, and the chain's (another machine saved since) otherwise. +export async function probeAgentUri(args: { client: PublicClient registry: Erc8004RegistryConfig agentId: bigint @@ -214,13 +197,13 @@ async function probeAgentUri(args: { try { const onChain = await args.client.readContract({ address: args.registry.identityRegistryAddress, - abi: ERC8004_AGENT_URI_ABI, - functionName: 'agentURI', + abi: ERC8004_ABI, + functionName: 'tokenURI', args: [args.agentId], }) as string if (onChain === localUri) return { kind: 'in-sync' } - if (!onChain) return { kind: 'local-newer' } - return { kind: 'local-newer' } + if (!onChain || hasPendingPublish(args.identity)) return { kind: 'local-newer' } + return { kind: 'chain-newer' } } catch { return { kind: 'unknown' } } diff --git a/src/identity/registry/erc8004/discovery.ts b/src/identity/registry/erc8004/discovery.ts index da4fe11..2e7eaa1 100644 --- a/src/identity/registry/erc8004/discovery.ts +++ b/src/identity/registry/erc8004/discovery.ts @@ -157,7 +157,6 @@ async function findCandidateTokenIds(args: { ownerAddress: Address fromBlock: bigint }): Promise { - const tokenIds = new Set() let balance: bigint try { balance = await args.publicClient.readContract({ @@ -175,8 +174,38 @@ async function findCandidateTokenIds(args: { cause: err, }) } - if (balance === 0n) return [] + const direct = balance === 0n ? [] : await findDirectTokenIds({ ...args, balance }) + // A token deposited into a Vault is owned by the Vault, so balanceOf never counts it. + // The deposit is a transfer out of this wallet, which is what this scan looks for. + let vaulted: bigint[] = [] + try { + vaulted = await findVaultHeldTokenIds(args) + } catch (err: unknown) { + // With agents already found, a failed Vault scan only means a Vault-held one may be + // missing; with none found, an empty list would claim the wallet holds nothing. + if (direct.length === 0) { + throw new AgentTokenIdRequiredError({ + ownerAddress: args.ownerAddress, + registry: args.registry, + balance, + detail: cleanRpcError(err), + cause: err, + }) + } + } + return [...new Set([...direct, ...vaulted])] +} +async function findDirectTokenIds(args: { + publicClient: PublicClient + injectedClient: boolean + registry: Erc8004RegistryConfig + ownerAddress: Address + fromBlock: bigint + balance: bigint +}): Promise { + const tokenIds = new Set() + const balance = args.balance const enumerableTokenIds = await findEnumerableTokenIds({ publicClient: args.publicClient, registry: args.registry, @@ -186,13 +215,7 @@ async function findCandidateTokenIds(args: { if (enumerableTokenIds) return enumerableTokenIds try { - for await (const logs of getTransferLogChunksBackwards({ - publicClient: args.publicClient, - injectedClient: args.injectedClient, - registry: args.registry, - ownerAddress: args.ownerAddress, - fromBlock: args.fromBlock, - })) { + for await (const logs of getTransferLogChunksBackwards({ ...args, direction: 'to' })) { for (const log of logs) { const tokenId = log.args.tokenId if (tokenId === undefined || tokenIds.has(tokenId)) continue @@ -222,7 +245,50 @@ async function findCandidateTokenIds(args: { return [...tokenIds] } -// Transfer logs into the owner, newest first, through scanLogs: each endpoint's +// Tokens this wallet sent away that now sit in a Vault recording it as the owner. +async function findVaultHeldTokenIds(args: { + publicClient: PublicClient + injectedClient: boolean + registry: Erc8004RegistryConfig + ownerAddress: Address + fromBlock: bigint +}): Promise { + const seen = new Set() + const held: bigint[] = [] + for await (const logs of getTransferLogChunksBackwards({ ...args, direction: 'from' })) { + for (const log of logs) { + const tokenId = log.args.tokenId + if (tokenId === undefined || seen.has(tokenId)) continue + seen.add(tokenId) + const vaultOwner = await readVaultLevelOwnerOf(args.publicClient, args.registry.identityRegistryAddress, tokenId, args.ownerAddress) + if (vaultOwner && vaultOwner.toLowerCase() === args.ownerAddress.toLowerCase()) held.push(tokenId) + } + } + return held +} + +async function readVaultLevelOwnerOf( + publicClient: PublicClient, + registry: Address, + tokenId: bigint, + ownerAddress: Address, +): Promise
{ + try { + const currentOwner = await publicClient.readContract({ + address: registry, + abi: ERC8004_ABI, + functionName: 'ownerOf', + args: [tokenId], + }) as Address + // Still in this wallet: the direct lookup already counts it. + if (currentOwner.toLowerCase() === ownerAddress.toLowerCase()) return undefined + return await readVaultLevelOwner({ publicClient, identityRegistryAddress: registry, tokenId }, getAddress(currentOwner)) + } catch { + return undefined + } +} + +// Transfer logs into (or out of) the owner, newest first, through scanLogs: each endpoint's // learned block range instead of fixed windows, handing over when an endpoint cannot // reach back far enough. An injected client (tests, callers with their own transport) // answers for every endpoint. @@ -232,6 +298,7 @@ async function* getTransferLogChunksBackwards(args: { registry: Erc8004RegistryConfig ownerAddress: Address fromBlock: bigint + direction: 'to' | 'from' }): AsyncGenerator { const latest = await args.publicClient.getBlockNumber() if (args.fromBlock > latest) return @@ -253,7 +320,7 @@ async function* getTransferLogChunksBackwards(args: { query: async (url, fromBlock, toBlock) => await clientFor(url).getLogs({ address: args.registry.identityRegistryAddress, event: TRANSFER_EVENT, - args: { to: args.ownerAddress }, + args: args.direction === 'to' ? { to: args.ownerAddress } : { from: args.ownerAddress }, fromBlock, toBlock, }) as TransferLog[], diff --git a/src/net/adaptive.ts b/src/net/adaptive.ts index ff82d52..f2d840b 100644 --- a/src/net/adaptive.ts +++ b/src/net/adaptive.ts @@ -1,7 +1,5 @@ -import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' -import { mkdir } from 'node:fs/promises' +import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { atomicWriteText } from '../storage/atomicWrite.js' import { getConfigDir } from '../storage/config.js' export type FetchLike = (input: string | URL, init?: RequestInit) => Promise @@ -40,11 +38,28 @@ function statsFile(): string | null { return path.join(getConfigDir(), 'hosts.json') } +const STALE_TEMP_MS = 60_000 + +// Temp files a killed process never renamed into place. Ones under a minute old may +// belong to a process still writing, so they are left alone. +function sweepStaleTemps(file: string): void { + try { + const dir = path.dirname(file) + const prefix = `${path.basename(file)}.` + for (const name of readdirSync(dir)) { + if (!name.startsWith(prefix) || !name.endsWith('.tmp')) continue + const temp = path.join(dir, name) + if (Date.now() - statSync(temp).mtimeMs > STALE_TEMP_MS) unlinkSync(temp) + } + } catch {} +} + function load(): void { if (loaded) return loaded = true const file = statsFile() if (!file) return + sweepStaleTemps(file) try { const raw = JSON.parse(readFileSync(file, 'utf8')) as Record> for (const [host, value] of Object.entries(raw)) { @@ -69,22 +84,30 @@ function statsText(): string { return `${JSON.stringify(Object.fromEntries(measured), null, 2)}\n` } -// A one-shot command ends before a deferred write gets its turn, so whatever is still -// unsaved goes out synchronously as the process exits. -function saveOnExit(): void { - if (changesSaved === changes) return +// Every write is synchronous: the file is small, and a write that is never interrupted +// can't be cut off by process.exit halfway, leaving its temp file behind. +function writeStats(): void { const file = statsFile() if (!file) return + const upTo = changes try { mkdirSync(path.dirname(file), { recursive: true }) const temp = `${file}.${process.pid}.tmp` writeFileSync(temp, statsText(), { mode: 0o600 }) renameSync(temp, file) + changesSaved = Math.max(changesSaved, upTo) } catch { // The cache is an optimization; losing one update costs nothing. } } +// A one-shot command ends before a deferred write gets its turn, so whatever is still +// unsaved goes out as the process exits. +function saveOnExit(): void { + if (changesSaved === changes) return + writeStats() +} + function persist(): void { const file = statsFile() if (!file) return @@ -97,10 +120,7 @@ function persist(): void { writeQueued = true setImmediate(() => { writeQueued = false - const upTo = changes - void mkdir(path.dirname(file), { recursive: true }) - .then(() => atomicWriteText(file, statsText())) - .then(() => { changesSaved = Math.max(changesSaved, upTo) }, () => {}) + writeStats() }).unref?.() } diff --git a/test/cli/bootstrapAutosync.test.ts b/test/cli/bootstrapAutosync.test.ts index f15a64c..1a30d20 100644 --- a/test/cli/bootstrapAutosync.test.ts +++ b/test/cli/bootstrapAutosync.test.ts @@ -16,6 +16,9 @@ import { readDaemonPid, resumeSync, writeDaemonPid, + daemonPidPath, + stopDaemon, + touchDaemonPid, } from '../../src/cli/daemon.js' import { withHome } from '../support/home.js' @@ -237,6 +240,25 @@ test('daemon is single-instance: ensureDaemon is a no-op while a live pid file e }) }) +test('a pid file that stopped beating is not a running daemon, and its pid is never signalled', async () => { + await withHome(async () => { + // The test runner's own pid stands in for a pid the system handed to another process. + writeDaemonPid() + const old = new Date(Date.now() - 10 * 60_000) + await fs.utimes(daemonPidPath(), old, old) + assert.equal(daemonStatus().running, false) + assert.equal(readDaemonPid(), null, 'the stale file is cleared') + writeDaemonPid() + await fs.utimes(daemonPidPath(), old, old) + assert.equal(stopDaemon(), false, 'a stale pid is not ours to signal') + writeDaemonPid() + await fs.utimes(daemonPidPath(), old, old) + touchDaemonPid() + assert.equal(daemonStatus().running, true, 'a heartbeat makes it current again') + clearDaemonPid() + }) +}) + async function withEnv(key: string, value: string, fn: () => Promise): Promise { const prev = process.env[key] process.env[key] = value diff --git a/test/cli/onchainCommands.test.ts b/test/cli/onchainCommands.test.ts index 1f43b5b..6e73a37 100644 --- a/test/cli/onchainCommands.test.ts +++ b/test/cli/onchainCommands.test.ts @@ -359,7 +359,7 @@ test('ens --delete previews clearing the records, removing the subname from its assert.match(String(out.note), /can create it again/) }) -test('ens --delete refuses when the signer does not manage the parent, and never takes the operator key', async () => { +test('ens --delete refuses when the signer does not manage the parent', async () => { const id = identity({ ensName: 'meow.femboi.eth' }) const other = getAddress('0x00000000000000000000000000000000000beef1') const d = deps(id) @@ -369,7 +369,7 @@ test('ens --delete refuses when the signer does not manage the parent, and never })), 1) assert.match(String(d.io.json().hint), /--unlink/) const op = operatorDeps(id) - assert.equal(await runEnsCommand(['--delete', '--operator', '--json'], op, ensSeams({})), 2) + assert.equal(await runEnsCommand(['--delete', '--operator', '--json'], op, ensSeams({})), 1, 'an operator key that manages no parent is refused') const top = deps(identity({ ensName: 'femboi.eth' })) assert.equal(await runEnsCommand(['--delete', '--json'], top, ensSeams({ 'femboi.eth': { owner: OWNER } })), 1) assert.match(String(top.io.json().error), /not a subdomain/) @@ -385,3 +385,32 @@ test('ens --delete resumes: a subname already removed leaves only the save', asy assert.deepEqual(out.transactions, []) assert.equal(out.publish.ensName, '') }) + +test('ens --delete --operator works when the operator key manages the parent, and the browser path points there', async () => { + const id = identity({ ensName: 'agent.example.eth', activeOperatorAddress: OPERATOR }) + const names = { + 'example.eth': { owner: OPERATOR }, + 'agent.example.eth': { owner: OPERATOR, resolver: RESOLVER, addr: OWNER, text: { [ENSIP25_BASE]: '1' } }, + } + const op = operatorDeps(id) + assert.equal(await runEnsCommand(['--delete', '--operator', '--json'], op, ensSeams(names)), 0, op.io.stdout()) + const out = op.io.json() as Record + assert.deepEqual(out.signer, { kind: 'operator', address: OPERATOR }) + assert.deepEqual(out.transactions.map((tx: any) => tx.step), ['clear-records', 'delete-subdomain']) + assert.equal(out.publish.signer, 'owner wallet', 'the unlinked save still needs the owner') + const browser = deps(id) + assert.equal(await runEnsCommand(['--delete', '--json'], browser, ensSeams(names)), 1) + assert.match(String(browser.io.json().hint), /ens --delete --operator/) +}) + +test('ens without a key in the shell still says whether the active operator could sign', async () => { + const id = identity({ ensName: 'agent.example.eth', activeOperatorAddress: OPERATOR }) + const d = deps(id) + assert.equal(await runEnsCommand(['--json'], d, ensSeams({ + 'agent.example.eth': { owner: OPERATOR, resolver: RESOLVER, addr: OWNER }, + })), 0) + assert.deepEqual(d.io.json().operator, { address: OPERATOR, canSign: true, via: 'owner', keyAvailable: false }) + const none = deps(identity({ ensName: 'agent.example.eth', activeOperatorAddress: '' })) + assert.equal(await runEnsCommand(['--json'], none, ensSeams({ 'agent.example.eth': { owner: OWNER, resolver: RESOLVER } })), 0) + assert.equal(none.io.json().operator, null) +}) diff --git a/test/cli/operatorSave.test.ts b/test/cli/operatorSave.test.ts new file mode 100644 index 0000000..64a79ba --- /dev/null +++ b/test/cli/operatorSave.test.ts @@ -0,0 +1,96 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { runOperatorSave, type RunOperatorSaveDeps } from '../../src/cli/operatorSave.js' +import type { EthagentConfig, EthagentIdentity } from '../../src/storage/config.js' +import { multiCustodyIdentity } from '../identity/manager/effects/effects.fixtures.js' + +const KEY = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d' as const +const IDENTITY = { + ...multiCustodyIdentity, + rpcUrl: 'https://mainnet.base.org', + state: { ...multiCustodyIdentity.state, operatorVaultAddress: '0x6bdC0000000000000000000000000000000051d7' }, +} as EthagentIdentity + +const PUBLISHED: EthagentIdentity = { + ...IDENTITY, + agentUri: 'ipfs://meta-new', + metadataCid: 'meta-new', + backup: { + cid: 'snap-new', createdAt: '2026-10-06T00:00:00.000Z', envelopeVersion: '1', + ipfsApiUrl: 'https://uploads.pinata.cloud/v3/files', status: 'pinned', txHash: '0xabc', metadataCid: 'meta-new', + }, +} + +type Spies = { pulls: number; sends: number; saved: EthagentConfig[] } + +function deps(spies: Spies, overrides: Partial = {}): RunOperatorSaveDeps { + return { + readOperatorKey: () => ({ ok: true, key: KEY, address: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8' }) as never, + loadConfig: async () => ({ version: 2, firstSeenAt: '', identity: IDENTITY }), + saveConfig: async config => { spies.saved.push(config) }, + resolveValidatedPinataJwt: async () => 'jwt', + continuityVaultStatus: async () => ({ ready: true, files: {} as never }), + continuityWorkingTreeStatus: async () => ({ ready: true, localChangedAfterBackup: true, publishState: 'local-changes' }) as never, + listPublishedContinuitySnapshots: async () => [], + pullHarnessSoulMemoryIntoVault: async () => { spies.pulls++; return [] }, + runOperatorWalletRebackup: async args => { + spies.sends++ + await args.callbacks.onIdentityComplete(PUBLISHED, 'saved', 'update') + }, + createSigner: () => (async () => { throw new Error('the fake rebackup never signs') }) as never, + discoverOwnedAgentBackupByTokenId: async () => ({ backup: { cid: 'snap-new' } }) as never, + ...overrides, + } +} + +async function capture(fn: () => Promise): Promise<{ result: T; out: string }> { + const orig = process.stdout.write + let out = '' + process.stdout.write = ((chunk: unknown) => { out += String(chunk); return true }) as typeof process.stdout.write + try { + return { result: await fn(), out } + } finally { + process.stdout.write = orig + } +} + +test('operator-save pulls the tools\' edits, publishes, and verifies the onchain pointer', async () => { + const spies: Spies = { pulls: 0, sends: 0, saved: [] } + const { result, out } = await capture(() => runOperatorSave(['--json'], deps(spies))) + assert.equal(result, 0) + const json = JSON.parse(out.trim()) + assert.equal(json.schema, 1) + assert.equal(json.published, true) + assert.equal(json.verification, 'verified') + assert.equal(spies.pulls, 1) + assert.equal(spies.sends, 1) + assert.equal(spies.saved.length, 1) +}) + +test('operator-save sends nothing when nothing changed since the last snapshot', async () => { + const spies: Spies = { pulls: 0, sends: 0, saved: [] } + const quiet = deps(spies, { + continuityWorkingTreeStatus: async () => ({ ready: true, localChangedAfterBackup: false, publishState: 'published' }) as never, + }) + const { result, out } = await capture(() => runOperatorSave(['--json'], quiet)) + assert.equal(result, 0) + assert.deepEqual(JSON.parse(out.trim()), { schema: 1, ok: true, skipped: true, reason: 'no-local-changes' }) + assert.equal(spies.pulls, 1, 'the tools\' edits are pulled before deciding') + assert.equal(spies.sends, 0) +}) + +test('operator-save reports a pointer that does not resolve to the new snapshot yet', async () => { + const spies: Spies = { pulls: 0, sends: 0, saved: [] } + const lagging = deps(spies, { discoverOwnedAgentBackupByTokenId: async () => ({ backup: { cid: 'snap-old' } }) as never }) + const { out } = await capture(() => runOperatorSave(['--json'], lagging)) + assert.equal(JSON.parse(out.trim()).verification, 'mismatch') +}) + +test('operator-save exits 3 without a key and never pins', async () => { + const spies: Spies = { pulls: 0, sends: 0, saved: [] } + const noKey = deps(spies, { readOperatorKey: () => ({ ok: false, reason: 'missing' }) as never }) + const { result, out } = await capture(() => runOperatorSave(['--json'], noKey)) + assert.equal(result, 3) + assert.equal(JSON.parse(out.trim()).schema, 1) + assert.equal(spies.sends, 0) +}) diff --git a/test/cli/restoreCommand.test.ts b/test/cli/restoreCommand.test.ts index db07706..738bbdf 100644 --- a/test/cli/restoreCommand.test.ts +++ b/test/cli/restoreCommand.test.ts @@ -5,7 +5,7 @@ import { getAddress, type Address, type Hex } from 'viem' import { runRestoreCommand, type RestoreSeams } from '../../src/cli/onchain/restore.js' import type { HistoryDeps } from '../../src/cli/history/shared.js' import type { EthagentConfig, EthagentIdentity } from '../../src/storage/config.js' -import type { Erc8004AgentCandidate } from '../../src/identity/registry/erc8004.js' +import { AgentTokenIdRequiredError, type Erc8004AgentCandidate } from '../../src/identity/registry/erc8004.js' import { createContinuitySnapshotChallenge, createContinuitySnapshotEnvelope } from '../../src/identity/continuity/envelope.js' import { addressFromPrivateKey, generatePrivateKey, signMessage } from '../../src/identity/crypto/eth.js' import { runRestoreAuthorize } from '../../src/identity/manager/restore/apply.js' @@ -184,3 +184,24 @@ test('restore with an identity previews a refetch and warns about local changes' assert.match(out.warnings.join('\n'), /local changes/) }) }) + +test('restore --owner reports why it could not list agents instead of an empty list', async () => { + const owner = getAddress('0xA1E9000000000000000000000000000000000001') + const d = deps(null) + const failing: RestoreSeams = { + ...seams(candidateFor(owner), envelopeFor(generatePrivateKey() as Hex)), + discoverOwner: async () => { + throw new AgentTokenIdRequiredError({ + ownerAddress: owner, + registry: { chainId: 8453, rpcUrl: 'https://mainnet.base.org', identityRegistryAddress: REGISTRY }, + balance: 0n, + detail: 'mainnet.base.org refused even a one-block query', + }) + }, + } + assert.equal(await runRestoreCommand(['--owner', owner, '--network', 'base', '--json'], d, failing), 1) + const out = d.io.json() + assert.match(String(out.error), /refused even a one-block query/) + assert.match(String(out.hint), /ETHAGENT_RPC_URL/) + assert.match(String(out.hint), /--network base/) +}) diff --git a/test/identity/manager/reconciliationProbes.test.ts b/test/identity/manager/reconciliationProbes.test.ts new file mode 100644 index 0000000..7016470 --- /dev/null +++ b/test/identity/manager/reconciliationProbes.test.ts @@ -0,0 +1,47 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { getAddress } from 'viem' +import { probeAgentUri, probeCustody } from '../../../src/identity/manager/shared/reconciliation/agentReconciliation/run.js' +import type { EthagentIdentity } from '../../../src/storage/config.js' + +const REGISTRY = getAddress('0x8004A169FB4a3325136EB29fA0ceB6D2e539a432') +const OWNER = getAddress('0xA1E9000000000000000000000000000000000001') +const VAULT = getAddress('0x6bdC0000000000000000000000000000000051d7') +const registry = { chainId: 8453, rpcUrl: 'https://mainnet.base.org', identityRegistryAddress: REGISTRY } + +function identity(extra: Partial = {}, state: Record = {}): EthagentIdentity { + return { + address: OWNER, ownerAddress: OWNER, createdAt: '', agentId: '45744', agentUri: 'ipfs://local', + state: { custodyMode: 'advanced', ...state }, ...extra, + } as EthagentIdentity +} + +function client(reads: Record): never { + return { + readContract: async (call: { functionName: string }) => { + if (!(call.functionName in reads)) throw new Error(`reverted: ${call.functionName}`) + return reads[call.functionName] + }, + } as never +} + +test('the agent URI probe reads tokenURI, the registry\'s own pointer', async () => { + const args = { registry, agentId: 45744n } + assert.equal((await probeAgentUri({ ...args, identity: identity(), client: client({ tokenURI: 'ipfs://local' }) })).kind, 'in-sync') + assert.equal((await probeAgentUri({ ...args, identity: identity(), client: client({ agentURI: 'ipfs://local' }) })).kind, 'unknown') +}) + +test('a differing pointer is the chain\'s unless a pinned snapshot is waiting here', async () => { + const args = { registry, agentId: 45744n, client: client({ tokenURI: 'ipfs://other-machine' }) } + assert.equal((await probeAgentUri({ ...args, identity: identity() })).kind, 'chain-newer') + const pending = identity({ metadataCid: 'bafy-new', backup: { cid: 'bafy-snap', metadataCid: 'bafy-old' } as never }) + assert.equal((await probeAgentUri({ ...args, identity: pending })).kind, 'local-newer') +}) + +test('custody is mid-flow only while the Vault holds the token and this machine has not saved Advanced', async () => { + const args = { registry, agentId: 45744n, expectedOwner: OWNER, vaultAddress: VAULT, client: client({ agentOwner: OWNER }) } + assert.equal((await probeCustody({ ...args, identity: identity() })).kind, 'advanced') + assert.equal((await probeCustody({ ...args, identity: identity({}, { custodyMode: 'simple' }) })).kind, 'mid-flow-uri-pending') + const empty = { ...args, client: client({ agentOwner: '0x0000000000000000000000000000000000000000' }) } + assert.equal((await probeCustody({ ...empty, identity: identity() })).kind, 'withdrawn') +}) diff --git a/test/identity/registry/erc8004Metadata.test.ts b/test/identity/registry/erc8004Metadata.test.ts index 6fc50f2..db9df6a 100644 --- a/test/identity/registry/erc8004Metadata.test.ts +++ b/test/identity/registry/erc8004Metadata.test.ts @@ -580,15 +580,18 @@ test('discoverOwnedAgentBackups uses the curated start block when fromBlock is o assert.equal(scannedFromBlock, 41_663_783n) }) -test('discoverOwnedAgentBackups skips log scans when balance is zero', async () => { +test('discoverOwnedAgentBackups with balance zero only scans for tokens sent into a Vault', async () => { const candidates = await discoverOwnedAgentBackups({ chainId: 8453, rpcUrl: 'https://mainnet.base.org', identityRegistryAddress: DEFAULT_ERC8004_IDENTITY_REGISTRY_ADDRESS, ownerHandle: '0x000000000000000000000000000000000000dEaD', publicClient: { - getLogs: async () => { - throw new Error('logs should not be scanned for an empty wallet') + getBlockNumber: async () => 41_663_783n, + getLogs: async (args: { args?: Record }) => { + assert.equal(args.args?.from, '0x000000000000000000000000000000000000dEaD') + assert.equal(args.args?.to, undefined) + return [] }, readContract: async (call: { functionName: string }) => { if (call.functionName === 'balanceOf') return 0n @@ -600,6 +603,61 @@ test('discoverOwnedAgentBackups skips log scans when balance is zero', async () assert.deepEqual(candidates, []) }) +test('discoverOwnedAgentBackups lists an agent its owner deposited into a Vault', async () => { + const owner = '0x000000000000000000000000000000000000dEaD' + const vault = '0x6bdC0000000000000000000000000000000051d7' + const stranger = '0x000000000000000000000000000000000000bEEF' + const candidates = await discoverOwnedAgentBackups({ + chainId: 8453, + rpcUrl: 'https://base.publicnode.com', + identityRegistryAddress: DEFAULT_ERC8004_IDENTITY_REGISTRY_ADDRESS, + ownerHandle: owner, + publicClient: { + getBlockNumber: async () => 41_663_783n, + getLogs: async (args: { args?: Record }) => { + assert.equal(args.args?.from, owner) + // 45744 went into the Vault; 12 was sold to a stranger and is not this wallet's. + return [{ args: { tokenId: 45_744n } }, { args: { tokenId: 12n } }] + }, + readContract: async (call: { address: string; functionName: string; args: unknown[] }) => { + if (call.functionName === 'balanceOf') return 0n + if (call.functionName === 'ownerOf') return call.args[0] === 45_744n ? vault : stranger + if (call.functionName === 'agentOwner') { + if (call.address.toLowerCase() === vault.toLowerCase()) return owner + throw new Error('not a Vault') + } + if (call.functionName === 'tokenURI') return agentDataUri('bafy-vaulted', 'vaulted agent') + throw new Error(`unexpected read: ${call.functionName}`) + }, + } as any, + }) + + assert.deepEqual(candidates.map(candidate => candidate.agentId), [45_744n]) + assert.equal(candidates[0]?.ownerAddress, owner) + assert.equal(candidates[0]?.backup?.cid, 'bafy-vaulted') +}) + +test('discoverOwnedAgentBackups says it could not check rather than listing nothing', async () => { + await assert.rejects(() => discoverOwnedAgentBackups({ + chainId: 8453, + rpcUrl: 'https://mainnet.base.org', + identityRegistryAddress: DEFAULT_ERC8004_IDENTITY_REGISTRY_ADDRESS, + ownerHandle: '0x000000000000000000000000000000000000dEaD', + publicClient: { + getBlockNumber: async () => 41_663_783n, + getLogs: async () => { throw new Error('block range too large') }, + readContract: async (call: { functionName: string }) => { + if (call.functionName === 'balanceOf') return 0n + throw new Error(`unexpected read: ${call.functionName}`) + }, + } as any, + }), (err: unknown) => { + assert.ok(err instanceof AgentTokenIdRequiredError) + assert.match(String(err.detail), /ETHAGENT_RPC_URL/) + return true + }) +}) + test('discoverOwnedAgentBackups verifies ownership before loading agent metadata', async () => { const owner = '0x000000000000000000000000000000000000dEaD' const other = '0x000000000000000000000000000000000000bEEF' @@ -659,8 +717,10 @@ test('discoverOwnedAgentBackups uses enumerable owner indexes before log scans', identityRegistryAddress: DEFAULT_ERC8004_IDENTITY_REGISTRY_ADDRESS, ownerHandle: owner, publicClient: { - getLogs: async () => { - throw new Error('logs should not be scanned when enumerable lookup works') + getBlockNumber: async () => 41_663_783n, + getLogs: async (args: { args?: Record }) => { + assert.equal(args.args?.to, undefined, 'the owner\'s own tokens come from the enumerable index, not logs') + return [] }, readContract: async (call: { functionName: string; args: unknown[] }) => { if (call.functionName === 'balanceOf') return 1n diff --git a/test/net/adaptive.test.ts b/test/net/adaptive.test.ts index 368b41e..af8c023 100644 --- a/test/net/adaptive.test.ts +++ b/test/net/adaptive.test.ts @@ -116,6 +116,28 @@ test('host measurements persist to the machine-local file and a corrupt file jus } }) +test('temp files a killed process left behind are swept on load; fresh ones are kept', async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'ethagent-hosts-')) + const file = path.join(dir, 'hosts.json') + const stale = `${file}.123.1.tmp` + const fresh = `${file}.456.2.tmp` + process.env.ETHAGENT_HOSTS_FILE = file + try { + await fs.writeFile(stale, '{}') + await fs.writeFile(fresh, '{}') + const old = new Date(Date.now() - 10 * 60_000) + await fs.utimes(stale, old, old) + resetHostStatsForTest(true) + rto('any.example') + await assert.rejects(fs.access(stale)) + await fs.access(fresh) + } finally { + process.env.ETHAGENT_HOSTS_FILE = '' + resetHostStatsForTest() + await fs.rm(dir, { recursive: true, force: true }) + } +}) + test('a host that never answers is dropped only after its backoff passes the ceiling', async t => { resetHostStatsForTest() t.mock.timers.enable({ apis: ['setTimeout'] }) diff --git a/test/run.ts b/test/run.ts index 6c36f33..8929041 100644 --- a/test/run.ts +++ b/test/run.ts @@ -22,6 +22,8 @@ import './cli/profileCommand.test.js' import './cli/custodyWrite.test.js' import './cli/setupCommands.test.js' import './cli/checkAndSkills.test.js' +import './cli/operatorSave.test.js' +import './identity/manager/reconciliationProbes.test.js' import './storage/config.test.js' import './storage/gitignore.test.js' import './storage/reset.test.js'