exportconstSECTION_LABEL: Record<Section,string>={spending:"Spending",tax:"Taxes",debt:"Debt and interest",bills:"Bills and subscriptions",cards:"Cards and rewards",saving:"Saving and investing"};
// Code-built moves set their own section; a move the AI adds (or a row from before 0019) falls back on its ref, then its kind.
why:`You paid ${money(f.interest90)} in card interest in 90 days, about ${money(f.interest90*365/90)} a year. Counted at half, since paying down takes time.`,
steps:["List each card's balance and interest rate.","Pay at least the full statement balance on new spending.","Put every spare dollar on the highest-rate card first.","Call the issuer and ask for a lower rate.","Don't open new cards until the balance is gone."],
message:{to:"Your card issuer",channel:"call",body:"Hi, I've been a customer for a while and I'm paying down my balance. Can you lower my interest rate? If not, is there a hardship or payment plan that would lower it?"},
links:[{label:"See your cards",url:"/cards"},{label:"See your accounts",url:"/accounts"}],
why:`You paid ${money(f.fees90)} in bank fees in 90 days. Banks often refund them when asked; counted at half.`,
steps:["Find the fee charges on your statement.","Message your bank and ask for a refund.","Ask how to avoid the fee from now on, like a minimum balance or direct deposit."],
message:{to:"Your bank",channel:"email",subject:"Fee refund request",body:`Hi,\n\nI was charged ${money(f.fees90)} in fees over the last 3 months. Could you refund them, and tell me how to avoid these fees from now on?\n\nThanks,\n[Your name]`},
...(typicalOver?[`In a typical month you spend about ${money(L.b!.spend)} and about ${money(L.b!.income)} comes in${L.b!.incomeTold?", from what you told us":""}.`]:[]),
...ms.map((m)=>`${monthName(m.month)}${m===ms.at(-1)&&ms.length>1?" so far":""}: you spent ${money(m.spend)} and ${money(m.income)} came in.`),
].join(" "),
steps:["Open this month's transactions and find the 3 biggest categories.","Set a budget for each one that ran over.","Pause anything you can until spending is below what comes in.","Check again at the end of the month."],
links:[{label:"See this month's spending",url:"/transactions"},{label:"Set budgets",url:"/budgets"}],
title:`Bring ${s.label} back to about ${money(s.avg)} a month`,
why:`${s.label} is ${money(s.now)} so far this month. Your average over the ${s.months>1?`${s.months} months before`:"month before"} was ${money(s.avg)}.`,
steps:[`Look through this month's ${s.label} charges for anything unusual.`,`Set a ${money(s.avg)} budget for ${s.label}.`,"Check it once a week until the month ends."],
links:[{label:`See ${s.label} charges`,url:`/transactions?category=${s.id}`},{label:`Set a ${money(s.avg)} budget`,url:`/budgets?set=${s.id}&amount=${r(s.avg)}`}],
why:`They cost ${money(subsYearly)} a year together. The biggest: ${names(subs.slice(0,3).map((b)=>`${b.name}${money(b.yearly)}`))}.`,
steps:["Open Recurring and go down the list.","Cancel anything you haven't used in the last month.","For the ones you keep, check for a cheaper plan or a yearly price.","Check next month's statement that cancelled charges stopped."],
title:`Undo the ${h.merchant} price rise or cancel it`,
why:`${h.merchant} went from ${money(h.from)} to ${money(h.to)} on ${h.date}, ${money(h.yearly)} more a year.`,
steps:[`Ask ${h.merchant} support for the old price or a cheaper plan.`,"If they say no, downgrade or cancel.","Set a reminder to check the next charge."],
message:{to:`${h.merchant} support`,channel:"email",subject:"Price increase on my account",body:`Hi,\n\nMy ${h.merchant} charge went from ${money(h.from)} to ${money(h.to)}. I'd like to keep my account at the old price or move to a cheaper plan. If that isn't possible, please tell me how to cancel.\n\nThanks,\n[Your name]`},
});
}
// 2. Starter emergency fund, 5. the full one. Not savings, so 0 toward the total.
constefGoal=goals.includes("Build an emergency fund");
if(L.b){
constwhat=L.b.essentialsAll?"spending":"essential spending (groceries, rent and utilities, transport, medical and loan payments)";
constnoSpare=L.spare!<1?`You have about ${money(0)} spare a month. Bring spending under income first.`:null;
title:`Build a ${money(L.starter!)} starter emergency fund`,
why:`The rule used here: one month of ${what}, or half a month of all spending if that is more. That is about ${money(L.starter!)}. You have ${money(L.b.cash)} available now.${efGoal?" You set an emergency fund as a goal.":""}`,
steps:["Use a separate savings account at an insured bank, or open one.","Set an automatic transfer for each payday, even a small one.","Put refunds and windfalls in it.","Use it only for real emergencies, then refill it."],
title:`Grow your emergency fund to ${money(L.full!)}`,
why:`That is ${FULL_MONTHS} months of ${L.b.essentialsAll?"spending":"essential spending"}. You have ${money(L.b.cash)} available now.${efGoal?" You set an emergency fund as a goal.":""}`,
steps:["Keep it in a savings account at an insured bank.","Raise the automatic transfer on each payday.","Stop once you reach the target and send the extra to the next step."],
});
}
// 3. The employer match, counted only as far as spare money covers the extra contribution (dollar for dollar).
gate: counted<value-1?`Needs about ${money(value/12)} a month; you have about ${money(L.spare!)} spare.`:null,
title:"Get your full 401(k) match",
why:`Your employer matches up to ${f.match.cap[0]}${f.match.cap[1]!==f.match.cap[0]?`-${f.match.cap[1]}`:""}% of pay. ${f.match.guessed?`If you put in ${r(f.match.pct)}%,`:`At ${r(f.match.pct)}%`} you likely leave about ${money(value)} a year unclaimed.`,
steps:["Ask HR how the match works and the rate you need.","Raise your contribution to at least the match cap in your 401(k) portal.","Check your next payslip shows the new rate."],
message:{to:"HR",channel:"email",subject:"Question about the 401(k) match",body:"Hi,\n\nCould you tell me how the 401(k) match works: the percent of pay it matches up to, and when it vests? I want to make sure I contribute enough to get all of it.\n\nThanks,\n[Your name]"},
why:`You set paying off debt as a goal. You owe ${names(by.map((x)=>`${money(x.total)} on ${label[x.k]}`))}.`,
steps:[
"Find the interest rate on each balance.","Pay every minimum on time, on autopay.","Put every spare dollar on the highest rate first, usually the card.","When one is paid off, add its payment to the next one.",
...(by.some((x)=>x.k==="student")?["For federal student loans, check studentaid.gov for an income-driven plan if payments are too high."]:[]),
],
links:[{label:"See your accounts",url:"/accounts"}],
});
}
// Goal targets: the monthly amount to hit each one, against what's spare. Within 5 years it's savings, next to the
// full emergency fund (step 5); further out it can be invested, next to tax-advantaged saving (step 6).
deadline:`${g.by}-01`,gate: first?`Needs about ${money(perMonth)} a month. ${first}`:null,
title:`Put ${money(perMonth)} a month toward ${g.goal==="Buy a home"?"your home":g.goal==="Save for kids' college"?"your kids' education":g.goal==="Plan a big purchase"?"your big purchase":g.goal}`,
why:[
`Your target is ${money(g.amount)} by ${when}${g.saved?`, with ${money(g.saved)} saved`:""}: ${money(left)} to go over ${months} months.`,
spare==null?"":short?`You have about ${money(spare)} spare a month, so at that pace it takes about ${Math.ceil(left/Math.max(spare,1))} months. Push the date out, lower the target, or free up spending.`:`You have about ${money(spare)} spare a month, which covers it.`,
].filter(Boolean).join(" "),
steps:[`Open ${where.label} for it. ${where.why}`,`Set an automatic transfer of ${money(perMonth)} each month${f.budget?" on payday":""}.`,"Keep your emergency fund separate from it.",`Check progress every few months and adjust the amount or the date.`],
});
}
// 6. Tax-advantaged room (HSA, 401(k), IRA in taxMoves), through the gate.
title: g.amount>=x.left-1?`Use your ${money(x.left)} of ${x.label} room`:g.amount>0?`Put about ${money(g.amount)} more in your ${x.label}`:`Add to your ${x.label} once the steps above are done`,
why:`You have ${money(x.left)} of ${x.label} room left, ${when}. ${g.amount>0?`${money(g.amount)} at ${pct(rate)} saves about ${money(g.amount*rate)} in federal tax.`:`Each $1,000 in saves about ${money(1000*rate)} in federal tax at ${pct(rate)}.`}${x.kind==="hsa"&&payroll?" Payroll contributions also skip Social Security and Medicare tax.":""}`,
steps:[`Check your ${x.label} balance and this year's contributions.`,x.kind==="k401"?"Raise your payroll contribution in your 401(k) portal.":payroll?"Raise your payroll contribution with HR or your benefits portal.":"Add money directly from your bank.","Keep your emergency fund and card payments covered first."],
});
}
// Outside the US: the local accounts in invest.ts, with no tax figure (local rates aren't checked).
title:`Use your ${x.label} room before ${x.deadline}`,
why:`You have ${money(x.left)} of ${x.label} room left for this tax year.`,
steps:[`Check what you've put into your ${x.label} this year.`,"Decide how much you can add without touching your emergency cash.",`Add it before ${x.deadline}.`],
});
}
if(t)taxMoves(f,t,money,add,L);
// After the basics (no card interest, full emergency fund, money spare): invest the rest, in the country's account order,
// with the mix set by how the user says they'd take a fall. General guidance only: broke never names a fund.
title:`Invest about ${money(L.spare!/ 2)} a month`,
why:`Card interest is clear and your emergency fund is full, with about ${money(L.spare!)} spare a month. Investing half leaves room for goals and surprises.${goals.includes("Retire early")?" You set retiring early as a goal, so the earlier you start the more it compounds.":""}${mix}`,
steps:[`Fill accounts in this order: ${investOrder(f.country).join(", then ")}.`,"Choose low-cost, broad index funds, and compare fees before you buy.","Set it to invest automatically each month.","Leave it alone through falls; check once or twice a year."],
});
}
// 7. Smaller wins: cards and bonuses only with no card interest and a starter fund. New credit otherwise is left out.
// Never a card outside the user's credit range (fitsCredit false).
const c = f.cards;
if (c?.best && L.creditOk && c.best.fitsCredit !== false) {
steps: [`Readthetermsonthe${best.issuer}pageandapply.`, ...(moved.length ? [`Move${names(moved.map((x)=>x.b.name))}tothenewcard.`] : []), "Use it for everyday spending.", "Set autopay to the full statement balance so you never pay interest."],
why: `Worthabout${money(c.bonusPick.bonus)}once,andyourusualspendingreachestheminimumintime.${c.bonusPick.fee?` The card has a ${money(c.bonusPick.fee)} yearly fee.`:""}`,
steps: ["Read the bonus terms on the issuer's page.", "Apply only if you can pay the card in full each month.", "Track your spending until you pass the minimum.", "Set autopay to the full balance."],
steps: ["Compare a few high-yield savings accounts at insured banks.", "Open one and link it to your checking.", `Move${money(f.idle.excess)}andkeep3monthsofspendinginchecking.`],
});
for (const b of f.bills.filter((x) => x.negotiable === "internet" || x.negotiable === "phone"))
steps: ["Look up what new customers pay for the same plan.", `Call${b.name}andaskfortheretentionorloyaltyteam.`, "Ask for a lower rate or a cheaper plan, and drop add-ons you don't use.", "If they say no, say you're ready to switch and ask again."],
message: { to: `${b.name}retentionteam`, channel: "call", body: `Hi,I've been a customer for a while and my bill is ${money(b.yearly / 12)} a month. I'veseenlowerpricesfornewcustomers.Whatcanyoudotobringmybilldown?OtherwiseI'm planning to switch.` },
});
for (const b of f.bills.filter((x) => x.negotiable === "insurance"))
why: `You pay ${b.name} ${money(b.yearly)} a year${b.nextDate ? `, next charge ${b.nextDate}` : ""}. Shopping around often saves about ${INSURANCE_CUT * 100}%.`,
steps: ["Find your current policy'scoveragelimitsanddeductible.", "Get3quotesforthesamecoveragefromotherinsurers.", "Compareprice,deductibleandcoveragelinebyline.", `Ask ${b.name} to match the best quote.`, "Switchatrenewal,andonlycanceloncethenewpolicyisactive."],
message: { to: "Landlord", channel: "email", subject: "Leaserenewal", body: "Hi,\n\nMyleaseendssoonandI'd like to plan ahead. Could you tell me the renewal rent? Would signing a longer lease lower it?\n\nThanks,\n[Your name]" },
});
// Doubtful data: no big move is built on it.
if (L.doubt)
for (const m of out)
if (m.yearly_impact >= 1000) Object.assign(m, { yearly_impact: 0, confidence: "low", gate: "This number looks off. Check your linked accounts first." });
return ladderSort(out);
}
// Ladder order, then value (yearly before one-time at the same value).
const rate = t.rate, rateWhy = t.guessed ? `Counted at ${pct(rate)}, the lowest bracket. Add your income in your profile for a closer number.` : `At your ${pct(rate)} bracket, from the low end of your income band.`;
title: `Get about ${money(t.refunds365 / 12)} a month back in your pay`,
why: `You got ${money(t.refunds365)} in tax refunds in the last 12 months. That is your own pay held back all year, so it isn'tcountedassavings.`,
steps: ["Run the IRS Tax Withholding Estimator with your latest payslip.", "Fill in a new Form W-4 with the result.", "Give the new W-4 to your employer or payroll portal.", "Check your next payslip shows less tax taken out.", "Leave a small margin so you don't owe next April."],
title: "Check your withholding so you don't owe again",
why: `Youpaid${money(t.payments365)}intaxfromyourbankinthelast12months.Withholdingthatcovers${SAFE_HARBOR.current}%ofthisyear's tax avoids the underpayment penalty.`,
steps: [
"Run the IRS Tax Withholding Estimator with your latest payslip.",
"If it shows a gap, add extra withholding on a new Form W-4.",
`No penalty if you paid ${SAFE_HARBOR.current}% of this year'staxor${SAFE_HARBOR.prior}%oflastyear's (${SAFE_HARBOR.priorHigh}% if last year'sAGIwasover${money(SAFE_HARBOR.highAgi)}).`,
"Sell the losing positions before Dec 31 to lock in the loss.",
"Don't buy the same or a substantially identical fund 30 days before or after the sale, in any account, including an IRA. That is the wash-sale rule.",
"To stay invested, buy a similar fund that isn't substantially identical.",
why: `${linked?`You have ${money(left)} of IRA room left`:`The ${year} IRA limit is ${money(limit)}`},openuntil${usDay(RETURN_DUE)}.${roth==="full"?`On ${bandText} a Roth IRA is open to you.`:roth==="partial"?`On ${bandText} your Roth amount may be reduced.`:`On ${bandText} a Roth IRA isn't open to you.`}${deductible&&g.amount>0?` A traditional IRA deduction on ${money(g.amount)} saves about ${money(g.amount*rate)}.`:""}`,
steps: [
linked ? "Check this year's contributions in your IRA account." : "Check whether you've put any money in an IRA this year.",
linked ? `Addthemoneyto${acct}by${usDay(RETURN_DUE)}andmarkitfor${year}.` : deductible && roth !== "none" ? "Pick Roth (tax-free later) or traditional (a deduction now)." : deductible ? "Use a traditional IRA and claim the deduction." : "Use a Roth IRA.",
linked ? "Set a monthly transfer so it fills over time." : "Open one at a low-cost brokerage.",
why: `Youpaid${money(t.studentLoan365)}towardstudentloansinthelast12months.Upto${money(STUDENT_LOAN_CAP)}oftheinterestisdeductiblewithoutitemizing;thepaymentsdon't show how much was interest.`,
steps: [
"Download Form 1098-E from your loan servicer in January.",
`Enter the interest on your return, up to ${money(STUDENT_LOAN_CAP)}.`,
`The deduction shrinks between ${money(s0)} and ${money(s1)} of modified AGI.`,
title: "Pay for childcare with a dependent care FSA",
why: `You spent ${money(t.childcare365)} on childcare in the last 12 months. From ${year} up to ${money(DEPENDENT_CARE_CAP)} can come from pre-tax pay. ${rateWhy}`,
steps: [
"Ask HR if your employer offers a dependent care FSA.",
"Sign up at open enrollment for what you expect to spend next year.",
"Send your childcare receipts to the plan to get paid back.",
export const PLAN_SYSTEM = `You are broke AI, the money assistant inside broke. You write the user's money plan: a ranked list of concrete moves that save or earn money.
Use only the facts given. Every number in "why" must come from the facts. Never invent prices, offers, phone numbers, email addresses or URLs.
Never say broke will do something for the user: give the steps they take. broke never files taxes, pays the IRS or changes withholding: tax moves are steps, drafts and links only.
Tax moves (kind "tax") use only the figures in their candidate. Never add a tax rule, limit, rate or date that isn't in the candidates or facts, and never apply US tax rules outside the US. A move with yearly_impact 0 stays 0: a smaller refund or a paid estimate is not savings.
Follow the priority ladder. Each candidate has a "step": 1 stop the bleeding (card interest, fees, spending above income), 2 a starter emergency fund, 3 the employer 401(k) match, 4 the rest of the debt, 5 a full emergency fund, 6 HSA, IRA and 401(k) room, 7 smaller wins (cards, bonuses, switching providers). Keep each candidate's step; the plan is ordered by it.
The affordability gate is already applied in code: a candidate's yearly_impact is only what the user can fund, and "gate" says why it is lower. Never raise it, never tell the user to put in more than the candidate says, and never drop a gate's point from the why.
Never recommend a new credit card, a sign-up bonus, a balance transfer card or any new credit while the user pays card interest or has no starter emergency fund ("new_credit_ok" false). Card and bonus moves you add then are dropped.
Never contradict a candidate's numbers: a rewrite may round a dollar figure the candidate has, never bring a new one. "once" means the value comes once, not every year; keep that wording.
You get candidate moves already worked out in code. Every candidate in steps 1 to 6, and every one worth $100 a year or more, must stay as its own move with its own ref (improve its wording); you may merge or drop the smaller ones in step 7, improve the wording, steps and drafted messages, and add at most 3 more moves only when the facts clearly show them (for example a large charge that looks shared with a friend, so a message asking them to settle up). No generic tips.
Reply with ONLY one JSON object, no prose, no code fence: