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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CLAUDE.md → AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,17 @@ Sentence case. Plain short sentences. No em dashes.
- Database changes: add the next numbered file in `supabase/migrations/`. It applies on start, or with `npm run migrate`.
- Checks: `npm run lint`, `npx tsc --noEmit`, and pure libraries with `node src/lib/<name>.test.ts`.
- `scripts/e2e-sandbox.mjs` runs a throwaway user through every page.

## Agent skills

### Issue tracker

GitHub issues in this repo. See `docs/agents/issue-tracker.md`.

### Triage labels

Default five roles, label names equal the role names. See `docs/agents/triage-labels.md`.

### Domain docs

Single-context. See `docs/agents/domain.md`.
51 changes: 51 additions & 0 deletions docs/agents/domain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Domain Docs

How the engineering skills should consume this repo's domain documentation when exploring the codebase.

## Before exploring, read these

- **`GLOSSARY.md`** at the repo root, or
- **`GLOSSARY-MAP.md`** at the repo root if it exists: it points at one `GLOSSARY.md` per context. Read each one relevant to the topic.
- **`docs/adr/`**: read ADRs that touch the area you're about to work in. In multi-context repos, also check `src/<context>/docs/adr/` for context-scoped decisions.

If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved.

## File structure

Single-context repo (most repos):

```
/
├── GLOSSARY.md
├── docs/adr/
│ ├── 0001-event-sourced-orders.md
│ └── 0002-postgres-for-write-model.md
└── src/
```

Multi-context repo (presence of `GLOSSARY-MAP.md` at the root):

```
/
├── GLOSSARY-MAP.md
├── docs/adr/ ← system-wide decisions
└── src/
├── ordering/
│ ├── GLOSSARY.md
│ └── docs/adr/ ← context-specific decisions
└── billing/
├── GLOSSARY.md
└── docs/adr/
```

## Use the glossary's vocabulary

When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `GLOSSARY.md`. Don't drift to synonyms the glossary explicitly avoids.

If the concept you need isn't in the glossary yet, that's a signal: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`).

## Flag ADR conflicts

If your output contradicts an existing ADR, surface it explicitly rather than silently overriding:

> _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_
50 changes: 50 additions & 0 deletions docs/agents/issue-tracker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Issue tracker: GitHub

Issues and specs for this repo live as GitHub issues. Use the `gh` CLI for all operations.

## Conventions

- **Create an issue**: `gh issue create --title "..." --body "..."`. Use a heredoc for multi-line bodies.
- **Read an issue**: `gh issue view <number> --json number,title,body,labels,comments`.
- **List issues**: `gh issue list --state open --json number,title,body,labels,comments --jq '[.[] | {number, title, body, labels: [.labels[].name], comments: [.comments[].body]}]'` with appropriate `--label` and `--state` filters.
- **Make an issue a sub-issue of a parent**: `gh issue create --parent <parent> ...`, or `gh issue edit <parent> --add-sub-issue <child>` afterwards (`gh` 2.94+). Older `gh`: `gh api --method POST repos/<owner>/<repo>/issues/<parent>/sub_issues -F sub_issue_id=<child-db-id>` (database id, as in **Blocking** below). Without sub-issues, put `Part of #<parent>` at the top of the child body.
- **Blocking**: GitHub's **native issue dependencies**, the canonical, UI-visible representation. Add an edge with `gh issue create --blocked-by <n>,<n> ...` or `gh issue edit <child> --add-blocked-by <blocker>` (`gh` 2.94+). Older `gh`: `gh api --method POST repos/<owner>/<repo>/issues/<child>/dependencies/blocked_by -F issue_id=<blocker-db-id>`, where `<blocker-db-id>` is the blocker's numeric **database id** (`gh api repos/<owner>/<repo>/issues/<n> --jq .id`, _not_ the `#number` or `node_id`). Where dependencies aren't available, fall back to a `Blocked by: #<n>, #<n>` line at the top of the child body. A ticket is unblocked when every blocker is closed.
- **Count open blockers**: `gh api repos/<owner>/<repo>/issues/<n> --jq .issue_dependencies_summary.blocked_by` (open blockers only; 0 means startable). `gh issue view <n> --json blockedBy` also lists closed blockers, so filter it: `--jq '[.blockedBy.nodes[] | select(.state == "OPEN")] | length'`.
- **Comment on an issue**: `gh issue comment <number> --body "..."`
- **Apply / remove labels**: `gh issue edit <number> --add-label "..."` / `--remove-label "..."`
- **Close**: post the explanation with `gh issue comment <number> --body "..."`, then `gh issue close <number>`. On an already-closed issue, `gh issue close --comment` drops the comment and still exits 0.

