Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Fix guardian-gated inheritance never completing

nirholas1dda5db5e634
diff --git a/api/_lib/agent-recovery.js b/api/_lib/agent-recovery.js
index 7957ce34a..9e9f016b8 100644
--- a/api/_lib/agent-recovery.js
+++ b/api/_lib/agent-recovery.js
@@ -128,6 +128,31 @@ export function computeRequestPhase({ status, approvalsRequired, approvalsCount,
return { phase: 'ready', approved: true, approvalsCount, approvalsRequired, timelockUntil, msUntilUnlock: 0, msUntilExpiry };
}
+/**
+ * Decide what happens to the time-lock when a fresh approval count is in. Pure:
+ * the caller hands in the stored request row + the freshly-counted approvals.
+ *
+ * Returns null when nothing changes (still below threshold, or not in the
+ * approval-collecting phase), otherwise `{ until, announce }` — the time-lock
+ * deadline to write and whether this is a newly-opened window worth announcing.
+ *
+ * A RECOVERY request carries no `timelock_until` until the threshold is first met,
+ * so we open a fresh RECOVERY_TIMELOCK_MS safety window here and announce it. An
+ * INHERITANCE request already carries its grace deadline (set when the dead-man's
+ * switch armed), so we PRESERVE that deadline and don't re-announce — without this,
+ * a guardian-gated inheritance would meet threshold but never leave
+ * 'pending_approvals', so the cron (which completes only 'time_locked'/'ready'
+ * rows) could never finish the hand-off.
+ */
+export function thresholdTimelockTransition(row, approvalsCount, now = Date.now()) {
+ if (!row || row.status !== 'pending_approvals') return null;
+ if (Number(approvalsCount) < Number(row.approvals_required)) return null;
+ const until = row.timelock_until
+ ? new Date(row.timelock_until).toISOString()
+ : new Date(now + RECOVERY_TIMELOCK_MS).toISOString();
+ return { until, announce: !row.timelock_until };
+}
+
// ── user resolution ───────────────────────────────────────────────────────────
/** Resolve a guardian handle (username, @username, email, or uuid) → a user row. */
@@ -576,12 +601,17 @@ export async function recordVote({ agentId, requestId, guardianId, decision, req
await recordCustodyEvent({ agentId, userId: guardianId, eventType: 'recovery_approval', reason: decision, meta: { request_id: requestId } }).catch(() => {});
logAudit({ userId: guardianId, action: `recovery.${decision}`, resourceId: agentId, meta: { request_id: requestId }, req });
- // Re-evaluate: arm the time-lock the moment the threshold is first reached.
+ // Re-evaluate: arm/confirm the time-lock the moment the threshold is first
+ // reached. Recovery opens a fresh 48h window; a guardian-gated inheritance keeps
+ // its already-set grace deadline but still transitions out of pending_approvals
+ // so the cron can complete it.
const { approvals } = await countApprovals(requestId, agentId);
- if (approvals >= row.approvals_required && !row.timelock_until && row.status === 'pending_approvals') {
- const until = new Date(Date.now() + RECOVERY_TIMELOCK_MS).toISOString();
- await sql`UPDATE agent_recovery_requests SET status = 'time_locked', timelock_until = ${until}, updated_at = now() WHERE id = ${requestId} AND status = 'pending_approvals'`;
- await notifyParties(agentId, 'recovery_timelock_started', { request_id: requestId, unlock_at: until });
+ const transition = thresholdTimelockTransition(row, approvals);
+ if (transition) {
+ await sql`UPDATE agent_recovery_requests SET status = 'time_locked', timelock_until = ${transition.until}, updated_at = now() WHERE id = ${requestId} AND status = 'pending_approvals'`;
+ if (transition.announce) {
+ await notifyParties(agentId, 'recovery_timelock_started', { request_id: requestId, unlock_at: transition.until });
+ }
} else if (decision === 'approve') {
insertNotification(row.requester_id, 'recovery_approval_received', { agent_id: agentId, request_id: requestId, by_user_id: guardianId });
}
diff --git a/prompts/agent-wallets/11-social-recovery-inheritance.md b/prompts/agent-wallets/11-social-recovery-inheritance.md
deleted file mode 100644
index 046006ad2..000000000
--- a/prompts/agent-wallets/11-social-recovery-inheritance.md
+++ /dev/null
@@ -1,91 +0,0 @@
-# Task 11 — Social Recovery & Inheritance (custodial wallets that never die with the owner)
-
-> **Read [00-README-orchestration.md](./00-README-orchestration.md) first** — the
-> ownership model, custody rules, tokens, real APIs, hard rules, and the "improve
-> then delete this file" close-out. Depends on the Wallet HUD (**task 02**). This
-> task touches custodial keys and fund custody directly: read "safe by construction"
-> three times. Nothing here may ever expose, log, or leak a secret key.
-
-## Mission
-
-Agent wallets are custodial and funded — so "I lost access" or "the owner is gone"
-must not mean funds are lost forever. Build **social recovery + inheritance** for
-agent wallets: an owner designates guardians and/or a beneficiary, and through a real,
-auditable, threshold-approved process, control of an agent (and its wallet) can be
-safely recovered or transferred — without ever copying or exposing a private key.
-
-Why only three.ws: the wallet is bound to an account-owned agent, custody is
-server-held and audited, and ownership is a real DB invariant — so recovery can be a
-designed, safe product feature instead of a seed-phrase prayer. This is trust
-infrastructure that makes people comfortable funding an agent at all.
-
-## What exists (read it before building)
-
-- Ownership invariant: `agent_identities.user_id` is the single owner
- ([api/_lib/auth.js](../../api/_lib/auth.js)). Recovery/inheritance changes **who the
- owner is** — it never moves or exposes the encrypted key
- ([api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js),
- [api/_lib/secret-box.js](../../api/_lib/secret-box.js) — keys stay AES-256-GCM at
- rest, decrypted only at signing, every decrypt audited).
-- Custody trail: `GET /api/agents/:id/solana/custody` — every recovery/transfer event
- must be written here. Spend policy / freeze: `.../solana/limits`. Fork/transfer
- ownership patterns: [api/agents/fork.js](../../api/agents/fork.js).
-
-## How it must work
-
-1. **Designate guardians / beneficiary (owner-only).** The owner picks guardians
- (other real accounts) and/or a beneficiary, and a threshold (e.g. 2-of-3). Persist
- this server-side, validated. Removing/changing guardians is owner-only and audited.
-2. **Recovery (owner regains access).** A real, multi-step, threshold-approved flow:
- the requester proves identity, guardians approve out of band, a time-lock /
- challenge window elapses (anti-takeover), and on success **ownership transfers** to
- the recovering account. The key is never exported — `user_id` changes; the encrypted
- secret stays server-side and continues to sign for the new owner.
-3. **Inheritance / dead-man's switch.** Optional owner-configured inactivity trigger:
- after a real, owner-set period of no activity and explicit guardian/beneficiary
- confirmation (with notifications and a generous grace + cancel window), control
- passes to the beneficiary. Never auto-trigger without confirmation and a cancel
- path; the owner can always abort by simply being active.
-4. **Safety rails everywhere.** Time-locks, notifications to all parties, freeze the
- wallet during a contested recovery, full audit of every step in the custody trail,
- and hard server-side enforcement that only the current owner (or a completed,
- threshold-approved process) can change ownership. No client-only gating on anything
- that changes custody.
-
-## Innovation mandate
-
-- **Custody you can actually trust.** Self-custody usually means "lose the seed, lose
- everything." This is custody with a safety net — guardians, time-locks, inheritance —
- designed like a product, not a recovery email. That's a reason to fund an agent.
-- **Guardianship as a social bond.** Being someone's guardian is a real, visible role
- in the graph. Surface it tastefully. The agent can even "speak" its recovery status
- in character (read-only narration of real state).
-- **Make the scary parts calm.** Every irreversible step is explained, time-locked,
- cancellable until commit, and reversible by owner activity where possible. The copy
- and pacing are the craft here.
-- Invent beyond this where it raises the bar — but every approval, time-lock, and
- transfer is real and audited; never simulate a recovery or fake an approval.
-
-## States & edge cases (all designed)
-
-Recovery requested by an impostor (threshold + time-lock + owner cancel defeats it);
-owner returns mid-recovery (instant abort); guardian declines / is unreachable
-(threshold logic, honest stall state); dead-man's switch approached while owner is
-merely quiet (notify early, easy "I'm here" cancel); beneficiary same as a guardian;
-guardian account deleted; contested/duplicate recovery requests (serialize, freeze);
-network failure mid-transfer (atomic — ownership either fully transfers or not at
-all, never half); attempting any custody change without the completed process
-(refused server-side); a wallet with funds mid-recovery (frozen, never drained).
-
-## Definition of done
-
-Per the orchestration README. Plus: an owner can designate guardians/beneficiary with
-a threshold; a full recovery completes end-to-end and **transfers ownership** (the
-new owner can sign/withdraw; the old cannot) with **no key ever exported**; every step
-is in the custody trail; time-locks and cancel paths work; the dead-man's switch
-notifies and is cancellable; all custody changes enforced server-side; no console
-errors; responsive.
-
-When done: self-review + improvement pass, changelog entry, commit (explicit paths
-only, push to **both** remotes if asked), then **delete this file**
-(`prompts/agent-wallets/11-social-recovery-inheritance.md`).
diff --git a/tests/agent-recovery.test.js b/tests/agent-recovery.test.js
index ba7a846c1..0e2df91b4 100644
--- a/tests/agent-recovery.test.js
+++ b/tests/agent-recovery.test.js
@@ -16,7 +16,7 @@ vi.mock('../api/_lib/agent-trade-guards.js', () => ({ recordCustodyEvent: vi.fn(
const rec = await import('../api/_lib/agent-recovery.js');
const {
getRecoveryConfig, effectiveThreshold, computeRequestPhase, deadManStatus,
- RECOVERY_TIMELOCK_MS, RECOVERY_REQUEST_TTL_MS, isUuid,
+ thresholdTimelockTransition, RECOVERY_TIMELOCK_MS, RECOVERY_REQUEST_TTL_MS, isUuid,
} = rec;
const DAY = 24 * 60 * 60 * 1000;
@@ -126,6 +126,41 @@ describe('deadManStatus', () => {
});
});
+describe('thresholdTimelockTransition', () => {
+ const now = 1_700_000_000_000;
+
+ it('does nothing while approvals are below threshold', () => {
+ const row = { status: 'pending_approvals', approvals_required: 2, timelock_until: null };
+ expect(thresholdTimelockTransition(row, 1, now)).toBe(null);
+ });
+
+ it('opens a fresh 48h window for a recovery (no prior time-lock) and announces it', () => {
+ const row = { status: 'pending_approvals', approvals_required: 2, timelock_until: null };
+ const t = thresholdTimelockTransition(row, 2, now);
+ expect(t).not.toBe(null);
+ expect(t.announce).toBe(true);
+ expect(new Date(t.until).getTime()).toBe(now + RECOVERY_TIMELOCK_MS);
+ });
+
+ it('preserves a guardian-gated inheritance grace deadline and does not re-announce', () => {
+ // The dead-man's switch sets timelock_until (the grace deadline) at arm time.
+ // Reaching the guardian threshold must still leave pending_approvals (so the
+ // cron can complete it) WITHOUT extending or re-announcing the window.
+ const graceUntil = new Date(now + 14 * DAY).toISOString();
+ const row = { status: 'pending_approvals', approvals_required: 2, timelock_until: graceUntil };
+ const t = thresholdTimelockTransition(row, 2, now);
+ expect(t).not.toBe(null);
+ expect(t.announce).toBe(false);
+ expect(new Date(t.until).getTime()).toBe(new Date(graceUntil).getTime());
+ });
+
+ it('does nothing for a request no longer collecting approvals', () => {
+ for (const status of ['time_locked', 'ready', 'completed', 'cancelled']) {
+ expect(thresholdTimelockTransition({ status, approvals_required: 1, timelock_until: null }, 5, now)).toBe(null);
+ }
+ });
+});
+
describe('isUuid', () => {
it('accepts a v4 uuid and rejects junk', () => {
expect(isUuid('11111111-1111-4111-8111-111111111111')).toBe(true);