# Personal finance

You build the user a household finance app from the guides in this skill, then help them use it. The app answers four questions at any point in the month:

1. How much can we safely spend until payday?
2. Where is each part of the budget against its target?
3. What still needs sorting?
4. When are we debt-free, and what moves that date?

Files in this skill's folder:
- `references/budget.md`: the budget interview and the month math.
- `references/review-queue.md`: sorting transactions, the auto-file rule, undo, and statement-file import.
- `references/debt-payoff.md`: the debt interview and the payoff engine.
- `references/savings.md`: hold-back and savings goals (optional module).
- `references/plaid-setup.md`: live bank data. Local app only.
- `references/backups.md`: encrypted nightly backups. Local app only.
- `references/checklist.md`: what you test before saying it is done.
- `example/`: working code from a household finance app this skill was written from. Copy from it. Do not run it as the user's app. `example/README.md` says what each file is.

Install locations: Claude Code reads this skill from `~/.claude/skills/personal-finance/` and starts it with `/personal-finance`. Codex reads it from `~/.codex/skills/personal-finance/` and starts it when the user mentions `$personal-finance`.

## Rules that always apply

- **Code does the math.** Every number the user sees comes from the app's code (the logic in the references, ported from `example/server/src/`). When you answer a money question in chat, read the number from the app or run its code. Never do the arithmetic in your head and present it as the app's answer.
- **Money is exact.** Store amounts as integer cents (SQLite, browser storage) or `numeric(14,2)` (Postgres). Never floating point in storage. Round to cents only for display and at the points the example code rounds.
- **One sign rule.** Inside the app, positive means money out of an account and negative means money in. This is Plaid's rule. Statement imports are converted to it on the way in.
- **The user's data stays where they put it.** Never send transactions, balances or account names to any service other than the one the user chose (their AI's own storage for hosted builds; their computer and Plaid for the local build). No analytics, no remote logging.
- **Secrets never go in files.** Plaid keys, the token-encryption key and the backup key live in the operating system's keychain. Never in `.env`, the profile, the repo, logs or chat. Ask the user to type secrets into the keychain prompt themselves; never ask them to paste a secret into the chat.
- **Logs hold counts and error codes only.** Never log amounts, merchant names, tokens or request bodies.
- **This is a tool, not advice.** Show the user their own numbers and the effect of their choices. Do not recommend lenders, cards, investments or products.

## Step 1: Check for an existing app

- Local tools (Claude Code, Codex): read `~/.config/personal-finance/profile.md`. If it names a built app, skip to "Running it".
- Chat assistants (Claude.ai, ChatGPT): ask, "Have you set up this finance app before? If so, paste the summary you saved." If they paste one, skip to "Running it".

## Step 2: Interview

Ask one question at a time. Wait for each answer. Keep each question to one or two plain sentences.

1. "Are you using ChatGPT or Claude?"
2. "Do you want it hosted, or on your own computer?" Explain in one line: hosted runs inside your AI's web app with nothing to install, and you type in or upload your transactions; on your computer keeps everything on your machine and can pull bank transactions in automatically through Plaid.

Pick the build:

| | Hosted | On your computer |
|---|---|---|
| Claude | Claude artifact | Claude Code builds a local app, started with `/personal-finance` |
| ChatGPT | ChatGPT Site | Codex builds the same local app, started with `$personal-finance` |

If the user wants it on their computer but you are a chat assistant without file and command tools, say so plainly. Tell them to install Claude Code (Claude) or Codex (ChatGPT), add this skill there, and start it again. Stop here.