Infer the repo from `git remote -v`; `gh` does this automatically when run inside a clone.

File issues only into the user's own repo. Never file into `GrantCharge/broke` (the repo these skills come from) unless the user owns it. In a fork, `gh` can default to the upstream parent, so before the first `gh issue create` of a session, check the target with `gh repo view --json nameWithOwner` and confirm it with the user if it is not their repo.

## Pull requests as a triage surface

**PRs as a request surface: no.** _(Set to `yes` if this repo treats external PRs as feature requests; `/triage` reads this flag.)_

When set to `yes`, PRs run through the same labels and states as issues, using the `gh pr` equivalents:

- **Read a PR**: `gh pr view <number>`, then `gh pr view <number> --comments` (off a TTY, `--comments` prints only the comments, not the body), and `gh pr diff <number>` for the diff.
- **List external PRs for triage**: `gh api --paginate 'repos/{owner}/{repo}/pulls?state=open' --jq '.[] | select(.author_association | IN("OWNER","MEMBER","COLLABORATOR") | not) | {number, title, author: .user.login, author_association, labels: [.labels[].name]}'`.
- **Comment / label / close**: `gh pr comment`, `gh pr edit --add-label`/`--remove-label`, `gh pr close`.

GitHub shares one number space across issues and PRs, so a bare `#42` may be either: resolve with `gh pr view 42` and fall back to `gh issue view 42`.

## When a skill says "publish to the issue tracker"

Create a GitHub issue.

## When a skill says "fetch the relevant ticket"

Read it as in **Read an issue** above.

## Wayfinding operations

Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets.

- **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `gh issue create --label wayfinder:map`.
- **Child ticket**: an issue linked to the map as a GitHub sub-issue (see **Make an issue a sub-issue of a parent**). Where sub-issues aren't enabled, add the child to a task list in the map body and put `Part of #<map>` at the top of the child body. Labels: `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev.
- **Blocking**: see **Blocking** under Conventions.
- **Frontier query**: list the map's open children (`gh issue list --state open`, scoped to the map's sub-issues / task list), drop any with an open blocker (see **Count open blockers**, or an open issue in the `Blocked by` line) or an assignee; first in map order wins.
- **Claim**: `gh issue edit <n> --add-assignee @me`, the session's first write.
- **Resolve**: `gh issue comment <n> --body "<answer>"`, then `gh issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far.
15 changes: 15 additions & 0 deletions docs/agents/triage-labels.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Triage Labels

The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker.

| Label in GrantCharge/broke | Label in our tracker | Meaning |
| -------------------------- | -------------------- | ---------------------------------------- |
| `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue |
| `needs-info` | `needs-info` | Waiting on reporter for more information |
| `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent |
| `ready-for-human` | `ready-for-human` | Requires human implementation |
| `wontfix` | `wontfix` | Will not be actioned |

When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table.

Edit the "Label in our tracker" column to match whatever vocabulary you actually use.
6 changes: 3 additions & 3 deletions src/app/(app)/accounts/add/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ export default async function AddAccountsPage({ searchParams }: { searchParams:
const { connect } = await searchParams;
const country = countryOf(user?.user_metadata?.profile?.country);
const choices = addChoices(country.code, wantsAkahu(user?.user_metadata?.profile));
const { data: manual } = await supabase.from("accounts").select("id, name, custom_name, mask").eq("manual", true).eq("user_id", user!.id);
const accounts = (manual ?? []).map((a) => ({ id: a.id, label: `${a.custom_name || a.name}${a.mask ? ` ··${a.mask}` : ""}` }));
const { data: manual } = await supabase.from("accounts").select("id, name, custom_name, mask, currency").eq("manual", true).eq("user_id", user!.id);
const accounts = (manual ?? []).map((a) => ({ id: a.id, label: `${a.custom_name || a.name}${a.mask ? ` ··${a.mask}` : ""}`, currency: a.currency as string | null }));
return (
<div className="space-y-6 max-w-4xl">
<Link href="/accounts" className="inline-block text-sm text-muted hover:text-ink px-1">Back to accounts</Link>
Expand All @@ -21,7 +21,7 @@ export default async function AddAccountsPage({ searchParams }: { searchParams:
{connect === "cancelled" && <p className="card px-5 py-3 text-sm" role="status">The connection was cancelled. Nothing changed.</p>}
{connect === "failed" && <p className="card px-5 py-3 text-sm text-bad" role="alert">That bank didn&apos;t connect. Try again, or import a statement instead.</p>}
{!choices.bank && !choices.plaidMissing && !choices.feeds.length && !choices.akahuMissing && !choices.alsoAkahu && <p className="text-sm text-muted px-1">Automatic bank linking isn&apos;t available in {country.name} yet. Import a statement from your bank instead: it takes a minute and works with any bank.</p>}
<AddAccounts choices={choices} accounts={accounts} locale={country.locale} currency={country.currency} country={country.code} />
<AddAccounts choices={choices} accounts={accounts} locale={country.locale} country={country.code} />
{choices.akahuMissing && (
<p className="text-sm text-muted px-1">To sync NZ banks automatically, add Akahu keys on the <a href="/setup" className="underline underline-offset-2">Setup page</a>. Until then, import a statement from your bank.</p>
)}
Expand Down
31 changes: 20 additions & 11 deletions src/app/(app)/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { SyncButton } from "@/components/PlaidButtons";
import { TxnList } from "@/components/TxnList";
import { WeekCard } from "@/components/WeekCard";
import { categories, getUser, moneyByMonth, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
import { dateLabel, money0, monthStart, ymd } from "@/lib/format";
import { dateLabel, money0, monthStart, secondCurrency, ymd } from "@/lib/format";
import { deterministicMoves, ladder } from "@/lib/plan";
import { myPlanFacts } from "@/lib/plan-facts";
import { payGuess } from "@/lib/pay";
Expand Down Expand Up @@ -68,30 +68,37 @@ export default async function Dashboard() {
const checks = (fetchChecks(supabase, uid, day) as Promise<Checks>).catch(() => ({ rows: [], total: 0 })); // starts now, beside the queries below

// Own rows only: an account a partner shares is on the Accounts page, not in your totals.
const [{ data: recent }, { data: accounts }, { data: noRate }, { data: bills }, rows, cats] = await Promise.all([
const two = secondCurrency(); // totals also show in this currency (Settings, migration 0032)
const [{ data: recent }, { data: accounts }, { data: noRate }, { data: bills }, rows, cats, spent2] = await Promise.all([
supabase.from("transactions").select(TXN_SELECT).eq("user_id", uid).order("date", { ascending: false }).order("id").limit(5),
supabase.from("accounts").select("type, subtype, current_balance:home_balance, included").eq("user_id", uid),
supabase.from("accounts").select("type, subtype, current_balance:home_balance, second:second_balance, included").eq("user_id", uid),
supabase.rpc("fx_missing"),
supabase.from("recurring").select("id, merchant_name, logo_url, average_amount:home_average, next_date").eq("user_id", uid).eq("active", true).eq("is_income", false).neq("status", "TOMBSTONED").gte("next_date", day).lte("next_date", soon).order("next_date").limit(4),
moneyByMonth(supabase, ymd(monthStart(now))),
categories(),
two ? supabase.rpc("money_total", { start_date: ymd(monthStart(now)), cur: two }).single<{ spend: number }>() : null,
]);

if (!accounts?.length) return <EmptyBank />;

const txns = withAccountNames((recent ?? []) as unknown as Txn[]);
type Acct = { type: string; subtype: string | null };
const bal = (pred: (a: Acct) => boolean) => {
const bal = (pred: (a: Acct) => boolean, col: "current_balance" | "second" = "current_balance") => {
const list = accounts.filter((a) => a.included && pred(a));
return list.length ? list.reduce((s, a) => s + Number(a.current_balance ?? 0), 0) : null;
return list.length ? list.reduce((s, a) => s + Number(a[col] ?? 0), 0) : null;
};
// Each tile in home currency, and in the second currency underneath when one is set.
const tile = (label: string, href: string, pred: (a: Acct) => boolean, abs = false) => {
const fix = (n: number | null) => (n == null ? null : abs ? Math.abs(n) : n);
return { label, href, value: fix(bal(pred)), value2: two ? fix(bal(pred, "second")) : null };
};
const owed = bal((a) => a.type === "credit" || a.type === "loan");
const tiles = [
{ label: "In your bank", value: bal((a) => a.type === "depository" && a.subtype !== "savings"), href: "/accounts" },
{ label: "Savings", value: bal((a) => a.type === "depository" && a.subtype === "savings"), href: "/accounts" },
{ label: "Investments", value: bal((a) => a.type === "investment"), href: "/accounts" },
{ label: "You owe", value: owed == null ? null : Math.abs(owed), href: "/debt" },
tile("In your bank", "/accounts", (a) => a.type === "depository" && a.subtype !== "savings"),
tile("Savings", "/accounts", (a) => a.type === "depository" && a.subtype === "savings"),
tile("Investments", "/accounts", (a) => a.type === "investment"),
tile("You owe", "/debt", (a) => a.type === "credit" || a.type === "loan", true),
].filter((t) => t.value != null);
const spentTwo = spent2?.data ? Number(spent2.data.spend) : null;

const pic = moneyPicture(rows, cats, ymd(monthStart(now)).slice(0, 7), null);
const monthName = dateLabel(day, { month: "long" });
Expand All @@ -107,6 +114,7 @@ export default async function Dashboard() {
<Link key={t.label} href={t.href} className="row-hover p-5 space-y-1">
<span className="block text-sm text-muted">{t.label}</span>
<span className="block text-2xl font-semibold tabular tracking-[-0.02em]">{money0(t.value!)}</span>
{t.value2 != null && <span className="block text-sm text-muted tabular">{money0(t.value2, two)}</span>}
</Link>
))}
</section>
Expand All @@ -122,7 +130,8 @@ export default async function Dashboard() {
<span className="text-sm text-muted">Spent in {monthName}</span>
<Link href="/spending" className="text-sm text-muted hover:text-ink">See all</Link>
</div>
<p className="text-2xl font-semibold tabular tracking-[-0.02em]">{money0(pic.spent)}</p>
<p className="text-2xl font-semibold tabular tracking-[-0.02em]">{money0(pic.spent)}
{spentTwo != null && <span className="ml-2 text-sm font-normal text-muted tracking-normal">{money0(spentTwo, two)}</span>}</p>
{pic.spent > 0 ? (
<>
<div className="flex h-2 gap-0.5 rounded-full overflow-hidden" aria-hidden>
Expand Down
16 changes: 11 additions & 5 deletions src/app/(app)/settings/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ClearMyData, ClearTestData, RemoveTest } from "@/components/ClearTestDa
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { modelOptions, saveChoice } from "@/components/Assistant";
import { CountryField } from "@/components/CountryPicker";
import { CountryField, CurrencyField } from "@/components/CountryPicker";
import { Dropdown } from "@/components/Dropdown";
import { Modal } from "@/components/Modal";
import { ThemeToggle } from "@/components/Nav";
Expand All @@ -22,7 +22,7 @@ import { Segmented } from "../../setup/SetupActions";

type Group = "profile" | "banks" | "database" | "ai" | "referrals" | "appearance" | "advanced" | "improve";
type Mode = "sandbox" | "production";
type Profile = Record<string, unknown> & { country?: string; currency?: string };
type Profile = Record<string, unknown> & { country?: string; currency?: string; currency2?: string };

const NAV: { id: Group; label: string; icon: LucideIcon; what: string }[] = [
{ id: "profile", label: "Profile", icon: User, what: "Your account, country and money profile." },
Expand Down Expand Up @@ -183,10 +183,10 @@ function Card({ title, what, s, children }: { title: string; what?: string; s?:

function ProfileCards({ email, profile }: { email: string; profile: Profile }) {
const router = useRouter();
const start = { country: profile.country ?? "US", currency: profile.currency ?? countryOf(profile.country).currency };
const start = { country: profile.country ?? "US", currency: profile.currency ?? countryOf(profile.country).currency, currency2: profile.currency2 ?? "" };
const [c, setC] = useState(start);
const [msg, setMsg] = useState("");
const dirty = c.country !== start.country || c.currency !== start.currency;
const dirty = c.country !== start.country || c.currency !== start.currency || c.currency2 !== start.currency2;
const credit = creditOf(profile);
async function save() {
const { error } = await updateMeta(createClient(), { data: { profile: { ...profile, ...c } } });
Expand All @@ -203,7 +203,13 @@ function ProfileCards({ email, profile }: { email: string; profile: Profile }) {
</Card>
<Card title="Country and currency" what="Sets your currency, which banks you can link and which tax tips apply.">
<div className="max-w-sm">
<CountryField country={c.country} currency={c.currency} onChange={(country, currency) => (setC({ country, currency }), setMsg(""))} />
<CountryField country={c.country} currency={c.currency} onChange={(country, currency) => (setC({ ...c, country, currency }), setMsg(""))} />
</div>
<div className="max-w-sm space-y-1.5">
<span className="block text-sm font-medium">Also show totals in</span>
<CurrencyField label="Second currency" value={c.currency2 === c.currency ? "" : c.currency2} none="No second currency" first={["THB", "AUD", "USD"]}
onChange={(currency2) => (setC({ ...c, currency2 }), setMsg(""))} />
<p className="text-sm text-muted">For money in two countries. Each amount converts at that day&apos;s exchange rate.</p>
</div>
<div className="flex items-center gap-3">
<button className="btn-primary" disabled={!dirty} onClick={save}>Save</button>
Expand Down
Loading