Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions cli/src/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,22 @@ export const CAPABILITIES: readonly CapabilityDefinition[] = [
profiles: profilesForMcp("robinhood_share_safe"),
outputSchema: "shareSafe",
},
{
id: "roth-deposit-plan",
cli: "roth-deposit-plan",
mcp: "robinhood_roth_deposit_plan",
access: "read",
profiles: ["full"],
outputSchema: "legacyObject",
},
{
id: "roth-deposit-inventory",
cli: "roth-deposit-inventory",
mcp: "robinhood_roth_deposit_inventory",
access: "read",
profiles: ["full"],
outputSchema: "legacyObject",
},
] as const;

const REGISTERED_MCP_NAMES = new Set(CAPABILITIES.map((definition) => definition.mcp));
Expand Down
20 changes: 20 additions & 0 deletions cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ import {
getTaxLotsForOrder,
planTaxLotSale,
submitTaxLotSale,
buildRothDepositPlan,
getRothDepositSourceInventory,
} from "./lib.js";
import type { OptionStrategyLegTemplate, OptionsStrategyPricingMode } from "./lib.js";

Expand All @@ -156,6 +158,24 @@ program
)
.version("1.1.0");

program
.command("roth-deposit-plan")
.description("Validate a $1 Roth deposit rail plan. Does not submit a transfer.")
.requiredOption(
"--input-json <json>",
"verified source, destination, fee, history, and eligibility data",
)
.action((opts: { inputJson: string }) =>
printJson(buildRothDepositPlan(JSON.parse(opts.inputJson))),
);

program
.command("roth-deposit-inventory")
.description(
"Read verified Roth destination and bank source × rail availability. Never submits a deposit.",
)
.action(async () => printJson(await getRothDepositSourceInventory()));

program
.option(
"--share-safe",
Expand Down
29 changes: 29 additions & 0 deletions cli/src/lib.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
import { execFile, execFileSync } from "node:child_process";
import { createHash, createPrivateKey, randomUUID, sign } from "node:crypto";
export {
buildRothDepositPlan,
buildRothDepositSourceInventory,
classifyRothDepositReceipt,
executeRothDeposit,
} from "./roth-deposit.js";
export type {
CapturedDepositRequest,
RothDepositHistoryRow,
RothDepositInput,
RothDepositPlan,
RothDepositReceipt,
RothDepositSourceInventory,
RothDepositSourceInventoryRow,
RothPaymentMethod,
} from "./roth-deposit.js";
import { buildRothDepositSourceInventory } from "./roth-deposit.js";
import {
appendFileSync,
existsSync,
Expand Down Expand Up @@ -2942,6 +2959,18 @@ export async function brokerageGetJson(
return JSON.parse(result.body || "{}");
}

/** Live source × rail read using only captured authenticated GET contracts. */
export async function getRothDepositSourceInventory(): Promise<import("./roth-deposit.js").RothDepositSourceInventory> {
const [accounts, relationships] = await Promise.all([
brokerageGetJson("https://bonfire.robinhood.com/transfer/accounts/"),
brokerageGetJson("https://cashier.robinhood.com/ach/relationships/"),
]);
return buildRothDepositSourceInventory(
Array.isArray(accounts?.results) ? accounts.results : [],
Array.isArray(relationships?.results) ? relationships.results : [],
);
}

/**
* Paginated read: follows Robinhood's `next` cursor and returns ALL `results` across pages.
*
Expand Down
209 changes: 209 additions & 0 deletions cli/src/roth-deposit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
/** The only requested rails. Wire is deliberately excluded: no wire-deposit contract was captured. */
export type RothPaymentMethod = "bank_standard" | "bank_instant" | "debit_card";

export type RothDepositRequestStatus =
"missing_exact_write_contract" | "missing_source_and_exact_write_contract";

export interface RothDepositSourceInventoryRow {
id: string;
method: RothPaymentMethod;
eligible: boolean;
requestStatus: RothDepositRequestStatus;
evidence: string[];
}

export interface RothDepositSourceInventory {
destination?: { accountId: string; accountType: string; depositEnabled: boolean };
sources: RothDepositSourceInventoryRow[];
/** There is no POST capture in the approved route map, so this never authorizes a send. */
executableMethods: RothPaymentMethod[];
}

export interface RothDepositHistoryRow {
amountUsd: string;
method: RothPaymentMethod;
destinationAccountId: string;
state: string;
}

export interface CapturedDepositRequest {
method: "POST";
url: string;
/** Sanitized, action-scoped body template. The executor replaces only amount fields supplied here. */
body: Record<string, unknown>;
amountField: string;
}

export interface RothDepositInput {
year: number;
contributionRoomUsd: string;
eligibilityVerified: boolean;
destination: { accountId: string; accountType: string; depositEnabled: boolean };
source: { id: string; method: RothPaymentMethod; eligible: boolean };
fee: { known: boolean; usd?: string };
history: RothDepositHistoryRow[];
capturedRequest?: CapturedDepositRequest;
}

export interface RothDepositPlan {
executable: boolean;
amountUsd: "1.00";
year: number;
method: RothPaymentMethod;
destination: { accountId: string; accountType: string };
sourceId: string;
gates: string[];
request?: CapturedDepositRequest;
}

const ONE_DOLLAR = "1.00";
const asCents = (value: string | undefined): number | undefined => {
if (!value || !/^\d+(?:\.\d{1,2})?$/.test(value)) return undefined;
const [whole, fraction = ""] = value.split(".");
return Number(whole) * 100 + Number((fraction + "00").slice(0, 2));
};

/** Pure, rail-neutral eligibility plan. It does not invent undocumented POST bodies. */
export function buildRothDepositPlan(input: RothDepositInput): RothDepositPlan {
const gates: string[] = [];
if (!Number.isInteger(input.year) || input.year < 2020)
gates.push("contribution year is invalid");
if (!input.eligibilityVerified) gates.push("Roth contribution eligibility is not verified");
if ((asCents(input.contributionRoomUsd) ?? -1) < 100)
gates.push("verified Roth contribution room is below $1.00");
if (input.destination.accountType !== "ira_roth" || !input.destination.depositEnabled) {
gates.push("destination is not a deposit-enabled Roth IRA");
}
if (!input.source.eligible) gates.push(`${input.source.method} source is not eligible`);
if (!input.fee.known || asCents(input.fee.usd) !== 0)
gates.push("fee is unknown or non-zero; no fee is authorized");

const duplicate = input.history.some(
(row) =>
row.amountUsd === ONE_DOLLAR &&
row.method === input.source.method &&
row.destinationAccountId === input.destination.accountId &&
/pending|queued|submitted|complete|completed|settled/i.test(row.state),
);
if (duplicate) gates.push("matching $1 deposit is already pending or completed");
if (input.capturedRequest && input.capturedRequest.method !== "POST")
gates.push("captured rail request is not a POST");
if (
input.capturedRequest &&
(!input.capturedRequest.url.startsWith("https://") || !input.capturedRequest.amountField)
) {
gates.push("captured rail request is incomplete");
}
return {
executable: gates.length === 0,
amountUsd: ONE_DOLLAR,
year: input.year,
method: input.source.method,
destination: {
accountId: input.destination.accountId,
accountType: input.destination.accountType,
},
sourceId: input.source.id,
gates,
request: input.capturedRequest,
};
}

export interface RothDepositReceipt {
submitted: boolean;
ambiguous: boolean;
receiptStatus: "accepted" | "rejected" | "transport_ambiguous";
status?: number;
body?: unknown;
}

/**
* Normalize the exact read contracts observed on the transfer page. `is_rtp_eligible`
* proves an instant-payment rail capability, not a deposit POST shape; no source means
* debit-card availability is explicitly unavailable rather than guessed.
*/
export function buildRothDepositSourceInventory(
accounts: Array<Record<string, unknown>>,
relationships: Array<Record<string, unknown>>,
): RothDepositSourceInventory {
const roth = accounts.find((account) => account.type === "ira_roth");
const destination = roth
? {
accountId: String(roth.id ?? roth.account_id ?? ""),
accountType: "ira_roth",
depositEnabled: roth.is_deposits_enabled === true,
}
: undefined;
const sources: RothDepositSourceInventoryRow[] = [];
for (const relationship of relationships) {
const id = String(relationship.id ?? "");
const rails = (relationship.available_payment_rails ?? {}) as Record<string, unknown>;
const verified = relationship.verified === true && relationship.state === "approved";
sources.push({
id,
method: "bank_standard",
eligible: verified,
requestStatus: "missing_exact_write_contract",
evidence: ["cashier/ach/relationships GET", "relationship verified/approved"],
});
if (rails.is_rtp_eligible === true) {
sources.push({
id,
method: "bank_instant",
eligible: verified,
requestStatus: "missing_exact_write_contract",
evidence: ["cashier/ach/relationships GET", "available_payment_rails.is_rtp_eligible"],
});
}
}
sources.push({
id: "unobserved",
method: "debit_card",
eligible: false,
requestStatus: "missing_source_and_exact_write_contract",
evidence: ["no debit-card source or write request captured"],
});
return { destination, sources, executableMethods: [] };
}

/** Stable status boundary for callers to decide whether a history read is mandatory. */
export function classifyRothDepositReceipt(response?: {
status: number;
body?: unknown;
}): RothDepositReceipt {
if (!response) return { submitted: false, ambiguous: true, receiptStatus: "transport_ambiguous" };
const submitted = response.status >= 200 && response.status < 300;
return {
submitted,
ambiguous: false,
receiptStatus: submitted ? "accepted" : "rejected",
status: response.status,
body: response.body,
};
}

/** One-shot executor: no retry, and transport uncertainty is surfaced as ambiguous. */
export async function executeRothDeposit(
plan: RothDepositPlan,
send: (
request: CapturedDepositRequest & { body: Record<string, unknown> },
) => Promise<{ status: number; body?: unknown }>,
): Promise<RothDepositReceipt> {
if (!plan.executable) throw new Error(`Roth deposit is not executable: ${plan.gates.join("; ")}`);
if (!plan.request)
throw new Error(
"Roth deposit rail contract has not been captured; refusing to invent a request",
);
const body = { ...plan.request.body, [plan.request.amountField]: plan.amountUsd };
try {
const response = await send({ ...plan.request, body });
return classifyRothDepositReceipt(response);
} catch (error) {
return {
submitted: false,
ambiguous: true,
receiptStatus: "transport_ambiguous",
body: { error: (error as Error).message },
};
}
}
65 changes: 65 additions & 0 deletions cli/test/roth-deposit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import {
buildRothDepositPlan,
buildRothDepositSourceInventory,
classifyRothDepositReceipt,
executeRothDeposit,
} from "../src/roth-deposit.js";

const eligible = {
year: 2026,
contributionRoomUsd: "10.00",
eligibilityVerified: true,
destination: { accountId: "roth-id", accountType: "ira_roth", depositEnabled: true },
source: { id: "bank-1", method: "bank_instant" as const, eligible: true },
fee: { known: true, usd: "0.00" },
history: [],
};

describe("Roth $1 deposit planner", () => {
it("creates a one-dollar plan only with verified eligibility, room, source and zero fee", () => {
expect(buildRothDepositPlan(eligible)).toMatchObject({
executable: true,
amountUsd: "1.00",
method: "bank_instant",
destination: { accountType: "ira_roth" },
});
});

it("blocks a duplicate before transport and never retries an ambiguous submission", async () => {
const plan = buildRothDepositPlan({
...eligible,
history: [{ amountUsd: "1.00", method: "bank_instant", destinationAccountId: "roth-id", state: "pending" }],
});
expect(plan.executable).toBe(false);
expect(plan.gates).toContain("matching $1 deposit is already pending or completed");
let calls = 0;
await expect(executeRothDeposit(plan, async () => { calls++; throw new Error("timeout"); })).rejects.toThrow(/not executable/);
expect(calls).toBe(0);
});

it("refuses an unknown fee or insufficient room without imposing a method-count cap", () => {
expect(buildRothDepositPlan({ ...eligible, fee: { known: false } }).executable).toBe(false);
expect(buildRothDepositPlan({ ...eligible, contributionRoomUsd: "0.99" }).executable).toBe(false);
expect(buildRothDepositPlan({ ...eligible, source: { id: "bank-2", method: "bank_standard" as const, eligible: true } }).executable).toBe(true);
});

it("inventories verified bank rails but makes every unobserved write contract non-executable", () => {
const inventory = buildRothDepositSourceInventory(
[{ id: "roth", type: "ira_roth", is_deposits_enabled: true }],
[{ id: "bank", verified: true, state: "approved", available_payment_rails: { is_rtp_eligible: true, is_rfp_eligible: false } }],
);
expect(inventory.destination).toEqual({ accountId: "roth", accountType: "ira_roth", depositEnabled: true });
expect(inventory.sources).toEqual([
expect.objectContaining({ id: "bank", method: "bank_standard", eligible: true, requestStatus: "missing_exact_write_contract" }),
expect.objectContaining({ id: "bank", method: "bank_instant", eligible: true, requestStatus: "missing_exact_write_contract" }),
expect.objectContaining({ method: "debit_card", eligible: false, requestStatus: "missing_source_and_exact_write_contract" }),
]);
});

it("classifies accepted, rejected, and transport-ambiguous receipts without retries", () => {
expect(classifyRothDepositReceipt({ status: 201, body: { id: "receipt" } })).toMatchObject({ submitted: true, ambiguous: false, receiptStatus: "accepted" });
expect(classifyRothDepositReceipt({ status: 422, body: { detail: "invalid" } })).toMatchObject({ submitted: false, ambiguous: false, receiptStatus: "rejected" });
expect(classifyRothDepositReceipt()).toMatchObject({ submitted: false, ambiguous: true, receiptStatus: "transport_ambiguous" });
});
});
Loading
Loading