3. "Which parts do you want?" Offer the list and recommend the first two:
   - Budget (income, bills, spending targets, what's safe to spend)
   - Debt payoff (debt-free date, snowball or avalanche, a month-by-month plan)
   - Review queue (sort each transaction into a category; it learns your habits)
   - Savings goals (named goals with a target and a date)
   - Local only: bank connection through Plaid, and encrypted nightly backups

   The review queue needs transactions. If they pick it, ask question 4.
4. "How will transactions get in?" Options by build:
   - Hosted: typed in by hand, or uploaded statement files (CSV exported from the bank's website).
   - Local: the same two, or Plaid. Plaid needs a Plaid account and works only in the local app. Say that before they choose it.
5. Local only: "Where should the app live? I suggest `~/personal-finance`." Then: "Where should backups go?" if they picked backups. Suggest a folder they already back up. Backups are encrypted, so a cloud-synced folder is fine.

Then run the interview for each module they picked, in this order: `budget.md`, `debt-payoff.md`, `savings.md`. Each reference lists its questions. Enter the answers into the app as its starting data; they do not go in the profile.

## Step 3: Save the profile

The profile holds setup facts only. No amounts, account names or balances.

- Local tools: write `~/.config/personal-finance/profile.md` with: assistant, build type, app folder, data folder, backup folder (if any), modules, transaction source, Plaid environment (sandbox or production, if used), port, date built. Set the file to mode 600.
- Chat assistants: write the same facts as a short summary and tell the user: "Save this text. Paste it back next time so I can pick up where we left off." Also tell them their numbers live in the app and its export file, not in this summary.

## Step 4: Build

Read the references for the chosen modules first. Then build to the plan below.

### Screens

- **Home**: this month's ledger (income received and still expected, then each spending group, bills in no category, debt minimums, savings, and the extra toward debt), plus cards for safe to spend until payday, remaining after expenses (local with a checking balance), savings goals, debt-free date, and how many transactions wait in To review. `example/client/src/Home.tsx` shows the layout.
- **Spending**: bills (paid, not seen yet, due) and each category's target, spent and average, by group.
- **To review**: the queue, a Recently reviewed list with Undo, and an All list with search.
- **Debts**: each debt's balance, APR, minimum and source; the paydown chart (this plan against a baseline line); This month (minimums plus extra, editable); Full schedule (one column per debt, one row per month). `example/client/src/Paydown.tsx` shows it.
- **Savings** (if picked): goals with saved against target and this month's set-aside.
- **Accounts** (local with Plaid): linked banks, each account's type, balances, Reconnect, Refresh now, and Trial slot count.
- **Settings**: payday rule, payoff method, export and import, backup status (local).

Make every screen work at phone width with no sideways scroll and tap targets at least 44 px.

### Data model

Use these records. The SQL in `example/server/migrations/` is the full local schema; hosted builds keep the same shapes as JSON.

- `accounts`: name, last four digits, type (checking, savings, credit, loan, investment, ignore, or none yet), balances.
- `transactions`: account, date, amount (Plaid sign), merchant name, bank description, pending flag, kind (spend, income, refund, transfer, card_payment, debt_payment, savings), category, category source (auto or user), needs review, removed.
- `merchants`: display name, match keys, mode (consistent or mixed), default category, files as (debt_payment, savings, transfer, income or none), last debt used.
- `categories`: name, group (everyday, nice, other).
- `bills`: name, merchant, usual amount, usual day, monthly or periodic, category, budget share, archived from.
- `bill_matches`: bill, month, transaction (or none), source.
- `income_sources`: name, merchant, usual amount, usual days.
- `months`: YYYY-MM, frozen at, hold-back. `targets`: month, category, amount.
- `debts`: name, source (linked or manual), account, manual balance and the date it was confirmed, rate and rate override (APR percent), minimum and minimum override, payoff order, due day.
- `debt_payment_matches`, `debt_month_plan`, `review_actions` (for undo), `savings_goals`, `savings_entries`, `settings` (payoff method, payday rule).

### Hosted build (Claude artifact or ChatGPT Site)

- One page. Port the pure logic from `example/server/src/payoff.ts`, `budget.ts`, `goals.ts` and `history.ts` into the page's script. Strip the TypeScript types, keep the function names, and keep the math line for line. Leave out the database code in `categorize.ts`; use its rules from `review-queue.md`.
- Save data with the storage the platform gives the page. Before you rely on it, check its current size limit and whether it persists between sessions, and tell the user in one line where their data lives (inside their Claude or ChatGPT account).
- Always add **Export** (downloads one JSON file with every record and a schema version) and **Import** (reads that file back, shows the counts, then replaces the data after the user confirms). Tell the user to export after each session. It is their backup.
- Statement upload: parse CSV in the page (see `review-queue.md`). Nothing is sent anywhere.
- No Plaid and no keychain. If the user asks for bank sync, explain that it needs the local app.

### Local build (Claude Code or Codex)

- One Node.js process (Node 20 or newer) that serves an API and the built web page, bound to `127.0.0.1` only. Default port 4317; pick another if it is taken and save it in the profile.
- Database: SQLite in the data folder by default (one file, easy to back up). Use Postgres only if the user already runs it and asks for it. Run migrations at startup; each one must be safe to run twice, like the examples.
- TypeScript is fine. React or plain pages are both fine. Keep the pure math in its own files with no imports from server code, as `payoff.ts` does, so the web page can import the same file and move the debt-free date live while a slider is dragged.
- The skill command starts and stops it. When the user starts the skill and the app is built, start the server in the background, wait for `GET /api/health` to answer, and open the browser to it. When they say "stop my finance app", stop the process.
- Secrets: read them at startup from the keychain (`example/server/src/keychain.ts` reads the macOS Keychain; `plaid-setup.md` covers Linux and Windows). Plaid access tokens are stored encrypted with AES-256-GCM under a data key that also lives in the keychain. Tokens never go to the browser.
- Bank sync runs inside the process while it is open (see `plaid-setup.md`). Do not add a login item, launch agent, service or remote access unless the user asks. If they ask, add it and explain how to remove it.
- Initialize a git repository in the app folder for the code. Add the data folder and any export files to `.gitignore` before the first commit. Never push it anywhere unless the user asks.

## Step 5: Test and report

Run every item in `checklist.md` that applies to the build and modules. Fix what fails. Then tell the user, in a few lines:
- what you built and where it lives,
- how to open it (local: start the skill with `/personal-finance` in Claude Code or `$personal-finance` in Codex; hosted: the artifact or Site link),
- where their data is and how it is backed up,
- what is still missing (for example, Plaid production access not active yet).

## Running it

When the profile shows a built app:

- **Local:** start the server and open the browser, as above. Then ask what they want to do.
- **Hosted:** remind them to open their artifact or Site, and to export when they finish.

Common requests:
- "Import my statement": follow the import steps in `review-queue.md`.
- "How's the budget look?": read this month from the app. Answer in up to five short lines, in this order: safe to spend until payday; categories over target or on pace to be (spent against target and days left); income received against expected, only if a deposit is late; the debt-free date and whether it moved; how many transactions wait in To review. If nothing is off, two lines are enough. Offer one next step.
- "What if I paid more on debt" or "what if I cut dining out": run the payoff engine with the changed numbers without saving, and show the debt-free date and total interest before and after.
- A new month: the app rolls over by itself (see `budget.md`). Offer to review last month's targets with the user.

---

The files named above are included below. Treat each one as the file it is named after. The example files a hosted build needs are included too; the rest of example/ is only in the zip.

---

<!-- references/backups.md -->

# Backups (local app only)

Hosted builds back up through the Export file (see `SKILL.md`). This file is for the local app.

## Nightly encrypted backup

- **When:** once a night while the app is running (the example runs at 02:40), plus a run on start if the last good backup is more than a day old. If the user wants it to run when the app is closed, ask first, then add an operating-system schedule (launchd, cron or Task Scheduler) and tell them how to remove it.
- **What:** a full copy of the database. SQLite: use the database's own online backup (`VACUUM INTO` or the driver's backup call) into a temp file; never copy the file while it is being written. Postgres: `pg_dump -Fc`.
- **Encrypt** the copy with AES-256-GCM, streamed, before it reaches the backup folder. File layout: 8-byte header `FINBAK1\n`, 12-byte random IV, ciphertext, 16-byte tag. Delete the plain temp file.
- **Name:** `personal-finance-YYYY-MM-DD.backup.enc`. Folder mode 700, files mode 600. Only encrypted files go in the backup folder.
- **Key:** a random 256-bit key in the keychain item `personal-finance-backup-key`, made on the first run and never rotated. Rotating it would make every older backup unreadable. It is the only way to read a backup, so tell the user to copy it into their password manager now (macOS: `security find-generic-password -s personal-finance-backup-key -w`, which they run themselves).
- **Keep** the newest 14 days, plus the newest backup of each of the last 8 weeks. Delete older ones after each good run. Never touch files that do not match the name pattern.
- **Status:** one line per run (file name, size, row counts, error code; never data) in the app's log folder, and the last result shown in the app's health check and at the bottom of Accounts or Settings. Show "stale" when there is no good backup in 36 hours.
- **By hand:** a "Back up now" button or command.

## Restore test

Run this after setup and after any change to the backup code. It must leave nothing behind.

1. Decrypt the newest backup into a private temp folder (never the backup folder).
2. Restore it into a throwaway database (`personal_finance_restore_test`, or a temp SQLite file).
3. Compare the row count of every table with the live database.
4. Drop the throwaway database and delete the temp files.
5. Print PASS or FAIL with counts only.

A sync between the backup and the test can make transaction counts differ. Back up, then test right away.

## Real restore

1. Stop the app.
2. Decrypt the chosen backup to a temp file outside any synced folder.
3. Restore it over the live database (SQLite: replace the file; Postgres: `pg_restore --clean --if-exists --no-owner`).
4. Delete the decrypted temp file.
5. Start the app and check Home loads.

Confirm with the user before step 3. It replaces everything since that backup.

---

<!-- references/budget.md -->

# Budget

The budget is one month at a time. It shows money in, what each part of the plan allows, what has been spent, and what is left over for extra debt payments. The math lives in `example/server/src/budget.ts`. It is pure: a loader gathers rows, and every number is decided in that file. Port it as is.

## Interview

Ask one question at a time. Offer a sensible default when the user is unsure, and say they can change any of it later.

1. **Income.** "Who or what pays into your household, and how much each time?" For each source: a name (for example "Paycheck" or "Side work"), the usual amount, and how often (monthly, twice a month, every two weeks, weekly). Then: "Which days does it usually land?" For twice a month, two days of the month. For every two weeks, one recent payday date.
2. **Bills.** "What bills do you pay every month? Name, usual amount and the day it is due is enough." Rent or mortgage, utilities, phone, internet, insurance, subscriptions. Then: "Any bills that come less often, like a yearly insurance payment?" Those are periodic. For each periodic bill, ask how much to set aside per month.
3. **Categories.** Offer a starter list and let them edit it:
   - Everyday: Groceries, Gas and transit, Household, Kids, Pets, Health
   - Nice-to-haves: Dining out, Shopping, Entertainment, Subscriptions, Travel
   - Other: Bank fees, Gifts
   Ask which bills belong in which category. A bill can also sit in no category; it is then planned on its own line.
4. **Targets.** "How much do you want to allow for each category this month?" Go group by group. A category's target includes its bills.
5. **Savings hold-back.** "How much do you want to set aside for savings each month before extra goes to debt?" Zero is fine.
6. **Payday** (only if income history will be thin at first): "When is your next payday?" Saved as days of the month in `settings.payday_rule`, used until deposit history takes over.

## The month

- **Months are created on demand.** At startup, after each local midnight, and on the first budget request in a new month, make sure the current month exists. A new month copies the previous month's targets and hold-back. Fill any months that were skipped.
- **Earlier months are frozen.** A frozen month is view only. Writes to its targets, hold-back or bill matches are refused (the example returns `409 month_frozen`).
- **Groups.** Every category is in Everyday, Nice-to-haves or Other. All three come out of the extra toward debt and count in safe to spend.

## What counts as spending

- Rows of kind `spend` and `refund` on checking, savings and credit accounts count. Refunds net against their category.
- Pending charges count right away. When the posted charge arrives it replaces the pending one. A pending charge older than 10 days that never posted is kept but no longer counted.
- Transfers between the user's own accounts, card payments, debt payments, savings moves and income are not spending.
- A charge with no category yet counts under "Not categorized yet" in Everyday until it is filed.

## Bills

- A bill is part of its category's target. `budget` is the share of the target the bill takes each month (a monthly bill's usual amount, or a periodic bill's set-aside).
- A charge matched to a bill counts once, under the bill's category.
- Status: **paid** (matched to a charge), **not seen yet** (its usual day has passed with no match), **due** (its day is still ahead), or **not every month** (periodic).
- Matching rules are in `review-queue.md`.

## Income

- **Received** is this month's `income` rows on checking and savings.
- **Still expected** comes from each source's deposit history (`incomePattern` in `budget.ts`):
  - gaps of 25 to 35 days: monthly, on the median day of month;
  - gaps of 12 to 18 days that are uneven, with paydays in at most two tight groups: twice a month on those days;
  - anything else (every two weeks, weekly): every median-gap days from the last deposit.
  - Days of month are read on a circle, so the 30th and the 1st are neighbors.
- A projected payday counts as seen when a deposit from that source landed within 3 days of it.
- With fewer than two deposits from a source, use its usual days from the interview.
- **Next payday**: the user's own payday days if set; else deposit history (income sources first, then any payer); else the sources' usual days.

## The ledger numbers

All results are positive dollars except the extra, which can go negative.

- **Planned extra toward debt** (the steady figure the payoff plan uses):

  received + still expected − bills in no category − Everyday targets − Nice-to-have targets − Other targets − debt minimums − savings counted − goals counted

  Savings counted is the larger of the hold-back and what was actually moved to savings this month. Goals counted is, per goal, the larger of its planned amount and what was set aside (see `savings.md`). A debt with a known balance of zero needs no minimum.
- **Cash-based extra** (current month, local build with a checking balance): checking balance (posted minus pending) − bills in no category still due − what each category still needs (target less bills' share less non-bill spend, never below zero, plus its bills still due) − minimums still due − hold-back not moved yet − goal amounts not set aside yet − money earmarked for goals. This is `Cashflow.extra` in `budget.ts`. "Remaining after expenses" is that extra less the extra debt payments the user has planned this month.
- **Safe to spend until payday**: (Everyday targets + Nice-to-have targets − spent so far in those groups) × days to next payday ÷ days left in the month, never below zero. With no next payday known, use the days left in the month.
- Hosted builds have no live checking balance unless the user types one in, so they show the planned extra.

## Averages

- A category's average is its non-bill spending per full month of history, plus its bills' share.
- Until there are 3 full months of bank or statement history, show the starting figure the user gave (or no average). From 3 months on, use up to the last 6 full months and label it "recent avg". `averagesFrom` in `budget.ts` and `fullHistoryMonths` in `history.ts` hold this rule.
- The paydown chart's baseline line uses these averages (see `debt-payoff.md`).

---

<!-- references/checklist.md -->

# Checklist before saying it is done

Run every item that applies to the build and the modules the user picked. Write the checks as automated tests where the build has a test runner (local), and run the rest by hand. Use test data, never the user's real data, for anything that writes. Report each item as pass or fail.

## Every build

1. **Two-debt payoff, checked by hand.** Debts A (1,000.00 at 12% APR, minimum 50) and B (3,000.00 at 24%, minimum 90), avalanche, extra 100, nothing paid this month:
   - money to debt each month is 240; order is B then A;
   - after month 0: A 960.00, B 2,870.00;
   - after month 1: A 919.60, B 2,737.40;
   - debt-free at month index 19, total interest 760.58 (to the cent, give or take 0.01);
   - snowball: index 20, interest 857.35; no extra: index 41, interest 1,750.36.
2. **Stuck plan.** One debt of 5,000.00 at 24% with minimum 50 and no extra. The plan says stuck and shows no debt-free date.
3. **Manual estimate.** Confirmed 1,200.00 on Jan 15 at 18% APR, payments of 100 on Feb 10 and Mar 10, today Mar 20. Estimate is 1,034.77 (Feb 1 +18.00, Feb 10 −100, Mar 1 +16.77, Mar 10 −100).
4. **Month rollover.** With an open month that has targets and a hold-back, move the date to the 1st of the next month. The new month exists with the same targets and hold-back; the old month is frozen; editing an old-month target is refused. Skip a month and check the missing one was filled too.
5. **Budget hand-check.** Received 2,000 and still expected 2,000; bills in no category 1,200; Everyday targets 1,500, Nice-to-haves 300, Other 50; minimums 140; hold-back 200, nothing saved yet; no goals. Planned extra toward debt is 610.
6. **Safe to spend.** Everyday plus Nice-to-have targets 1,800, spent 900, next payday in 7 days, 14 days left in the month. Safe to spend is 450.
7. **Live slider.** Changing a target on Home moves the debt-free date without a page reload.
8. **Phone width.** At 390 px wide, every screen fits with no sideways scroll, and every button is at least 44 by 44 px.

## Review queue (if picked)

9. **Auto-file rule.** A new merchant's first charge goes to To review. After the user files three of its charges to the same category, the fourth files itself. Filing one more to a different category makes the merchant mixed, and the next one goes to To review with a suggestion.
10. **Undo.** File a charge, undo it, and check its category, review flag, kind and the merchant's memory are back as they were.
11. **Not spending.** A card payment from checking, a transfer between two of the user's accounts, and a charge filed as Savings do not appear in any category's spent.
12. **Statement import** (if used). Import a five-row test CSV twice. The second import adds nothing. Signs come out right (a purchase is money out).

## Savings (if picked)

13. A goal of 1,200 added in January with a target date in December of the same year and no fixed amount plans 100 in January. Log 100 as set aside in January. In February it shows saved 100, earmarked 100, and plans 100 again (1,100 left over 11 months).

## Hosted build

14. **Export and import round trip.** Export, clear the data, import. Every count matches and Home shows the same numbers.
15. **Storage survives a reload.** Reload the page; the data is still there, or the page says clearly that it is not saved and points to Export.

## Local build

16. **Bound to this computer only.** The server listens on `127.0.0.1`, not `0.0.0.0`.
17. **No secrets in files.** Search the app folder (code, data, logs, `.env`) and the profile for the Plaid client ID, secret, data key and backup key values. Nothing is found.
18. **Start and stop.** The skill command starts it, opens the browser and the health check answers. "Stop my finance app" stops it.
19. **Backup restore test** (if backups picked). Run it; it prints PASS and leaves no temp files or throwaway database.

## Plaid (if picked)

20. **Sandbox link.** Link a Sandbox bank with `user_good` / `pass_good`. Accounts appear with no type, and the app asks for each one.
21. **Sync totals match.** After the first full sync, for each account, the count and the sum of amounts in the app equal what Plaid returned across every `/transactions/sync` page (added and modified, less removed), after dropping rows before the history start.
22. **Pending replaced.** A posted charge with a `pending_transaction_id` replaces its pending row; the total spent does not double.
23. **Tokens stay on the server.** No API response to the browser contains an access token, and the stored token is encrypted.
24. **Reconnect** uses update mode and does not add a slot.

---

<!-- references/debt-payoff.md -->

# Debt payoff

The payoff plan answers "when are we debt-free, and what moves that date?" The engine is `example/server/src/payoff.ts`. It is pure and has no imports, so the web page can import the same file and move the debt-free date live while a slider is dragged. Port it line for line.

## Interview

Ask one question at a time.

1. "List each debt you want in the plan: credit cards, car loan, student loans, medical bills, payment plans, money owed to family. A name for each is enough to start."
2. For each debt, in turn: "What do you owe on it today?", "What's the interest rate (APR)? It's on the statement. Say zero if there's none.", "What's the minimum payment each month?", "Which day is it due?" If they do not know the APR, enter it as unknown and flag it on the Debts screen. The plan treats an unknown rate as zero, so say that the date will be too early until they fill it in.
3. "How much can you put toward debt each month in total, minimums included?" If they picked the budget module, skip this. The budget's extra toward debt is the answer, and say so.
4. "Do you want to pay off the smallest balance first, or the highest interest rate first?" Explain in one sentence each:
   - **Snowball**: smallest balance first. You clear whole debts sooner, which keeps you going.
   - **Avalanche**: highest rate first. You pay the least interest.
   - **Custom**: you set the order.
   Then show all three side by side (`compareMethods`) with debt-free date and total interest, and let them pick.

A linked card or loan (Plaid) fills balance, rate, minimum and due date itself. A rate or minimum the user types is an override that the sync never writes over. "Use the bank's" clears it. The balance always comes from the bank.

## The engine

`simulate(debts, extra, method)`. Month 0 is the current month. Rates are APR in percent (24.99).

- **Order** is fixed from today's balances: snowball sorts by balance, smallest first; avalanche by rate, highest first, ties by smaller balance; custom by the user's order, unset last.
- **Money to debt each month** = every minimum of a debt with a balance + the extra when it is positive.
- **Each month**: add interest (balance × APR ÷ 12) to every unpaid debt. Pay each unpaid debt the smaller of its minimum, its balance and what is left of the month's money. Send what remains to the unpaid debts in payoff order, each taking up to its balance before the rest rolls to the next.
- **Stops** when everything is paid, after 600 months, or when the total owed has not dropped over the last 12 months. That last case is **stuck**: say plainly that the plan never finishes at these numbers.
- **Debt-free date** is the month of the last payment (`debtFreeIndex`), or none when stuck.

### This month

Money already paid this month counts once (`paid`). Month 0 is planned on the start-of-month balance, and each debt is then sent only what is left of its plan. A manual debt's estimate already includes this month's interest (`interestAccrued`), so month 0 does not add it again.

`planMonth` builds the This month table: each debt gets this month's minimum less what it was already paid, plus any extra the user placed on it by hand. The rest of the month's extra goes to debts in payoff order. The user may also change one debt's minimum for this month only. If their hand-placed extras add up to more than is available, keep them and show by how much (`over`). `simulatePlanned` runs the engine with this month planned that way and later months on the steady extra.

### Manual debts

A debt with no linked account keeps an estimated balance (`manualEstimate`): the last confirmed balance, plus one month's interest on each 1st since, minus payments matched to it after the confirmation day. Never below zero. When the user types a statement balance, that becomes the new confirmed balance and date.

## Screens

- **Debt-free card on Home**: the date at the current plan, money to debt per month, the method, and a chip that says how many months sooner or later than the baseline (the same engine on last month's targets).
- **Paydown chart**: total owed over time for this plan, against a "no cuts" line: the same engine with every category at its recent average and nothing held back (`noCutsExtra` in `budget.ts`). The gap is what the budget buys.
- **This month**: one row per debt: owed, paid so far, minimum (editable for this month), extra by hand, extra in payoff order, still to send, left after.
- **Full schedule**: one column per debt, one row per month. Mark each cell as paid off this month, getting the extra (more than the minimum), minimum only, or done (`scheduleCell`). Past months show what was actually paid.
- **Debts list**: balance, APR, minimum, source (linked or manual), estimated or confirmed, payoff order (custom only).

## Worked example

Use this to check a port (it is also in `checklist.md`). Two debts, avalanche, extra 100 per month, nothing paid yet this month:

| Debt | Balance | APR | Minimum |
|---|---|---|---|
| A | 1,000.00 | 12% | 50 |
| B | 3,000.00 | 24% | 90 |

- Money to debt each month: 50 + 90 + 100 = 240. Order: B, then A.
- Month 0: A gets 10.00 interest (1,010.00), pays 50, ends at 960.00. B gets 60.00 interest (3,060.00), pays 90 + 100 = 190, ends at 2,870.00.
- Month 1: A: 960.00 + 9.60 − 50 = 919.60. B: 2,870.00 + 57.40 − 190 = 2,737.40.
- Result: debt-free at month index 19 (the 20th month), total interest about 760.58.
- Snowball on the same numbers: debt-free at index 20, interest about 857.35. With no extra (minimums only): index 41, interest about 1,750.36.

---

<!-- references/plaid-setup.md -->

# Plaid setup (local app only)

Plaid connects the app to the user's banks, so transactions, balances and card or loan details arrive on their own.

**Plaid works only in the local app.** Plaid's secret key must stay on a server the user controls. A Claude artifact or ChatGPT Site is a web page with no private server, so it cannot hold the key. Say this before the user signs up. Hosted builds use statement files instead (see `review-queue.md`).

The code is in `example/server/src/plaid.ts` (all Plaid calls), `history.ts` (how far back history goes) and `keychain.ts` (reading secrets). The tables are in `example/server/migrations/0001`, `0002`, `0003`, `0006` and `0008`.

## 1. Plaid account and access tiers

1. The user creates a Plaid account at dashboard.plaid.com and a team for this app. They do this themselves; it asks for their own details.
2. **Sandbox** comes first. It is Plaid's test environment with test banks and fake data. It costs nothing and needs no approval.
3. **Real banks need production access.** Plaid offers several access tiers, and their limits and prices change. The app this skill is based on used Plaid's free **Trial** plan for new teams, which allowed **10 bank logins, permanently**: each bank connection (Plaid calls it an Item) uses a slot for good, and removing it does not give the slot back.
4. Before the user picks a tier, tell them to open Plaid's pricing page and their dashboard and confirm what their team is offered now: how many bank logins, which products (Transactions, Liabilities), and any cost. Do not quote prices or limits from this file as current.
5. Keys: the dashboard shows a **client ID** (the same in every environment) and a **secret** for each environment.

## 2. Secrets in the keychain

Never put a Plaid key in a file, `.env`, the profile, the repo or the chat. The user types each one into the keychain prompt; the app reads them at startup.

| Item | What it holds | Who makes it |
|---|---|---|
| `personal-finance-plaid-client-id` | Plaid client ID | the user |
| `personal-finance-plaid-secret` | Plaid secret for the environment in use | the user |
| `personal-finance-plaid-sandbox-secret` | optional: the Sandbox secret, kept for tests after the switch | the user |
| `personal-finance-data-key` | random 256-bit key that encrypts stored access tokens | the app, on first start |

Commands for the user to run (each prompts for the value, so it never shows on screen or in shell history):

- macOS: `security add-generic-password -a personal-finance -s personal-finance-plaid-secret -U -w` (leave `-w` last with no value so it prompts). Read with `security find-generic-password -s <name> -w`. Exit code 44 means missing.
- Linux (GNOME Keyring or KWallet through libsecret): `secret-tool store --label='personal-finance-plaid-secret' service personal-finance-plaid-secret`. Read with `secret-tool lookup service personal-finance-plaid-secret`. Install with the package manager (`libsecret-tools` on Debian and Ubuntu).
- Windows: use Windows Credential Manager. Pick a maintained way to read it from Node (a current npm package or PowerShell's SecretManagement module), tell the user which one, and test it reads and writes before storing a real secret.

Without the Plaid items the app still runs, and its health check says "Plaid not configured".

## 3. Sandbox first

- Set the environment with `PERSONAL_FINANCE_PLAID_ENV=sandbox` (the default in the example is production; flip that default for a new build so a fresh app starts in Sandbox).
- In Plaid Link, pick any test bank and sign in with `user_good` / `pass_good`. Plaid's Sandbox docs list other test users, including ones with richer transaction data. Check the current list there.
- Plaid's Sandbox endpoints can create a test Item without Link and add test transactions. Use them in tests.

## 4. Connecting a bank (Link)

1. Server calls `/link/token/create` with: `client_name`, `language: "en"`, `country_codes`, `user.client_user_id` (a stable id with no personal details, such as "household"), `products: ["transactions"]`, `additional_consented_products: ["liabilities"]` (so card and loan details work later without relinking, and banks without Liabilities still show), and `transactions.days_requested` (section 7). See `linkTokenRequest` in `plaid.ts`.
2. The page loads Plaid's Link script from Plaid's own site and opens Link with the link token.
3. Link's success callback hands the page a **public token**. The page sends it to the server.
4. Server calls `/item/public_token/exchange` and gets the **access token** and item ID. Encrypt the access token with AES-256-GCM under the data key and store it. It never goes to the browser and is never logged.
5. Server calls `/accounts/get` and stores each account with no type. The Accounts screen asks the user to set each one: checking, savings, credit, loan, investment, or ignore.
6. In production, confirm with the user before opening Link for a new bank, and show how many slots are used (`plaid_item_slots` keeps one row per Item ever created and is never deleted).
7. **Reconnect** (when Plaid returns `ITEM_LOGIN_REQUIRED` or `ACCESS_NOT_GRANTED`): a link token made with the Item's access token and no products (update mode). It does not use a new slot.
8. OAuth banks: check Plaid's current OAuth guide for whether a registered redirect URI is needed for a desktop web page on this tier. Register one only if it is.

## 5. Transactions sync

- `/transactions/sync` with the Item's stored cursor. Loop while `has_more` is true, 500 per page. Apply `added`, `modified` and `removed` for each page in one database transaction, then save the cursor.
- If Plaid returns `TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION`, restart the whole update from the cursor its first page used (up to 3 times).
- Before the first data is ready the status is `NOT_READY`; after the full backfill it is `HISTORICAL_UPDATE_COMPLETE`. A new Item syncs right away and every minute after until its history is in.
- Ask for `include_original_description: true` to keep the bank's own description.
- A posted transaction with `pending_transaction_id` replaces its pending row. A pending row older than 10 days that never posted stays stored but stops counting.
- **Schedule** while the app is open: a few times a day (the example uses 06:00, 09:00, 12:00, 15:00, 18:00 and 21:00 with a few minutes of jitter), one run at a time, plus a catch-up run 30 seconds after start if a slot was missed. **Refresh now** calls `/transactions/refresh` for every Item, then syncs a minute later.
- No webhooks. That keeps the app off the internet.
- Record each run with counts and an error code only.
- `/accounts/get` on each run refreshes balances.

## 6. Cards and loans

- `/liabilities/get` once a day (with the first sync of the day), after a new bank's first sync, and right after an account is typed as a card or loan. Limit it to those accounts.
- It fills balance, rate, minimum and next due date (`toLiabilities` in `plaid.ts`). Cards use the purchase APR only. Student loans, mortgages and other loans have their own fields; any field may be missing, and the Debts screen asks for what is.
- Typing an account as a credit card or loan makes a debt for it. The user's rate or minimum override is never written by the sync.

## 7. How far back history goes

- `days_requested` can be 1 to 730 (Plaid's default is 90; the example notes production asks for at least 30). It is **fixed when the bank is linked**: Plaid's docs say it cannot be changed after Transactions has been added to the Item, and Reconnect does not change it. Going further back later means removing the Item and linking the bank again, which uses another slot.
- Ask the user before the first link: "How far back do you want bank history? More gives better averages; the most is about two years."
- The example's rule: keep history from the 1st of the month before the link (linked Nov 7 keeps from Oct 1). It asks Plaid for the days from that date to today plus 7, clamped to 1 to 730, and drops any older row it receives. `historyStartFor` and `daysRequestedFor` in `history.ts`. Use the user's answer in place of that rule if they want more.

## 8. Switching to production

In order:

1. The user activates production access for the team in the Plaid dashboard.
2. The user stores the production secret in `personal-finance-plaid-secret` (the Sandbox one can move to `personal-finance-plaid-sandbox-secret`).
3. Delete Sandbox data: Sandbox Items, their accounts, transactions, sync runs, matches, and merchants and debts made only from them. Do a dry run first that shows counts, and run it in one database transaction. Keep categories, targets, bills, income sources, manual debts, months, settings and the slot ledger.
4. Stop the app, set `PERSONAL_FINANCE_PLAID_ENV=production`, start it again.
5. The user connects the first real bank from Accounts. Each new bank login uses a slot.

Ask for a typed confirmation before steps 3 and 4.

---

<!-- references/review-queue.md -->

# Review queue

Every transaction is worked out once when it arrives, and again when the bank changes it. Merchants the user always files the same way get filed silently. Everything else waits in **To review** with a suggestion. Unreviewed charges already count under their suggested category, so the budget is never empty while the queue is full.

The rules are in `example/server/src/categorize.ts` (the pure functions at the top: `decideKind`, `decideCategory`, `rememberedKind`, `suggestDebt`) and `example/server/src/merchants.ts` (name matching). The rest of `categorize.ts` is the Postgres version of the same flow.

## Order of work for each transaction

Skip accounts with no type, or typed `ignore` or `investment`.

1. **Kind.** `decideKind`:
   - A row with an opposite-signed twin on another of the user's accounts, same amount, within 3 days, is a move between their own accounts. Card account on one side and checking or savings on the other: `card_payment`. Loan on the other side: `debt_payment`. Otherwise `transfer`.
   - On a loan account: money in is `debt_payment`.
   - Money out of checking or savings that the bank tags as a credit card payment: `card_payment`. Tagged as a loan payment: `debt_payment`.
   - Other money out: `spend`.
   - Money into a credit card from an unlinked bank: `card_payment`; otherwise `refund`.
   - Money into checking or savings: a reversed bank fee is a `refund`; from a known income payer, or tagged income by the bank, `income`; from a merchant the user has bought from, `refund`; anything else `income`.
2. **Payee memory.** If the merchant remembers a choice (`files_as`), it decides first (`rememberedKind`): transfer and savings payees are filed on their own; an income payer's deposits are income; a debt payee's charges go to To review with its last-used debt preselected. The app never links a charge to a debt without the user's Confirm.
3. **Merchant.** Normalize the name (`normalizeMerchant`: lowercase, strip punctuation, card-processor prefixes, store and card numbers, and filler words). Try an exact key match first, then the best fuzzy match at a similarity of 0.6 or more (`findMerchant`). If nothing matches, create a merchant from the name.
4. **Bill match.** If the merchant belongs to an active bill (or has paid it before by the user's own match) and the amount is within 10% of the bill's usual amount, or of what the user last matched to it, link it to that month's bill. A bill already paid this month, or marked "none of these" by the user, is skipped. A matched charge is filed to the bill's category.
5. **Category.** `decideCategory`:
   - **Consistent**: the merchant has 3 or more confirmed charges and all of them are in one category. File silently.
   - **Mixed**: confirmed charges in more than one category. Suggest the category it lands in most (ties go to the most recent) and send it to To review.
   - **New**: no confirmed charges. Suggest the merchant's default category if it has one, and send it to To review.
   - Confirmed means filed silently or chosen by the user. A pending suggestion does not count.
6. **Bank fees.** Charges the bank tags as fees file to a "Bank fees" category by themselves. They do not count toward the merchant's habit, so a bank's other charges never start filing as fees.

Never overwrite a choice the user made (`category_source = user`). Changing an account's type works its rows out again, and the user's choices still stand.

## Filing choices

The picker (in To review, Recently reviewed, and every "Move to") offers:

- a **category**;
- **Paid a debt…**: the user picks which debt each time; the charge is linked to it and counts as a payment, not spending;
- **Savings**: money moved to savings; not spending;
- **Transfer, not spending**;
- **Income** (money coming in): also makes the payer an income source, so the budget follows its paydays.

The payee remembers non-category choices (`files_as`). Picking a category clears that memory. When the user files a charge, other open items from the same merchant are worked out again with the new history.

## Undo

Every choice can be undone. Store what it replaced in `review_actions`: the old category, source, review flag and kind; the old debt and bill matches; the merchant's old mode, default category and memory; any income source it created or relinked; and the other open rows it filed as a side effect. Undo puts all of it back in one database transaction. Undo is refused if a later choice on the same charge is still standing.

## Debt suggestions

For a debt payment whose payee has never been tied to a debt (`suggestDebt`): preselect the only debt whose name matches the payee, else the only debt whose minimum is within 10% of the amount. If neither is unambiguous, preselect nothing.

## Getting transactions in without Plaid

Hosted builds, and local builds without Plaid, take statement files.

1. Ask the user to download a CSV from their bank's website for one account and one date range. Most banks offer it under statements, activity or export.
2. Read the header row. Find the date, description, and amount columns. Some banks use separate debit and credit columns; some use a type column. Show the user the first five rows as you read them and ask them to confirm: which account this is, and whether a positive number means money in or money out.
3. Convert to the app's sign: positive is money out.
4. Skip rows already imported. Use the account, date, amount and description as the key, plus a count for identical rows on the same day (two identical coffees are two rows).
5. Run each new row through the steps above. There is no bank category tag, so step 1 relies on twin matching and the user's choices.
6. Report counts only: rows read, added, skipped as duplicates, sent to To review.

By hand: one form with date, account, amount, money in or out, and description. It goes through the same steps.

An optional local model on the user's computer can preselect a suggestion in To review. It never files anything on its own. Leave it out unless the user asks.

---

<!-- references/savings.md -->

# Savings (optional)

Two kinds of savings: a general monthly **hold-back**, and named **goals** with a target. Both come out of the extra toward debt before it is counted. The goal math is `example/server/src/goals.ts`, pure like `budget.ts`.

## Interview

1. "Do you want to save toward anything specific? For example an emergency fund, a car, a trip or holiday gifts." If no, only the hold-back from the budget interview applies.
2. For each goal: "How much do you need in total?", "By when? A month is enough, or no date.", "Do you want to put in a fixed amount each month, or should I work it out from the date?"
3. "Do you keep this money in a separate savings account, or does it stay in checking?" This decides how entries are logged (below). Both are fine.

## Hold-back

- Each month has its own hold-back, copied from the month before.
- **Saved this month** (`savedThisMonth` in `budget.ts`) is savings-kind payments (to a payee the user marked as Savings) plus transfers into a linked savings account from another of the user's accounts. A move between two savings accounts does not count.
- The ledger takes out the larger of the hold-back and what was actually saved. Saving more than planned leaves less for debt this month. Saving less does not free the hold-back until the month is over.

## Goals

A goal has a name, target amount, optional target date, optional fixed monthly amount, the month it was added, and the month it was archived (if it was).

**This month's amount** (`plannedFor`):
- With a fixed monthly amount: that amount, never more than what is left to the target.
- With a date and no fixed amount: what is left ÷ months to the date (this month included), rounded up to whole dollars so the goal is reached on time.
- Neither: nothing planned.

**Three ways money moves for a goal** (`savings_entries.kind`):
- **logged**: the user says they set it aside, but it stays in checking. It counts as saved, and it stays **earmarked** (kept out of the free money) every month after, until it is spent from the goal.
- **transfer**: a savings transfer linked to the goal. The money already left checking, so it is saved but not earmarked.
- **spent**: a charge paid from the goal. It comes off saved, and off the earmark first. The charge stops counting against its category.

Saved and earmarked are worked out month by month and never go below zero.

**What the ledger takes out per goal**: the larger of its planned amount and what was set aside this month (`goalTotals.counted`). The cash-based extra also takes out goal amounts not set aside yet and all earmarked money.

A goal is **reached** when saved is at or above its target. Archive a goal to stop it planning anything from that month on; earlier months keep it.

## Screens

- Home card: each goal's saved against target, and what is still to set aside this month.
- Savings screen: add, edit and archive goals; log money set aside; link a transfer or a charge to a goal.

---

<!-- example/server/src/payoff.ts -->

```ts
/**
 * The debt payoff engine, ported from an earlier budget artifact. Pure and dependency-free: the
 * client imports this same file to move the debt-free date live while a target slider is dragged,
 * so it must not import anything (no Node modules, no server code).
 *
 * Month 0 is the current month. Rates are APR in percent (24.99), as stored in debts.rate.
 */

export type PayoffMethod = "avalanche" | "snowball" | "custom";
export const PAYOFF_METHODS: readonly PayoffMethod[] = ["snowball", "avalanche", "custom"];
export const isPayoffMethod = (v: unknown): v is PayoffMethod => typeof v === "string" && (PAYOFF_METHODS as readonly string[]).includes(v);

/** The artifact's horizon: 50 years. */
export const MAX_MONTHS = 600;
/** No progress over this many months (total not lower than a year earlier) means the plan never finishes. */
export const STUCK_WINDOW = 12;
/** A balance at or under half a cent is paid off. */
const EPS = 0.005;

export interface PayoffDebt {
  id: number;
  balance: number;
  /** APR in percent. */
  rate: number;
  /** The effective minimum (the user's override, else Plaid's or the imported one). */
  min: number;
  /** Custom order position; null sorts last. */
  order: number | null;
  /**
   * Already paid toward it in month 0. `balance` is after these payments (a manual estimate takes
   * matched payments off; a bank balance has them posted), so the engine must not take them off again.
   */
  paid?: number;
  /**
   * `balance` already has this month's interest in it, so month 0 must not add it again. True for a
   * manual debt (its estimate adds a month's interest on each 1st, through this month's). A bank
   * balance only has what the bank has posted, so linked debts accrue month 0 here.
   */
  interestAccrued?: boolean;
}

export interface PayoffResult {
  /** Debt ids with a balance, in payoff order (fixed from today's balances). */
  order: number[];
  /** What goes to debt each month: minimums plus any extra. */
  monthly: number;
  /** Months simulated. When not stuck, the last one (months − 1) is the debt-free month. */
  months: number;
  interest: number;
  /** Debt id → month index it reached zero. */
  paidOff: Record<number, number>;
  /** Total owed at the end of each simulated month. */
  totals: number[];
  /** Each debt's balance at the end of each simulated month. */
  balances: Record<number, number>[];
  /** What each debt was paid in each simulated month (minimum plus any extra); unpaid debts are absent. Month 0 is the larger of the plan and what was already paid. */
  payments: Record<number, number>[];
  /** Month 0's plan for each debt, before what was already paid replaces it. */
  planned: Record<number, number>;
  /** Total owed before month 0. */
  start: number;
  stuck: boolean;
  /** Month index of the last payment; null when stuck or there is no debt. */
  debtFreeIndex: number | null;
}

/** The balance at the start of month 0, before this month's payments. */
const startBal = (d: PayoffDebt) => d.balance + Math.max(0, d.paid ?? 0);

/** Debts with a balance at the start of the month, in the method's order. */
export function payoffOrder(debts: PayoffDebt[], method: PayoffMethod): number[] {
  const list = debts.filter((d) => startBal(d) > 0);
  const byBal = (a: PayoffDebt, b: PayoffDebt) => startBal(a) - startBal(b);
  if (method === "snowball") list.sort(byBal);
  else if (method === "avalanche") list.sort((a, b) => b.rate - a.rate || byBal(a, b));
  else list.sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity) || byBal(a, b));
  return list.map((d) => d.id);
}

/** Minimums of every debt with a balance at the start of the month, plus the extra when there is any. */
export function monthlyToDebt(debts: PayoffDebt[], extra: number): number {
  return debts.filter((d) => startBal(d) > 0).reduce((s, d) => s + Math.max(0, d.min), 0) + Math.max(0, extra);
}

/**
 * Each month: interest (balance × APR ÷ 12) on every unpaid debt; each unpaid debt gets the
 * smaller of its minimum, its balance and what is left of the month's money; what remains goes to
 * the unpaid debts in payoff order. Stops when everything is paid, after 600 months, or when the
 * total has not dropped over the last 12 months (stuck).
 *
 * Month 0 is planned on the start-of-month balance (today's plus what was already paid), and each
 * debt is then sent only what is left of its plan after that: max(0, plan − paid). So what was paid
 * counts once, a payment above the plan counts in full, and the plan's remainder is still assumed to
 * go out before the month ends. Month 0's interest is on today's balance, and only for debts whose
 * balance doesn't already include it (`interestAccrued`).
 *
 * `month0` replaces that for month 0 only: debt id → what is still to send this month on top of what
 * was already paid (planMonth's `send`). `extra` then drives month 1 on.
 */
export function simulate(debts: PayoffDebt[], extra: number, method: PayoffMethod, month0?: Record<number, number>): PayoffResult {
  const order = payoffOrder(debts, method);
  const list = order.map((id) => debts.find((d) => d.id === id)!);
  const monthly = monthlyToDebt(debts, extra);
  const bal = new Map(list.map((d) => [d.id, d.balance]));
  const paidOff: Record<number, number> = {};
  const totals: number[] = [];
  const balances: Record<number, number>[] = [];
  const payments: Record<number, number>[] = [];
  const planned: Record<number, number> = {};
  const start = list.reduce((s, d) => s + d.balance, 0);
  const unpaid = (d: PayoffDebt) => bal.get(d.id)! > EPS;
  const already = (d: PayoffDebt, i: number) => (i === 0 ? Math.max(0, d.paid ?? 0) : 0);
  // What the plan can still send a debt: its balance, plus in month 0 what was already paid.
  const room = (d: PayoffDebt, i: number) => bal.get(d.id)! + already(d, i);
  let interest = 0;
  let stuck = false;
  let i = 0;

  for (; i < MAX_MONTHS && list.some((d) => room(d, i) > EPS); i++) {
    let pool = monthly;
    const pay: Record<number, number> = {};
    for (const d of list) {
      if (!unpaid(d) || (i === 0 && d.interestAccrued)) continue;
      const x = (bal.get(d.id)! * d.rate) / 100 / 12;
      bal.set(d.id, bal.get(d.id)! + x);
      interest += x;
    }
    // `plan` is what the month's money sends each debt; month 0's already-paid part comes off below.
    const plan: Record<number, number> = {};
    if (i === 0 && month0) {
      // The user's plan for this month (see planMonth): what is still to send, on top of what was paid.
      for (const d of list) if (room(d, i) > EPS) plan[d.id] = already(d, i) + Math.max(0, month0[d.id] ?? 0);
      pool = 0;
    }
    for (const d of i === 0 && month0 ? [] : list) {
      if (room(d, i) <= EPS) continue;
      const p = Math.max(0, Math.min(d.min, room(d, i), pool));
      pool -= p;
      plan[d.id] = p;
    }
    for (const d of list) {
      if (pool <= EPS) break;
      const left = room(d, i) - (plan[d.id] ?? 0);
      if (left <= EPS) continue;
      const p = Math.min(pool, left);
      pool -= p;
      plan[d.id] = (plan[d.id] ?? 0) + p;
    }
    for (const d of list) {
      const was = already(d, i);
      const send = Math.min(bal.get(d.id)!, Math.max(0, (plan[d.id] ?? 0) - was));
      bal.set(d.id, bal.get(d.id)! - send);
      if (plan[d.id] !== undefined || was > 0) pay[d.id] = was + send;
      if (i === 0 && plan[d.id] !== undefined) planned[d.id] = plan[d.id]!;
    }
    for (const d of list) if (!unpaid(d) && paidOff[d.id] === undefined) paidOff[d.id] = i;
    totals.push(list.reduce((s, d) => s + Math.max(0, bal.get(d.id)!), 0));
    payments.push(pay);
    balances.push(Object.fromEntries(list.map((d) => [d.id, Math.max(0, bal.get(d.id)!)])));
    const m = i + 1;
    if (m >= STUCK_WINDOW && list.some(unpaid)) {
      const before = m === STUCK_WINDOW ? start : totals[m - STUCK_WINDOW - 1]!;
      if (totals[m - 1]! >= before) {
        stuck = true;
        i++;
        break;
      }
    }
  }
  if (list.some(unpaid)) stuck = true;
  return {
    order,
    monthly,
    months: i,
    interest,
    paidOff,
    totals,
    balances,
    payments,
    planned,
    start,
    stuck,
    debtFreeIndex: stuck || i === 0 ? null : i - 1,
  };
}

// ---- this month's plan ------------------------------------------------------------------------

/** The user's entry for one debt in the current month. */
export interface MonthEntry {
  /** Extra they placed on it by hand. */
  extra: number;
  /** This month's minimum when it differs from the usual one; null keeps the usual one. */
  min: number | null;
}

/**
 * Where the month's extra comes from. "cash": the checking-based extra, already net of everything
 * paid this month (payments have left checking) and of the minimums still due. "plan": the planned
 * extra (income less the whole month's plan), which payments made so far haven't touched.
 */
export type PoolFrom = "cash" | "plan";

export interface MonthPlanRow {
  id: number;
  /** Today's balance, plus month 0's interest when the bank hasn't posted it yet: the most it can take. */
  owed: number;
  /** Paid to it so far this month. */
  paid: number;
  /** This month's minimum: the user's override, else the debt's usual one. */
  min: number;
  usualMin: number;
  minOverridden: boolean;
  /** The part of the minimum still to send: min less what was paid, never below zero, never above `owed`. */
  minDue: number;
  /** The user's extra as typed, and the part of it the debt can take. */
  extraTyped: number;
  extra: number;
  /** Applied in payoff order from what the user didn't place. */
  auto: number;
  /** Still to send this month: minDue + extra + auto. */
  send: number;
  /** The month's total to it: paid + send (the larger of paid and the minimum, plus the extras). */
  total: number;
  /** Left after this month. */
  after: number;
}

export interface MonthPlan {
  from: PoolFrom;
  /** The month's extra toward debt as the ledger has it (Home's "Extra toward debt"). */
  pool: number;
  /** What overridden minimums take from the pool (negative when one was lowered). */
  minChange: number;
  /** "plan" only: what was already paid above this month's minimums, which the planned extra still counts. */
  paidOver: number;
  /** The pool after those: what the user's extras and the automatic part share. Never below zero. */
  available: number;
  /** The user's extras, as the debts can take them. */
  manual: number;
  /** Applied in payoff order. */
  auto: number;
  /** Available but with nowhere to go: every debt is covered. */
  unassigned: number;
  /** The user's extras beyond what's available. Allowed, flagged. */
  over: number;
  /** Every debt with a balance at the start of the month, in payoff order. */
  rows: MonthPlanRow[];
  /** Debt id → still to send this month: simulate's `month0`. */
  send: Record<number, number>;
}

const r2 = (n: number) => Math.round(n * 100) / 100;

/**
 * This month's payments: every debt gets this month's minimum less what it was already paid, plus
 * any extra the user placed on it; what's left of the pool goes to the debts in payoff order, each
 * taking up to what it still owes before the rest rolls to the next. The user's extras may add up to
 * more than the pool: they are kept and `over` says by how much.
 */
export function planMonth(
  debts: PayoffDebt[],
  pool: number,
  from: PoolFrom,
  method: PayoffMethod,
  entries: Record<number, MonthEntry | undefined>,
): MonthPlan {
  let minChange = 0;
  let paidOver = 0;
  let manual = 0;
  // Debts with a balance at the start of the month: a debt paid off earlier this month stays listed.
  const rows: MonthPlanRow[] = payoffOrder(debts, method).map((id) => {
    const d = debts.find((x) => x.id === id)!;
    const e = entries[id];
    const bal = Math.max(0, d.balance);
    const owed = bal > EPS && !d.interestAccrued ? bal + (bal * d.rate) / 100 / 12 : bal;
    const paid = Math.max(0, d.paid ?? 0);
    // As the ledger counts it: nothing owed today needs no minimum (budget.ts effectiveMin).
    const usualMin = bal <= EPS ? 0 : Math.max(0, d.min);
    const min = bal <= EPS ? 0 : (e?.min ?? usualMin);
    const minDue = Math.min(owed, Math.max(0, min - paid));
    // The cash pool already took out the usual minimum's remainder; the planned one, the whole usual minimum.
    if (from === "cash") minChange += minDue - Math.min(owed, Math.max(0, usualMin - paid));
    else {
      minChange += min - usualMin;
      paidOver += Math.max(0, paid - min);
    }
    const extraTyped = Math.max(0, e?.extra ?? 0);
    const extra = Math.min(extraTyped, Math.max(0, owed - minDue));
    manual += extra;
    return { id, owed, paid, min, usualMin, minOverridden: e?.min != null && bal > EPS, minDue, extraTyped, extra, auto: 0, send: 0, total: 0, after: 0 };
  });
  const available = Math.max(0, pool - minChange - paidOver);
  let left = Math.max(0, available - manual);
  const autoPool = left;
  for (const row of rows) {
    const room = Math.max(0, row.owed - row.minDue - row.extra);
    const a = Math.min(left, room);
    row.auto = r2(a);
    left -= a;
  }
  const send: Record<number, number> = {};
  for (const row of rows) {
    row.send = r2(row.minDue + row.extra + row.auto);
    row.total = r2(row.paid + row.send);
    row.after = r2(Math.max(0, row.owed - row.send));
    row.minDue = r2(row.minDue);
    row.extra = r2(row.extra);
    row.owed = r2(row.owed);
    send[row.id] = row.send;
  }
  return {
    from,
    pool: r2(pool),
    minChange: r2(minChange),
    paidOver: r2(paidOver),
    available: r2(available),
    manual: r2(manual),
    auto: r2(autoPool - left),
    unassigned: r2(left),
    over: r2(Math.max(0, manual - available)),
    rows,
    send,
  };
}

/** The current month's pool and the user's entries, as GET /debts sends them. */
export interface MonthInput {
  pool: number;
  from: PoolFrom;
  entries: Record<number, MonthEntry | undefined>;
}

/** The payoff with this month planned by planMonth and later months on `extra`. */
export function simulatePlanned(debts: PayoffDebt[], extra: number, method: PayoffMethod, month?: MonthInput | null): PayoffResult {
  if (!month) return simulate(debts, extra, method);
  return simulate(debts, extra, method, planMonth(debts, month.pool, month.from, method, month.entries).send);
}

/** How the Full schedule marks one debt in one month. */
export type ScheduleCell = "off" | "attack" | "min" | "done";

/**
 * "off": this is the month it reaches zero. "attack": paid more than its minimum (it is getting the
 * extra). "min": paid its minimum only. "done": nothing paid (already gone). Half a dollar of slack
 * keeps rounding from reading as extra.
 */
export function scheduleCell(r: PayoffResult, debtId: number, min: number, month: number): ScheduleCell {
  const p = r.payments[month]?.[debtId] ?? 0;
  if (r.paidOff[debtId] === month) return "off";
  if (p > min + 0.5) return "attack";
  if (p > 0) return "min";
  return "done";
}

/** The Full schedule's cell for one debt in the current month: what is still to send, and its parts. */
export interface CurrentMonthCell {
  kind: ScheduleCell;
  /** Still to send this month (planMonth's `send`): the cell's number. */
  send: number;
  /** The part of the minimum still to send. */
  min: number;
  /** Extra still to send: the user's by hand plus the part applied in payoff order. */
  extra: number;
  /** This month's interest the send covers beyond today's balance; 0 when the send fits in the balance. */
  interest: number;
  /** Already paid to it this month. */
  paid: number;
}

/**
 * `balance` is today's balance as the column header shows it. The send can only exceed it by the
 * month's interest the bank hasn't posted yet (planMonth's `owed`), and `interest` says by how much.
 * "off": the plan pays it off this month, or it was paid off earlier this month.
 */
export function currentMonthCell(row: MonthPlanRow, balance: number): CurrentMonthCell {
  const bal = Math.max(0, balance);
  const extra = r2(row.extra + row.auto);
  const off = row.owed > EPS ? row.after <= EPS : row.paid > EPS;
  const kind: ScheduleCell = off ? "off" : extra > 0.5 ? "attack" : row.send > EPS || row.paid > EPS ? "min" : "done";
  const interest = row.send > bal + EPS ? r2(Math.min(row.send, row.owed) - bal) : 0;
  return { kind, send: row.send, min: row.minDue, extra, interest, paid: row.paid };
}

/** The debt getting the extra in a month: the first in payoff order paid more than its minimum. */
export function extraTarget(r: PayoffResult, mins: Record<number, number>, month: number): number | null {
  const pay = r.payments[month];
  if (!pay) return null;
  return r.order.find((id) => (pay[id] ?? 0) > (mins[id] ?? 0) + 0.5) ?? null;
}

export interface MethodSummary {
  method: PayoffMethod;
  interest: number;
  debtFreeIndex: number | null;
  stuck: boolean;
}

/** The three methods side by side on the same debts and money. */
export function compareMethods(debts: PayoffDebt[], extra: number, month?: MonthInput | null): MethodSummary[] {
  return PAYOFF_METHODS.map((method) => {
    const r = simulatePlanned(debts, extra, method, month);
    return { method, interest: r.interest, debtFreeIndex: r.debtFreeIndex, stuck: r.stuck };
  });
}

/**
 * A manual debt's balance today: the last confirmed balance, plus a month's interest at each month
 * start since, minus payments matched to it after the confirmation day. Never below zero.
 * Dates are YYYY-MM-DD.
 */
export function manualEstimate(
  confirmed: { balance: number; date: string },
  ratePct: number,
  payments: { date: string; amount: number }[],
  today: string,
): number {
  const events: { date: string; pay?: number }[] = payments
    .filter((p) => p.date > confirmed.date && p.date <= today && p.amount > 0)
    .map((p) => ({ date: p.date, pay: p.amount }));
  let ym = confirmed.date.slice(0, 7);
  for (;;) {
    ym = nextYm(ym);
    const first = `${ym}-01`;
    if (first > today) break;
    events.push({ date: first });
  }
  // Interest on the first of the month comes before that day's payments.
  const rank = (e: { pay?: number }) => (e.pay === undefined ? 0 : 1);
  events.sort((a, b) => a.date.localeCompare(b.date) || rank(a) - rank(b));
  let bal = confirmed.balance;
  for (const e of events) {
    if (e.pay === undefined) bal += (Math.max(0, bal) * ratePct) / 100 / 12;
    else bal -= e.pay;
  }
  return Math.max(0, Math.round(bal * 100) / 100);
}

function nextYm(ym: string): string {
  const y = Number(ym.slice(0, 4));
  const m = Number(ym.slice(5, 7));
  return m === 12 ? `${y + 1}-01` : `${y}-${String(m + 1).padStart(2, "0")}`;
}

/** YYYY-MM of month index `i` counted from `ym` (index 0). */
export function ymAt(ym: string, i: number): string {
  const y = Number(ym.slice(0, 4));
  const m = Number(ym.slice(5, 7)) - 1 + i;
  return `${y + Math.floor(m / 12)}-${String((((m % 12) + 12) % 12) + 1).padStart(2, "0")}`;
}
```

---

<!-- example/server/src/budget.ts -->

```ts
/**
 * Budget math for one month, per the skill's references/budget.md. Pure: the loader in
 * budget-service.ts gathers rows, everything that decides a number happens here, so it is unit-tested
 * on fake fixtures.
 *
 * Amounts in rows use Plaid's sign (positive = money out). Results are positive dollars.
 */
import { BUDGET_ROLES, type Kind, type Role } from "./categorize.js";
import { goalLines, goalTotals, type GoalEntryIn, type GoalIn, type GoalLine, type GoalTotals } from "./goals.js";
import { MIN_HISTORY_MONTHS } from "./history.js";

/** A deposit this many days either side of a usual payday counts as that payday's. */
export const PAYDAY_TOLERANCE_DAYS = 3;

export interface SpendRow {
  id: number;
  date: string;
  amount: number;
  kind: Kind;
  role: Role | null;
  pending: boolean;
  /** Pending more than 10 days and never posted: kept, not counted. */
  pendingExpired: boolean;
  categoryId: number | null;
  /** Linked to a bill: counted under its category like any charge, and shown there as the bill's. */
  billMatched: boolean;
  /** Role of the account on the other side of a transfer between our accounts; null when unpaired. */
  pairRole?: Role | null;
  /** Linked to a savings goal: a charge paid from it, or a savings transfer toward it. */
  goal?: "spent" | "transfer" | null;
}

export interface Deposit {
  date: string;
  /** Plaid sign: a deposit is negative. */
  amount: number;
  merchantId: number | null;
  role: Role | null;
  kind: Kind;
  pendingExpired: boolean;
}

export interface IncomeSourceIn {
  id: number;
  name: string;
  merchantId: number | null;
  usualAmount: number;
  usualDays: number[];
}

export interface BillIn {
  id: number;
  name: string;
  usualAmount: number;
  usualDay: number | null;
  frequency: "monthly" | "periodic";
  /** Share of its category's target this bill takes each month. */
  budget: number;
  categoryId: number | null;
  /** Counts this month: active, or archived in a later month. */
  active: boolean;
  /** This month's match: a charge, or the user's "none of these" (transactionId null). */
  match: { transactionId: number | null; amount: number | null; date: string | null; source: "auto" | "user" } | null;
}

/** A spending group: everyday, nice-to-haves, or other (neither, like bank fees). */
export type Bucket = "everyday" | "nice" | "other";

export interface CategoryIn {
  id: number;
  name: string;
  bucket: Bucket;
  /** The stored target, bills in this category included. */
  target: number | null;
  /** The plan's average for the category's non-bill items. */
  importedAvg: number | null;
  /** Countable non-bill spend over the history window (see BudgetInput.historyMonths). */
  historyTotal: number;
}

export interface DebtIn {
  /** Matches the month plan's entries (BudgetInput.debtPlan); a debt without one has no plan. */
  id?: number;
  minPayment: number | null;
  minOverride: number | null;
  /** Known balance; a paid-off debt (≤ 0) needs no minimum. Null when unknown. */
  balance: number | null;
  /** Payments linked to this debt, by YYYY-MM. */
  paidByMonth?: Record<string, number>;
}

/** Checking accounts now, as the bank last reported them. */
export interface CashIn {
  /** Sum of the banks' current balances, which leave pending charges out. */
  posted: number;
  /** Plaid-sign sum of live pending rows on those accounts (positive: on its way out). */
  pending: number;
  accounts: number;
  asOf: string | null;
}

export interface BudgetInput {
  ym: string;
  /** Local date, YYYY-MM-DD. For a past month pass its last day. */
  today: string;
  current: boolean;
  frozen: boolean;
  holdBack: number;
  categories: CategoryIn[];
  bills: BillIn[];
  /** This month's rows, any kind (transfers and card payments are filtered out here). */
  spend: SpendRow[];
  /** Income rows from about five months before today through today, this month included. */
  deposits: Deposit[];
  incomeSources: IncomeSourceIn[];
  debts: DebtIn[];
  /** Full months of bank history before this month, capped at 6. Averages use it from MIN_HISTORY_MONTHS. */
  historyMonths: number;
  /** The user's payday days when they set them by hand; null means derive from deposits. */
  paydayDays: number[] | null;
  /** Checking balances now; the current month's extra starts from them. Null for a past month or no balance. */
  cash?: CashIn | null;
  /**
   * The user's entries in the debt planner for this month, by debt id: extra typed on a debt and this
   * month's minimum when it differs from the usual one. Only the open current month reads them.
   */
  debtPlan?: Record<number, { extra: number; min: number | null }>;
  /** Savings goals and every entry toward them (all months; the math reads up to this one). */
  goals?: GoalIn[];
  goalEntries?: GoalEntryIn[];
}

// ---- dates -----------------------------------------------------------------------------------

const toDate = (ymd: string) => {
  const [y, m, d] = ymd.split("-").map(Number);
  return new Date(Date.UTC(y!, m! - 1, d!));
};
const fromDate = (d: Date) => d.toISOString().slice(0, 10);
const addDays = (ymd: string, n: number) => fromDate(new Date(toDate(ymd).getTime() + n * 86_400_000));
export const daysBetween = (a: string, b: string) => Math.round((toDate(b).getTime() - toDate(a).getTime()) / 86_400_000);
const dim = (ym: string) => {
  const [y, m] = ym.split("-").map(Number);
  return new Date(Date.UTC(y!, m!, 0)).getUTCDate();
};
const nextYm = (ym: string) => {
  const [y, m] = ym.split("-").map(Number);
  return m === 12 ? `${y! + 1}-01` : `${y}-${String(m! + 1).padStart(2, "0")}`;
};
/** Day `d` of a month, moved to the last day when the month is shorter. */
const dayIn = (ym: string, d: number) => `${ym}-${String(Math.min(d, dim(ym))).padStart(2, "0")}`;

const median = (xs: number[]) => {
  const s = [...xs].sort((a, b) => a - b);
  const mid = Math.floor(s.length / 2);
  return s.length % 2 ? s[mid]! : (s[mid - 1]! + s[mid]!) / 2;
};
const round2 = (n: number) => Math.round(n * 100) / 100;

/**
 * The median of days of month read on a circle, so the 30th and the 1st are neighbors: the circle
 * is cut at its widest gap and the plain median taken. Days past the end of the month wrap to the 1st.
 */
export function circularMedianDay(days: number[]): number {
  const s = [...days].sort((a, b) => a - b);
  let cut = 0;
  let widest = s[0]! + 31 - s[s.length - 1]!;
  for (let i = 1; i < s.length; i++) {
    if (s[i]! - s[i - 1]! > widest) {
      widest = s[i]! - s[i - 1]!;
      cut = i;
    }
  }
  const unrolled = [...s.slice(cut), ...s.slice(0, cut).map((d) => d + 31)];
  return ((Math.round(median(unrolled)) - 1) % 31) + 1;
}

// ---- income ----------------------------------------------------------------------------------

export type IncomePattern =
  | { mode: "days"; days: number[]; amount: number; from: "history" | "source" | "settings" }
  | { mode: "every"; gapDays: number; last: string; amount: number; from: "history" };

/**
 * How a stream of deposits repeats. Same-day deposits are merged. Needs two or more paydays.
 * Days of month are read on a circle (see circularMedianDay):
 *   gap 25–35 days → monthly on the median day of month;
 *   gap 12–18, uneven, with days of month in at most two tight groups → twice a month on those days;
 *   anything else (biweekly, weekly) → every median-gap days from the last deposit.
 */
export function incomePattern(deposits: { date: string; amount: number }[]): IncomePattern | null {
  const byDay = new Map<string, number>();
  for (const d of deposits) byDay.set(d.date, (byDay.get(d.date) ?? 0) + Math.abs(d.amount));
  const days = [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b));
  if (days.length < 2) return null;
  const gaps = days.slice(1).map(([d], i) => daysBetween(days[i]![0], d));
  const gap = median(gaps);
  const amount = round2(median(days.slice(-3).map(([, a]) => a)));
  const doms = days.map(([d]) => Number(d.slice(8)));
  if (gap >= 25 && gap <= 35) {
    return { mode: "days", days: [circularMedianDay(doms.slice(-3))], amount, from: "history" };
  }
  // A steady 14-day gap is biweekly even when its days of month happen to line up.
  const steady = gaps.every((g) => Math.abs(g - gaps[0]!) <= 1);
  if (gap >= 12 && gap <= 18 && !steady) {
    const recent = doms.slice(-6).sort((a, b) => a - b);
    const groups: number[][] = [];
    for (const d of recent) {
      const g = groups.find((x) => d - x[0]! <= PAYDAY_TOLERANCE_DAYS);
      if (g) g.push(d);
      else groups.push([d]);
    }
    // The month's last days and its first are one group.
    const last = groups[groups.length - 1]!;
    if (groups.length > 1 && groups[0]![0]! + 31 - last[last.length - 1]! <= PAYDAY_TOLERANCE_DAYS) groups[0]!.push(...groups.pop()!);
    if (groups.length <= 2 && groups.every((g) => g.length >= 2)) {
      return { mode: "days", days: groups.map((g) => circularMedianDay(g)).sort((a, b) => a - b), amount, from: "history" };
    }
  }
  return { mode: "every", gapDays: Math.max(1, Math.round(gap)), last: days[days.length - 1]![0], amount, from: "history" };
}

/** Pattern dates within [from, to], inclusive. */
export function paydaysBetween(p: IncomePattern, from: string, to: string): string[] {
  const out: string[] = [];
  if (p.mode === "days") {
    for (let ym = from.slice(0, 7); ym <= to.slice(0, 7); ym = nextYm(ym)) {
      for (const d of p.days) {
        const day = dayIn(ym, d);
        if (day >= from && day <= to && !out.includes(day)) out.push(day);
      }
    }
    return out.sort();
  }
  for (let day = addDays(p.last, p.gapDays); day <= to; day = addDays(day, p.gapDays)) if (day >= from) out.push(day);
  return out;
}

const isDeposit = (d: Deposit) => d.kind === "income" && !d.pendingExpired && d.role !== null && BUDGET_ROLES.includes(d.role);

export interface IncomeLine {
  sourceId: number;
  name: string;
  received: number;
  expected: number;
  /** Paydays still to come this month that haven't been seen. */
  expectedDates: string[];
  pattern: IncomePattern | null;
}

export interface IncomeResult {
  received: number;
  expected: number;
  /** Earliest still-expected date this month, for the "expected Nov 15" hint. */
  expectedBy: string | null;
  sources: IncomeLine[];
  nextPayday: string | null;
  paydayFrom: "history" | "source" | "settings" | null;
}

export function income(input: BudgetInput): IncomeResult {
  const monthStart = `${input.ym}-01`;
  const monthEnd = dayIn(input.ym, 31);
  const deposits = input.deposits.filter(isDeposit);
  const thisMonth = deposits.filter((d) => d.date >= monthStart && d.date <= monthEnd);
  const received = round2(thisMonth.reduce((s, d) => s - d.amount, 0));

  const sources: IncomeLine[] = input.incomeSources.map((s) => {
    const mine = deposits.filter((d) => s.merchantId !== null && d.merchantId === s.merchantId && d.date <= input.today);
    const pattern: IncomePattern | null =
      incomePattern(mine) ??
      (s.usualDays.length ? { mode: "days", days: [...s.usualDays].sort((a, b) => a - b), amount: s.usualAmount, from: "source" } : null);
    const seen = mine.filter((d) => d.date >= monthStart).map((d) => d.date);
    const got = round2(-mine.filter((d) => d.date >= monthStart).reduce((n, d) => n + d.amount, 0));
    let expectedDates: string[] = [];
    if (pattern && input.current && !input.frozen) {
      // A projected payday is seen when a deposit from the source landed within the tolerance of it.
      const unused = [...seen];
      expectedDates = paydaysBetween(pattern, monthStart, monthEnd).filter((day) => {
        const i = unused.findIndex((d) => Math.abs(daysBetween(d, day)) <= PAYDAY_TOLERANCE_DAYS);
        if (i >= 0) {
          unused.splice(i, 1);
          return false;
        }
        return day >= input.today;
      });
    }
    const amount = pattern?.amount ?? s.usualAmount;
    return {
      sourceId: s.id,
      name: s.name,
      received: got,
      expected: round2(expectedDates.length * amount),
      expectedDates,
      pattern,
    };
  });

  const expected = round2(sources.reduce((n, s) => n + s.expected, 0));
  const expectedBy = sources.flatMap((s) => s.expectedDates).sort()[0] ?? null;

  // Next payday: the user's days if they set them; else deposit history (sources first, then any income
  // merchant); else the sources' usual days.
  const horizon = addDays(input.today, 62);
  const after = (p: IncomePattern | null) => (p ? paydaysBetween(p, addDays(input.today, 1), horizon)[0] ?? null : null);
  let nextPayday: string | null = null;
  let paydayFrom: IncomeResult["paydayFrom"] = null;
  const pick = (dates: (string | null)[], from: IncomeResult["paydayFrom"]) => {
    if (nextPayday) return;
    const d = dates.filter((x): x is string => !!x).sort()[0];
    if (d) {
      nextPayday = d;
      paydayFrom = from;
    }
  };
  if (input.paydayDays?.length) pick([after({ mode: "days", days: input.paydayDays, amount: 0, from: "settings" })], "settings");
  pick(sources.filter((s) => s.pattern?.from === "history").map((s) => after(s.pattern)), "history");
  if (!nextPayday) {
    const byMerchant = new Map<number, Deposit[]>();
    for (const d of deposits) {
      if (d.merchantId === null || d.date > input.today) continue;
      byMerchant.set(d.merchantId, [...(byMerchant.get(d.merchantId) ?? []), d]);
    }
    pick([...byMerchant.values()].map((ds) => after(incomePattern(ds))), "history");
  }
  pick(sources.filter((s) => s.pattern?.from === "source").map((s) => after(s.pattern)), "source");

  return { received, expected, expectedBy, sources, nextPayday, paydayFrom };
}

// ---- bills -----------------------------------------------------------------------------------

export type BillStatus =
  | { state: "paid"; amount: number; date: string | null; transactionId: number }
  | { state: "not_seen" }
  | { state: "due"; day: number | null }
  | { state: "not_every_month" };

export interface BillLine {
  id: number;
  name: string;
  usualAmount: number;
  usualDay: number | null;
  frequency: "monthly" | "periodic";
  budget: number;
  categoryId: number | null;
  status: BillStatus;
  matchSource: "auto" | "user" | null;
}

/** A bill the user archived: kept (its match history with it) so it can be unarchived. */
export interface ArchivedBill {
  id: number;
  name: string;
  usualAmount: number;
  frequency: "monthly" | "periodic";
  budget: number;
  categoryId: number | null;
}

export function billStatus(b: BillIn, ym: string, today: string, current: boolean): BillStatus {
  const m = b.match;
  if (m && m.transactionId !== null && m.amount !== null) {
    return { state: "paid", amount: round2(m.amount), date: m.date, transactionId: m.transactionId };
  }
  if (b.frequency === "periodic") return { state: "not_every_month" };
  if (!current) return { state: "not_seen" };
  if (b.usualDay === null) return { state: "due", day: null };
  const due = dayIn(ym, b.usualDay);
  return due <= today ? { state: "not_seen" } : { state: "due", day: Number(due.slice(8)) };
}

// ---- the month -------------------------------------------------------------------------------

export interface CategoryLine {
  /** null for charges with no category yet. */
  id: number | null;
  name: string;
  bucket: Bucket;
  /** The full target, this category's bills included (never less than their share). */
  target: number;
  /** Bills' share of the target. */
  billPortion: number;
  /** Everything filed here, bill payments included. */
  spent: number;
  /** The part of `spent` that paid a bill. */
  billSpent: number;
  /** Non-bill average plus the bills' share, so it compares with the full target. */
  avg: number | null;
  avgFrom: "history" | "import" | null;
}

export interface BucketLine {
  target: number;
  spent: number;
}

/**
 * The current month from the checking balance: what's there now, minus what the month still has to
 * pay for. Pay not received yet is left out: the month runs on what's in checking. All positive
 * dollars except `extra`.
 */
export interface Cashflow {
  /** posted − pending: pending charges already count as spent, so they come off the balance too. */
  balance: number;
  posted: number;
  pending: number;
  accounts: number;
  asOf: string | null;
  /** Active monthly bills not matched to a charge yet and due later this month. */
  billsDue: number;
  billsDueCount: number;
  /** The part of billsDue with no category on the ledger: taken out on its own line. */
  unfiledBillsDue: number;
  /**
   * Per bucket: what each category still needs, its bills due later this month included. The
   * non-bill part is the target less bills' share less non-bill spend, never below zero; a bill
   * counts at its usual amount until a charge is matched to it, then not at all (the charge has
   * already left the balance).
   */
  targetsLeft: Record<string, number>;
  /** The part of targetsLeft that is bills due, per bucket. */
  billsDueIn: Record<string, number>;
  /** Each debt's minimum less what was paid to it this month, never below zero. */
  minimumsDue: number;
  /** The month's hold-back not moved to savings yet. */
  savingsToMove: number;
  /** This month's goal amounts not set aside yet (see goals.ts). */
  goalsToSetAside: number;
  /** Money logged toward goals that is still in checking: kept out of the extra every month until spent. */
  earmarked: number;
  extra: number;
  /**
   * What the user's debt plan still sends beyond minimumsDue: per debt, the month's minimum (their
   * override, else the usual one) plus their extra, less what was paid to it, less the usual
   * minimum's remainder already in minimumsDue. Negative when a lowered minimum frees money. The
   * part applied in payoff order isn't in it: that's only where `remaining` is suggested to go.
   */
  plannedExtraDue: number;
  /** extra less plannedExtraDue: Home's "Remaining after expenses". */
  remaining: number;
}

export interface Budget {
  ym: string;
  today: string;
  current: boolean;
  frozen: boolean;
  daysLeft: number;
  income: IncomeResult;
  /**
   * Active bills' budgets (`total`), what's matched as paid, and `unfiled`: the budget of bills in no
   * category on the ledger, the only bills planned outside a category. Archived bills are listed apart.
   */
  bills: { total: number; paid: number; unfiled: number; lines: BillLine[]; archived: ArchivedBill[] };
  everyday: BucketLine;
  nice: BucketLine;
  other: BucketLine;
  categories: CategoryLine[];
  debtMinimums: number;
  /** The planned hold-back for savings. */
  holdBack: number;
  /** Actually moved to savings this month (see savedThisMonth). */
  saved: number;
  /** What the ledger takes out for savings: the larger of the plan and what was saved. */
  savingsCounted: number;
  /** Savings goals active this month, with this month's amounts. */
  goals: GoalLine[];
  goalTotals: GoalTotals;
  /** The current month: from the checking balance (see cashflow); a past month, or no balance: planned. */
  extra: number;
  /** Income less the full plan (targets with their bills, unfiled bills, minimums, hold-back): the steady monthly figure the payoff uses. */
  plannedExtra: number;
  cashflow: Cashflow | null;
}

/** Counted as spending: spend and refund rows on budget accounts, pending included unless it went stale. */
export const countsAsSpend = (r: SpendRow) =>
  (r.kind === "spend" || r.kind === "refund") && !r.pendingExpired && r.role !== null && BUDGET_ROLES.includes(r.role) && r.goal !== "spent";

/**
 * Money moved to savings: savings-kind outflows (to a payee the user marked as savings), plus transfers
 * into a linked savings account from one of our other accounts (counted on the savings side, so a
 * move between two savings accounts is not counted). Stale pending rows don't count.
 */
export function savedThisMonth(rows: SpendRow[]): number {
  let saved = 0;
  for (const r of rows) {
    if (r.pendingExpired) continue;
    if (r.kind === "savings" && r.amount > 0 && r.role !== null && BUDGET_ROLES.includes(r.role)) saved += r.amount;
    else if (r.kind === "transfer" && r.role === "savings" && r.amount < 0 && r.pairRole && r.pairRole !== "savings") saved -= r.amount;
  }
  return round2(saved);
}

export const effectiveMin = (d: DebtIn) =>
  d.balance !== null && d.balance <= 0 ? 0 : Math.max(0, d.minOverride ?? d.minPayment ?? 0);

/** One debt's part of Cashflow.plannedExtraDue. */
function plannedBeyondMin(d: DebtIn, e: { extra: number; min: number | null } | undefined, ym: string): number {
  if (!e || (d.balance !== null && d.balance <= 0)) return 0;
  const paid = Math.max(0, d.paidByMonth?.[ym] ?? 0);
  const inMinimums = Math.max(0, effectiveMin(d) - paid);
  const planned = Math.max(0, Math.max(0, e.min ?? effectiveMin(d)) + Math.max(0, e.extra) - paid);
  // Nothing past the balance can be sent; minimumsDue isn't capped, so the cap never goes below it.
  const cap = d.balance === null ? Infinity : Math.max(d.balance, inMinimums);
  return Math.min(planned, cap) - inMinimums;
}

/** Where category averages (and the no-cuts baseline) come from for this many full months of history. */
export const averagesFrom = (historyMonths: number): "history" | "import" =>
  // One or two months of history would swing too far; the imported starting average holds until then.
  historyMonths >= MIN_HISTORY_MONTHS ? "history" : "import";

export function computeBudget(input: BudgetInput): Budget {
  const lastDay = dayIn(input.ym, 31);
  const daysLeft = input.current ? daysBetween(input.today, lastDay) + 1 : 0;
  const inc = income(input);

  const activeBills = input.bills.filter((b) => b.active);
  const billLines: BillLine[] = activeBills.map((b) => ({
    id: b.id,
    name: b.name,
    usualAmount: b.usualAmount,
    usualDay: b.usualDay,
    frequency: b.frequency,
    budget: b.budget,
    categoryId: b.categoryId,
    status: billStatus(b, input.ym, input.today, input.current),
    matchSource: b.match?.source ?? null,
  }));
  const archived: ArchivedBill[] = input.bills
    .filter((b) => !b.active)
    .map((b) => ({ id: b.id, name: b.name, usualAmount: b.usualAmount, frequency: b.frequency, budget: b.budget, categoryId: b.categoryId }));
  const billsTotal = round2(activeBills.reduce((s, b) => s + b.budget, 0));
  const billsPaid = round2(billLines.reduce((s, b) => s + (b.status.state === "paid" ? b.status.amount : 0), 0));
  const known = new Set(input.categories.map((c) => c.id));
  const filed = (categoryId: number | null): categoryId is number => categoryId !== null && known.has(categoryId);
  const portion = new Map<number, number>();
  for (const b of activeBills) if (filed(b.categoryId)) portion.set(b.categoryId, (portion.get(b.categoryId) ?? 0) + b.budget);
  // Bills with no category on the ledger have no target to sit in, so they're planned on their own.
  const unfiled = round2(activeBills.filter((b) => !filed(b.categoryId)).reduce((s, b) => s + b.budget, 0));

  // A bill's charge counts once: under the category it's filed to. The money math below still splits
  // each category into its bills (planned at budget, reserved at usual amount until paid) and the
  // rest, so a bill paid over or under its budget doesn't move the extra.
  const spentBy = new Map<number | null, number>();
  const billSpentBy = new Map<number | null, number>();
  for (const r of input.spend) {
    if (!countsAsSpend(r)) continue;
    const key = filed(r.categoryId) ? r.categoryId : null;
    spentBy.set(key, (spentBy.get(key) ?? 0) + r.amount);
    if (r.billMatched) billSpentBy.set(key, (billSpentBy.get(key) ?? 0) + r.amount);
  }
  /** Per category, its target and spend with its bills taken out: the cashflow reserves what's left of it. */
  const plan = new Map<number, { target: number; spent: number }>();

  const categories: CategoryLine[] = input.categories.map((c) => {
    const billPortion = round2(portion.get(c.id) ?? 0);
    const rest = Math.max(0, (c.target ?? 0) - billPortion);
    const spent = spentBy.get(c.id) ?? 0;
    const billSpent = billSpentBy.get(c.id) ?? 0;
    plan.set(c.id, { target: rest, spent: spent - billSpent });
    const fromHistory = averagesFrom(input.historyMonths) === "history";
    const avg = fromHistory ? c.historyTotal / input.historyMonths : c.importedAvg;
    return {
      id: c.id,
      name: c.name,
      bucket: c.bucket,
      target: round2(rest + billPortion),
      billPortion,
      spent: round2(spent),
      billSpent: round2(billSpent),
      // Bills at their budgeted share: the history and the import average leave them out.
      avg: avg === null ? null : round2(avg + billPortion),
      avgFrom: fromHistory ? "history" : c.importedAvg === null ? null : "import",
    };
  });
  // Charges still without a category count as everyday money spent until they are filed.
  const loose = round2(spentBy.get(null) ?? 0);
  if (loose !== 0) {
    const looseBills = round2(billSpentBy.get(null) ?? 0);
    categories.push({ id: null, name: "Not categorized yet", bucket: "everyday", target: 0, billPortion: 0, spent: loose, billSpent: looseBills, avg: null, avgFrom: null });
  }

  const bucket = (b: Bucket): BucketLine => {
    const cs = categories.filter((c) => c.bucket === b);
    return { target: round2(cs.reduce((s, c) => s + c.target, 0)), spent: round2(cs.reduce((s, c) => s + c.spent, 0)) };
  };
  const everyday = bucket("everyday");
  const nice = bucket("nice");
  const other = bucket("other");
  const debtMinimums = round2(input.debts.reduce((s, d) => s + effectiveMin(d), 0));
  // Saving more than planned leaves less for debt this month; saving less doesn't free the plan's
  // hold-back until the month is over, so the larger of the two is taken out.
  // A transfer linked to a goal counts toward that goal, not the general hold-back.
  const saved = savedThisMonth(input.spend.filter((r) => r.goal !== "transfer"));
  const savingsCounted = round2(Math.max(input.holdBack, saved));
  const goals = goalLines(input.goals ?? [], input.goalEntries ?? [], input.ym);
  const gt = goalTotals(goals);
  const plannedExtra = round2(
    inc.received + inc.expected - unfiled - everyday.target - nice.target - other.target - debtMinimums - savingsCounted - gt.counted,
  );

  let cashflow: Cashflow | null = null;
  if (input.current && !input.frozen && input.cash) {
    const due = billLines.filter((b) => b.frequency === "monthly" && b.status.state === "due");
    const dueBy = new Map<number, number>();
    for (const b of due) if (filed(b.categoryId)) dueBy.set(b.categoryId, (dueBy.get(b.categoryId) ?? 0) + b.usualAmount);
    const targetsLeft: Record<string, number> = {};
    const billsDueIn: Record<string, number> = {};
    for (const c of categories) {
      if (c.id === null) continue;
      const p = plan.get(c.id)!;
      const rest = Math.max(0, p.target - p.spent);
      const bills = dueBy.get(c.id) ?? 0;
      targetsLeft[c.bucket] = round2((targetsLeft[c.bucket] ?? 0) + rest + bills);
      billsDueIn[c.bucket] = round2((billsDueIn[c.bucket] ?? 0) + bills);
    }
    const minimumsDue = round2(input.debts.reduce((s, d) => s + Math.max(0, effectiveMin(d) - (d.paidByMonth?.[input.ym] ?? 0)), 0));
    const savingsToMove = round2(Math.max(0, input.holdBack - saved));
    const billsDue = round2(due.reduce((s, b) => s + b.usualAmount, 0));
    const unfiledBillsDue = round2(due.filter((b) => !filed(b.categoryId)).reduce((s, b) => s + b.usualAmount, 0));
    const balance = round2(input.cash.posted - input.cash.pending);
    const left = Object.values(targetsLeft).reduce((s, v) => s + v, 0);
    // Earmarked money is still in the balance, so it comes out here too; this month's logged part is
    // in it once (it's no longer in goalsToSetAside).
    const extra = round2(balance - unfiledBillsDue - left - minimumsDue - savingsToMove - gt.toSetAside - gt.earmarked);
    const plannedExtraDue = round2(
      input.debts.reduce((s, d) => s + (d.id === undefined ? 0 : plannedBeyondMin(d, input.debtPlan?.[d.id], input.ym)), 0),
    );
    cashflow = {
      balance,
      posted: round2(input.cash.posted),
      pending: round2(input.cash.pending),
      accounts: input.cash.accounts,
      asOf: input.cash.asOf,
      billsDue,
      billsDueCount: due.length,
      unfiledBillsDue,
      targetsLeft,
      billsDueIn,
      minimumsDue,
      savingsToMove,
      goalsToSetAside: gt.toSetAside,
      earmarked: gt.earmarked,
      extra,
      plannedExtraDue,
      remaining: round2(extra - plannedExtraDue),
    };
  }
  const extra = cashflow?.extra ?? plannedExtra;

  return {
    ym: input.ym,
    today: input.today,
    current: input.current,
    frozen: input.frozen,
    daysLeft,
    income: inc,
    bills: { total: billsTotal, paid: billsPaid, unfiled, lines: billLines, archived },
    everyday,
    nice,
    other,
    categories,
    debtMinimums,
    holdBack: round2(input.holdBack),
    saved,
    savingsCounted,
    goals,
    goalTotals: gt,
    extra,
    plannedExtra,
    cashflow,
  };
}

/**
 * The extra toward debt with no cuts: every category at its recent average (its target when it has
 * no average yet), bills as budgeted (inside their category's average, or on their own when in no
 * category), nothing held back. The paydown chart's gray line. Charges not categorized yet have
 * neither, so they count as nothing here.
 */
export function noCutsExtra(b: Budget): number {
  const spend = b.categories.reduce((s, c) => s + (c.id === null ? 0 : (c.avg ?? c.target)), 0);
  return round2(b.income.received + b.income.expected - b.bills.unfiled - spend - b.debtMinimums);
}
```

---

<!-- example/server/src/goals.ts -->

```ts
/**
 * Savings goals for one month. Pure, like budget.ts: the loader gathers goals and entries, the
 * numbers are decided here.
 *
 * Three ways money moves for a goal:
 *  - logged: the user says they set it aside but it stays in checking. It counts as saved, and it stays
 *    earmarked (kept out of the free money) every month after, until it's spent from the goal.
 *  - transfer: a savings transfer linked to the goal. That money already left checking, so it is
 *    saved but not earmarked.
 *  - spent: a charge paid from the goal. It comes off saved, and off the earmark first (money logged
 *    in checking is what usually pays for it); the charge stops counting against its category.
 */

export type GoalEntryKind = "logged" | "transfer" | "spent";

export interface GoalIn {
  id: number;
  name: string;
  target: number;
  /** YYYY-MM-DD, or null for no date. */
  targetDate: string | null;
  /** The user's fixed amount a month; null to suggest one from the date. */
  monthlyAmount: number | null;
  /** Month the goal was added, YYYY-MM: it plans nothing before it. */
  createdYm: string;
  /** Month it was archived, YYYY-MM: from then on it plans and earmarks nothing. Null when active. */
  archivedYm: string | null;
}

export interface GoalEntryIn {
  id: number;
  goalId: number;
  ym: string;
  /** Positive dollars. */
  amount: number;
  kind: GoalEntryKind;
  transactionId: number | null;
}

export interface GoalLine {
  id: number;
  name: string;
  target: number;
  targetDate: string | null;
  monthlyAmount: number | null;
  /** This month's amount: the fixed one, else the suggestion from the date, never past what's left to the target. */
  planned: number;
  plannedFrom: "fixed" | "date" | "none";
  /** Months to the target date, this one included; null with no date. */
  monthsLeft: number | null;
  /** Logged or transferred this month. */
  setAside: number;
  /** This month's amount not set aside yet. */
  toSetAside: number;
  /** Spent from the goal this month. */
  spent: number;
  /** Saved toward the goal through this month: set aside less spent. */
  saved: number;
  /** Logged money still sitting in checking through this month. */
  earmarked: number;
  reached: boolean;
}

const round2 = (n: number) => Math.round(n * 100) / 100;

/** Whole months from a to b (YYYY-MM), b later is positive. */
export const monthsFrom = (a: string, b: string) => {
  const [ya, ma] = a.split("-").map(Number);
  const [yb, mb] = b.split("-").map(Number);
  return (yb! - ya!) * 12 + (mb! - ma!);
};

/** A goal plans and earmarks in a month when it existed and wasn't archived yet. */
export const activeIn = (g: GoalIn, ym: string) => g.createdYm <= ym && (g.archivedYm === null || g.archivedYm > ym);

/**
 * Saved and earmarked through `ym`, running month by month so neither goes below zero: a charge paid
 * from transferred money doesn't eat a later month's logged money.
 */
function running(entries: GoalEntryIn[], through: string): { saved: number; earmarked: number } {
  const byYm = new Map<string, { logged: number; transfer: number; spent: number }>();
  for (const e of entries) {
    if (e.ym > through) continue;
    const m = byYm.get(e.ym) ?? { logged: 0, transfer: 0, spent: 0 };
    m[e.kind] += e.amount;
    byYm.set(e.ym, m);
  }
  let saved = 0;
  let earmarked = 0;
  for (const ym of [...byYm.keys()].sort()) {
    const m = byYm.get(ym)!;
    saved = Math.max(0, saved + m.logged + m.transfer - m.spent);
    earmarked = Math.max(0, earmarked + m.logged - m.spent);
  }
  return { saved: round2(saved), earmarked: round2(earmarked) };
}

/** This month's amount for a goal, from what was saved before this month. */
export function plannedFor(g: GoalIn, ym: string, savedBefore: number): { planned: number; from: GoalLine["plannedFrom"]; monthsLeft: number | null } {
  const left = Math.max(0, g.target - savedBefore);
  const monthsLeft = g.targetDate === null ? null : Math.max(1, monthsFrom(ym, g.targetDate.slice(0, 7)) + 1);
  if (g.monthlyAmount !== null) return { planned: round2(Math.min(g.monthlyAmount, left)), from: "fixed", monthsLeft };
  if (monthsLeft !== null) {
    // Rounded up to whole dollars so the goal is reached by its date.
    return { planned: Math.ceil(round2(left / monthsLeft)), from: "date", monthsLeft };
  }
  return { planned: 0, from: "none", monthsLeft };
}

export function goalLines(goals: GoalIn[], entries: GoalEntryIn[], ym: string): GoalLine[] {
  return goals
    .filter((g) => activeIn(g, ym))
    .map((g) => {
      const mine = entries.filter((e) => e.goalId === g.id);
      const before = running(mine, prevYm(ym));
      const now = running(mine, ym);
      const p = plannedFor(g, ym, before.saved);
      const thisMonth = mine.filter((e) => e.ym === ym);
      const setAside = round2(thisMonth.filter((e) => e.kind !== "spent").reduce((s, e) => s + e.amount, 0));
      const spent = round2(thisMonth.filter((e) => e.kind === "spent").reduce((s, e) => s + e.amount, 0));
      return {
        id: g.id,
        name: g.name,
        target: g.target,
        targetDate: g.targetDate,
        monthlyAmount: g.monthlyAmount,
        planned: p.planned,
        plannedFrom: p.from,
        monthsLeft: p.monthsLeft,
        setAside,
        toSetAside: round2(Math.max(0, p.planned - setAside)),
        spent,
        saved: now.saved,
        earmarked: now.earmarked,
        reached: now.saved >= g.target - 0.005,
      };
    });
}

const prevYm = (ym: string) => {
  const [y, m] = ym.split("-").map(Number);
  return m === 1 ? `${y! - 1}-12` : `${y}-${String(m! - 1).padStart(2, "0")}`;
};

export interface GoalTotals {
  planned: number;
  setAside: number;
  toSetAside: number;
  earmarked: number;
  /** What the planned ledger takes out: per goal the larger of its plan and what was set aside. */
  counted: number;
}

export function goalTotals(lines: GoalLine[]): GoalTotals {
  const sum = (f: (l: GoalLine) => number) => round2(lines.reduce((s, l) => s + f(l), 0));
  return {
    planned: sum((l) => l.planned),
    setAside: sum((l) => l.setAside),
    toSetAside: sum((l) => l.toSetAside),
    earmarked: sum((l) => l.earmarked),
    counted: sum((l) => Math.max(l.planned, l.setAside)),
  };
}
```

---

<!-- example/server/src/history.ts -->

```ts
// How far back bank history goes. Each Item keeps transactions from its own history_start: the
// 1st of the month before the month it was linked. Pure functions, no Node or DB imports.

/** /link/token/create transactions.days_requested bounds (Plaid: min 1, max 730, default 90). */
export const DAYS_REQUESTED_MIN = 1;
export const DAYS_REQUESTED_MAX = 730;
/** Extra days asked of Plaid beyond history_start, so a link that crosses midnight or a month end loses nothing. */
export const DAYS_REQUESTED_BUFFER = 7;
/** Full months of history after history_start before a category's average comes from history, not the import. */
export const MIN_HISTORY_MONTHS = 3;

const pad = (n: number) => String(n).padStart(2, "0");
/** Local calendar day of a time, YYYY-MM-DD. */
export const localYmd = (d: Date): string => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;

const YMD = /^(\d{4})-(\d{2})-(\d{2})$/;

function parts(ymd: string): [number, number, number] {
  const m = YMD.exec(ymd);
  if (!m) throw new Error("date must be YYYY-MM-DD");
  return [Number(m[1]), Number(m[2]), Number(m[3])];
}

/** The 1st of the month before `linkedOn` (YYYY-MM-DD): Nov 7 → Oct 1, Jan 3 → Dec 1 of the year before. */
export function historyStartFor(linkedOn: string): string {
  const [y, m] = parts(linkedOn);
  const d = new Date(Date.UTC(y, m - 2, 1));
  return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-01`;
}

/** Whole days from a to b (both YYYY-MM-DD, calendar days, no DST drift). */
export function daysFrom(a: string, b: string): number {
  const [ay, am, ad] = parts(a);
  const [by, bm, bd] = parts(b);
  return Math.round((Date.UTC(by, bm - 1, bd) - Date.UTC(ay, am - 1, ad)) / 86_400_000);
}

/** days_requested for a link made today: back to history_start plus a buffer, clamped to Plaid's range. */
export function daysRequestedFor(historyStart: string, today: string): number {
  const days = daysFrom(historyStart, today) + DAYS_REQUESTED_BUFFER;
  return Math.min(DAYS_REQUESTED_MAX, Math.max(DAYS_REQUESTED_MIN, days));
}

/** True for a transaction dated before its Item's history_start: not stored. */
export const beforeHistory = (date: string, historyStart: string | null): boolean =>
  historyStart !== null && date < historyStart;

/**
 * Full calendar months between the earliest history_start and the month `ym` (exclusive), capped.
 * history_start is always a 1st, so its own month counts as full.
 */
export function fullHistoryMonths(earliestHistoryStart: string | null, ym: string, cap = 6): number {
  if (!earliestHistoryStart) return 0;
  const [sy, sm] = parts(earliestHistoryStart);
  const [y, m] = ym.split("-").map(Number);
  const n = (y! - sy) * 12 + (m! - sm);
  return Math.max(0, Math.min(cap, n));
}
```
