Skip to content

AI agent rules

Project rules for AI agents working on this codebase. Read this before making any change.


Only source belongs in git. Never commit anything that can be reproduced by running a command. If you create or encounter a generated artifact, add it to .gitignore instead.

Generated outputs that must stay out of git:

Path Regenerated by
dist/, dist-ssr/ pnpm build
dist-electron/ pnpm electron:compile
release/ pnpm electron:build
coverage/ pnpm test:coverage
marketing/node_modules/ npm ci --prefix marketing
docs-site/node_modules/, docs-site/dist/, docs-site/.astro/ npm ci --prefix docs-site, npm run build --prefix docs-site
docs-site/src/content/docs/, docs-site/src/generated/, docs-site/public/ npm run collect and npm run openapi in docs-site/ (both run by build)
build/appx/ scripts/make-store-tiles.ps1 (Windows)
marketing/store-screenshots/out/ pnpm marketing:screenshots
marketing/app-preview/out/, marketing/showreel/out/ pnpm marketing:preview, pnpm showreel
marketing/showreel/vault/out/ node marketing/showreel/vault/capture.mjs, then render.mjs
node_modules/, .cache/ pnpm install
android/app/src/main/assets/public/ cap sync android
ios/App/App/public/ cap sync ios
android/capacitor-cordova-android-plugins/ cap sync
ios/capacitor-cordova-ios-plugins/ cap sync

Before committing, ask: “Can this be reproduced by running a command?” If yes, gitignore it.

One deliberate exception: the finished marketing videos in marketing/search-demo/final/ and marketing/showreel/final/ are committed so the owner can share them from the repository. Store screenshots are not: pnpm marketing:screenshots regenerates them, and each GitHub release attaches a zip. Everything else a marketing tool generates (marketing/*/out/) stays ignored. Keep only the current cut there; a committed video stays in the history for good.


  • Framework: React 19 + TypeScript + Vite
  • Styling: Tailwind CSS + shadcn/ui
  • Icons: lucide-react (lucide-react-motion on the homepage)
  • State: TanStack Query, React Context, Dexie (IndexedDB)
  • Routing: React Router — BrowserRouter for web, HashRouter for Electron/Capacitor
  • Desktop: Electron (source in electron/)
  • Mobile: Capacitor — iOS (ios/) and Android (android/)
  • Package manager: pnpm

  • Privacy-first: No data leaves the device unless explicitly exported by the user. API keys are stored locally and never included in exports.
  • Local-first: The app must work 100% offline. IndexedDB via Dexie is the primary data store.
  • Data goes through DataProvider: Production code must not import @/lib/dexieDB; add a method to DataProvider (src/types/dataProvider.ts) and LocalDataProvider instead, with a test in src/providers/DataProviderContract.test.ts. ESLint enforces this. Do not add exceptions to the rule in eslint.config.js.
  • Routes live in src/App.tsx: Do not scatter route definitions elsewhere.
  • Pages in src/pages/, components in src/components/, hooks in src/hooks/.
  • For mobile-specific work, consult documentation/IOS_RULES.md and documentation/ANDROID_RULES.md.

  • TypeScript: camelCase for variables/functions, PascalCase for components and classes.
  • Use descriptive names — avoid abbreviations that require context to decode.
  • Comment non-obvious logic; add multi-line comments for core business logic.
  • Never commit secrets, API keys, or .env files.
  • Never push code that does not build or pass type-checking.

Never reference public assets with absolute paths (src="/logo.png"). Under Electron’s file:// protocol, / resolves to the filesystem root, not dist/.

Always use Vite static imports instead:

// ✅ correct — Vite hashes and bundles the path
import logoSquareDark from "@/assets/logo-square-dark.png";
// ❌ broken in Electron builds
<img src="/logo-square-dark.png" />;

These patterns were discovered fixing real bottlenecks in this codebase.

Tiered useMemo for global derivations Global state (e.g. running balances) must derive from the global data source only — never from a filtered view. Compute the global cache in one useMemo, then project it onto the filtered view in a separate, cheaper step. Coupling both to the filtered list causes full recalculation on every filter change.

Stabilise handlers passed to memoised lists React.memo on a list row is useless if the parent passes new inline arrow functions as props on every render. Wrap all handlers passed to large lists or memoised components in useCallback.

Fast-forward fixed-interval recurring transactions Do not iterate from a transaction’s start date to project into a future window. For daily and weekly intervals, use arithmetic (differenceInDays, differenceInWeeks) to jump directly to the first occurrence in the window — O(1) instead of O(N). Leave monthly/yearly as iterative to handle variable-length months correctly.

Hoist property accessors outside sort comparators Parsing nested key paths (e.g. "category.name") inside a sort comparison runs O(N log N) string splits. Compute the accessor strategy — simple key or path getter — once before the sort, then reuse it inside the comparator.


Interactive table cells must be <button> elements div[onClick] breaks keyboard navigation and screen readers. Reset button styles with bg-transparent border-0 p-0 text-left to preserve visual appearance. Add aria-label for context.

Sortable column headers Keep aria-sort on the <th> element; move the click handler to a child <button type="button"> that fills the cell. Use flex utilities (justify-end) for alignment. Mixing both on <th> breaks semantic structure.

Text contrast is measured, not eyeballed Light-only colours (text-slate-400, text-green-500, text-indigo-100 on the near-white dark-mode primary button) and opacity-* fades fell below 4.5:1 in one theme while looking fine in the other. Pair every text colour with a dark: colour, do not fade text to show an inactive state, and check both themes. See “Text Contrast” in documentation/UI_UX_STANDARDS.md.

Measure outlines, not just text A text-only contrast pass missed that dark-mode form controls had no visible edge (--input 1.05:1 against the page). Control outlines (inputs, selects, the search box, outline buttons, switch tracks) need 3:1 (WCAG 1.4.11); keep --input separate from the quieter --border for cards.

TooltipProvider is already mounted in Layout Layout.tsx wraps the authenticated app in a TooltipProvider. Do not add a local one — use Tooltip, TooltipTrigger, and TooltipContent directly inside any authenticated route.

Menus come from one list The sidebar and the phone bottom bar render from src/components/navigation/navConfig.ts, and isNavItemActive decides the selected item everywhere. Add or rename pages there, never in a single menu.

Name every sheet SheetContent has no placeholder title. Give it a visible SheetTitle, or srTitle when it has none (the phone menus), so screen readers never announce a generic name.

Check Larger text on a 360px phone The text-size setting scales every rem, so a layout that fits at default can overflow at Larger. Button never wraps (whitespace-nowrap): give long labels h-auto whitespace-normal. Let names wrap (break-words) rather than truncate, keep fixed-width columns from starving a name column (let them wrap below it), and keep phone top-bar icon buttons in px so the title beside them keeps its room.

Respect the side safe areas (iPhone landscape, iPhone Duo) iPhone Duo keeps its status bar on the right edge (84pt) and iPhones turned sideways have the camera on one side. #root is padded by --safe-area-left/--safe-area-right (in globals.css), but anything fixed is measured from the screen edge: add the variables yourself, e.g. right-[calc(1rem+var(--safe-area-right))], as the phone header, tab bar, add button, sidebar and side sheets do. Never pad body; open dialogs overwrite its padding. Branch layouts on available width, never on device or orientation.

Plain CSS beats Tailwind utilities In Tailwind 4, CSS outside a layer wins over every utility class. Put shared component rules (such as .touch-target) in @layer components so classes like absolute still apply; leave only deliberate overrides (the display settings in globals.css) unlayered.

Combobox (cmdk) interaction Combobox fields render as <input> elements, not button[role='combobox']. Target them by placeholder text (e.g. "Search accounts..."). Select results via role="option" or [cmdk-item].


These came from adding swipe and long press to phone cards (2.1).

New card lists use SwipeableCard. Build one CardAction list per card and pass it to leftAction, rightAction and menuActions, so the swipe and the menu can never differ. Do not write another pointer handler for a list.

A swipe never commits. It only reveals a button; the action runs on a tap and keeps any confirmation the menu has. Swipe left is Delete, swipe right is Duplicate or Edit, never anything destructive.

Fields, buttons and links are excluded. A press that starts on an input, textarea, link, button or [data-selectable-text] does not swipe or long-press, so text stays selectable. A full-card button that should still swipe carries data-swipe-surface.

Gestures are never the only route. Keep the ”…” button or inline buttons. Tests of “the gesture did not open the card” must send the click the phone fires on lift (fireEvent.click), or they prove nothing.

A long press swallows the lift’s click page-wide. The menu can open under the finger, and the click the phone sends on lift would pick the menu item there. useSwipeGesture drops that one click anywhere on the page; keep it.

A wrapped card still has to fit its column. A grid item that holds a SwipeableCard needs min-w-0, and the name inside needs room (min-w-[8rem], with amounts and buttons wrapping below), or at Larger text on a 360px phone the card overflows and the shell cuts off its right side.

The sliding layer is opaque. Give SwipeableCard the card’s radius (className) and the colour the card sits on (contentClassName), or a rectangle of the wrong colour shows behind it.


These came from reworking natural-language search.

One parser, no second one. src/utils/searchParser.ts is the only place a typed query is read. Do not add another parser for a screen; add the phrase to it with a row in src/tests/searchParserQueries.test.ts (tests run it on a fixed “today”). src/utils/searchFilters.ts only applies results.

The search box and the API share interpretQuery. Anything the box can understand, GET /ledgers/{id}/search/interpret must report the same way. Change the shared code (searchInterpretation.ts), never one side. A change to what a phrase means is an API change: update the route tests, Postman assertions and documentation/API.md.

Never apply a guess silently. Typo matching is opt-in (fuzzy: true) and only used where the user confirms the result. Suggestions are applied only when picked, one piece at a time. Say how filters combine (AND across kinds).

Stemming can hurt typos. Compare a typed word both as written and singularised (“grocies” stems to “grocy”, which is further from “groceries”).

Dates written with new Date(y, m, d, 12); today comes from options.now. Order matters in the parser: “2 weeks from today” must be read before the bare word “today” is removed.

These vulnerabilities were found and fixed in the Electron IPC layer.

IPC filename validation path.join('/safe/dir', '/etc/passwd') returns /etc/passwd — Node discards previous segments on absolute paths. Always call path.basename() on renderer-supplied filenames and reject any value containing /, \, or ...

File extension allowlist Sanitising the filename is not enough. Restrict writable extensions to an explicit allowlist (.json, .lock). Unrestricted extensions allow writing .sh or .bat startup scripts even with path-traversal protection in place.

Folder authorisation allowlist Never trust a directory path received from the renderer. Maintain an allowlist of authorised directories in the Main process. Expand the allowlist only when the user explicitly selects a folder via dialog.showOpenDialog. Validate every write request against the list before writing.

CSP must be build-time only Injecting a <meta http-equiv="Content-Security-Policy"> tag into index.html directly breaks Vite’s dev server (HMR uses inline scripts). Use a Vite plugin transform with apply: 'build' so the CSP header is only added to production output.

CSV export sanitisation Sanitise formula-injection prefixes (=, +, -, @) before writing CSV output. But preserve valid numeric strings: -100 is data, not a formula. Check the regex against a numeric format before escaping to avoid corrupting legitimate negative values.


Dependabot opens grouped PRs against pre-prod every week: one for the app, one for the docs site (docs-site/), one for GitHub Actions. Security fixes are the exception: GitHub always opens them against main, so retarget them to pre-prod (gh pr edit <n> --base pre-prod). These patterns came from fixing those PRs when CI went red.

Reproduce every CI step before pushing a fix CircleCI runs lint, typecheck, format check, pnpm test:coverage, pnpm build and pnpm audit --prod --audit-level=moderate. pnpm validate covers only the first three, so run the rest too (see Quality checks). A new security advisory can fail the audit even when no code changed. Fix it with a patched version in pnpm.overrides.

Bisect the grouped update, then fix the cause When a grouped bump breaks something, check out pre-prod, bump the suspect packages one at a time (pnpm add -D <pkg>@<version>), and rerun the failing check to find the culprit. Fix the root cause rather than pinning the old version. Pin only when upstream is incompatible, and then add a Dependabot ignore entry with a tracking link, as .github/dependabot.yml does for TypeScript.

Tests must not depend on focus left behind by earlier tests In jsdom 30.1.0, removing a focused element (which Testing Library’s cleanup does) handed focus to the Document, and the next focus() fired a blur on window. Radix menus and selects close on window blur, so a dropdown test that ran after another focus-moving test never saw its menu open. src/tests/setup.ts resets focus before every test; keep that reset when editing the setup file. src/tests/test-environment-focus.test.tsx guards it.

Assert behaviour, not jsdom internals jsdom’s focus bookkeeping changes between patch releases. document.hasFocus() returned false after blur() in 30.1.0 but true in 30.1.1, which broke a test that asserted on it. Assert what a user would observe (document.activeElement, whether a menu opened) rather than jsdom-specific state.

Type Radix checkbox handlers as CheckedState @radix-ui/react-checkbox 1.4 declares onCheckedChange as a property instead of a method, so TypeScript now checks its parameter strictly. A handler typed (checked: boolean) => void fails tsc (and so pnpm build), because the callback can also receive "indeterminate". Accept the CheckedState value and convert it explicitly, e.g. (checked) => onSelect(checked === true).

Type translation callbacks as i18next’s TFunction i18next 27 tightened TFunction’s overloads, so passing t to a helper typed (key: string, options?: Record<string, unknown>) => string fails tsc. Type the parameter as TFunction (import type { TFunction } from "i18next").

Prettier minor bumps can reformat translations Prettier 3.10 measures Tamil and other Indic strings differently, which rewrapped 17 files in src/i18n/. When a Prettier bump fails format:check, run pnpm exec prettier --write "src/**/*.{ts,tsx,css}" and commit the result.

Commit the regenerated acknowledgments pnpm build and the test suite regenerate src/data/acknowledgments.generated.ts from installed versions. Commit the regenerated file along with the dependency bump so the Acknowledgments page lists the versions that actually ship.


These came from issue #253, where UI renames and deletes reached into Dexie directly.

Names act as foreign keys Transactions, recurring transactions and budgets store vendor, account, category and sub-category names, not ids. Vendor, account and sub-category budgets hold the name twice, in budget_scope_name and in the display field category_name. A rename or delete must update or remove every record that stores the name. Use the DataProvider methods (renamePayee, updateAccountDetails, renameCategory, renameSubCategory, delete*). Each runs in one Dexie transaction.

Scope every name match to the ledger The same name can exist in several ledgers and mean different things. A query like where("vendor").equals(name) without a user_id check changes every ledger. The deletes used to wipe other ledgers’ recurring transactions this way. src/providers/DataProviderContract.test.ts seeds two ledgers with identical names to catch it.

Sub-category budgets match by name in any category Rename or delete a sub_category budget only when no other sub-category in the ledger still has that name.

Merges delete the merged-away schedules and budgets A merge moves past transactions to the target. It then deletes the sources together with their recurring transactions and budgets, because there is no telling which duplicate’s schedule or budget the user still wants. This was the owner’s decision. Do not change merges to move them instead. A merge into a target that doesn’t exist throws, and a target listed among its own sources is ignored.

Ledger names are unique Ledgers are separate books to the user. addLedger and updateLedger refuse a name another ledger has, ignoring case and spaces. They check only when the name changes, so ledgers that already share a name still open.


The desktop Local API (src/api/, electron/apiServer.ts) is a public contract that scripts depend on. Any change that touches an API entity must update the API, its tests, its docs and the Postman collection in the same change. “Entity” means anything the API exposes: ledgers, accounts, vendors, categories/sub-categories, transactions, recurring transactions, budgets, currencies, AI providers, languages, backups, and the analytics/insights/reports outputs.

This applies when you:

  • add, remove, rename or change an endpoint, parameter, request field, response field, status code or error;
  • change an entity’s type or storage in src/types/dataProvider.ts, src/lib/dexieDB.ts or LocalDataProvider, or the logic the API shares with the UI (the rename and delete methods on DataProvider, src/api/compute/*, src/utils/budgetUtils.ts, backupUtils.ts);
  • change a validation rule, default or side effect (renames that propagate, cascading deletes, auto-created records).

Checklist:

  1. Code – update the route in src/api/routes/ (schemas are zod; the route table is the source of truth).
  2. Unit tests – update src/api/api.test.ts. Cover the success path and the error paths (400/404/409).
  3. Postman collection – update documentation/postman/vaulted-money-local-api.postman_collection.json: add or change the request and its test assertions, keep it inside the throwaway-ledger flow, and make sure any setting it changes is restored (see documentation/postman/README.md). Update the request counts there if they change.
  4. Docs – update documentation/API.md (and the README “Using the Local API” section if the quick start changes).
  5. Verify – run pnpm test:coverage. src/api/postmanCoverage.test.ts fails if a route has no Postman request or a request points at a route that no longer exists, and src/api/postmanRun.test.ts runs the whole collection with Newman against the real server code and fails on any failed assertion. If response shapes changed, refresh the saved examples (see documentation/postman/README.md).
  6. OpenAPI – GET /openapi.json is generated from the route table, and so is the docs site’s API reference (scripts/write-openapi.mjs). Give new routes a body (their zod schema) and query descriptions so the spec and the reference stay complete.
  7. MCP server – mcp/ reaches every route through search_api and call_api, so a new route needs no new tool, but an agent can only use it if search_api finds it. Give every route a distinctive summary (not just “Get one”); mcp/coverage.test.ts fails if a route has none or search_api cannot find it from it. If you change a response shape that a curated tool in mcp/server.mjs reads (analytics, insights, budgets, transactions, accounts), update that tool and mcp/README.md too.

Conventions for new endpoints: operations that change many records take dry_run and report what they would do; deletions require confirm_delete: true; AI or network calls are opt-in per request. Where the app has a button for something, reuse its logic (extract it to a shared util, as src/utils/transactionMaintenance.ts does) instead of re-implementing it, and say which button it mirrors in the route summary.

Never expose secrets (AI API keys, backup password hashes) through the API, and keep destructive operations behind an explicit confirmation flag.


Keys already in src/i18n/resources.ts win over the area modules, so changing the wording of an existing key there needs a new key in an area module (as nav.* and pages.* did) or an edit to resources.ts in all five languages.

User-visible text goes through t("key", { defaultValue }) and every key is added for all five languages in src/i18n/areas/ (see documentation/I18N.md). src/i18n/coverageGuard.test.ts fails if a key is undefined or if a file gains hard-coded English. Never build sentences by concatenation, and format dates with formatDisplayDate.


“Generate demo data” is the app’s shop window. Its content lives in src/utils/demoDataPlan.ts (see documentation/DEMO_DATA.md).

  • When you add or change a user-visible feature, give the demo a scenario that uses it and assert it in src/utils/demoDataPlan.test.ts or src/api/demoData.test.ts.
  • Never hard-code a date or year in demo data. Derive everything from the now the plan is given; the tests run it with several different “today” values.
  • Keep it deterministic for a seed, and keep balances believable (no overdrawn cash accounts, cards within their limit).
  • No real company or product names (payees or notes): store screenshots and videos are made from the demo, and real brands are trademarks. Invent names; src/utils/demoDataPlan.test.ts lists the ones to avoid.

Apps ship the app build, not the website. pnpm build makes the website, including the homepage and its demo videos. iOS, Android and the desktop app use pnpm build:app (vite build --mode app), which compiles the homepage out and drops the website-only files listed in vite.config.ts. The mobile:*, android:*, ios:* and electron:build scripts already use it. Run cap sync only after pnpm build:app, and keep website-only assets imported from HomePage alone.

Check Codex’s review before merging into pre-prod or main. The Codex bot (chatgpt-codex-connector) reviews pull requests. Before merging any PR into pre-prod or main, read its inline comments (gh api --paginate repos/{owner}/{repo}/pulls/<n>/comments, filtered to that bot across every page) and check each one against the code on the PR’s head. Fix the findings that hold up, with a test where one fits, within the limits below, and reply on every other thread (why it doesn’t apply, or where it is tracked). Do not merge with a finding unanswered. If a review is still running, wait up to 10 minutes, then merge if CI is green, and handle any findings that arrive later in a follow-up PR. If Codex has not started at all, comment @codex review to start it. Its comments on feature branches can be skipped when the same change will go through a reviewed PR into pre-prod. In the first review (11 PRs, #310 to #333) all ten distinct findings were real, so treat them as likely bugs, not noise.

Limit how much fixing a Codex review sets off. Codex reviews when a PR opens, so every PR gets reviewed once. Fixing findings costs far more than the review, so keep it bounded:

  • Fix by severity. Fix P1 and P2 findings that change how the app behaves before merging. Reply on P3 findings and on ones only about documentation wording, add them to documentation/BACKLOG.md, and fix them later in a batch.
  • One fix round per PR. Fix the findings, push once, and merge when CI is green. Do not ask Codex to review the fix again (@codex review) unless the fix itself was risky. Findings that arrive later are answered and go to a follow-up batch, not another round on the same PR.
  • Do not fix twice on promotion. A pre-prod to main PR carries code Codex already reviewed in pre-prod. Act on findings there only if they are P1. A valid P2 found only at this step may ship to main: reply, add it to documentation/BACKLOG.md, and fix it in the next batch through pre-prod. These limits take precedence over fixing every finding before merging.
  • Run the full checks once per round, not after every edit.

Promote pre-prod to main with a merge commit. Use GitHub’s “Create a merge commit” (gh pr merge --merge), never squash or rebase. A squash leaves main with commits pre-prod doesn’t have, so the next promotion conflicts on every line both releases touched.


Terminal window
pnpm lint # ESLint
pnpm format:check # Prettier
tsc --noEmit # TypeScript
pnpm test:coverage # Vitest + coverage
pnpm build # Production build
pnpm validate # Combined lint + typecheck
pnpm audit --prod --audit-level=moderate # Security audit (CI blocks on this)

src/ — App source (components, pages, hooks, utils, types, contexts, providers)
electron/ — Electron main process source (main.ts, preload.ts)
android/ — Capacitor Android project (custom icons, splash, Gradle config)
ios/ — Capacitor iOS project (custom icons, splash, Xcode config)
public/ — Static files served at web root
assets/ — Source brand images (icons, splash screens)
documentation/ — Project and developer docs
marketing/ — Store screenshots, App Store preview, showreels and demo videos, and the tools that make them (see each folder's README)
specs/ — Feature specifications
scripts/ — Build helper scripts
patches/ — pnpm dependency patches