ownledger 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -37,6 +37,7 @@ amounts, and never write without the owner's go. `npx ownledger check` must pass
37
37
  - `void: true` hides a transaction but keeps it in history. Don't delete lines from ledger files.
38
38
  - `plan: "<plan id>"` marks a payment of an instalment, loan or premium.
39
39
  - `src: {import, key}` ties an imported transaction to its source row. Never change it.
40
+ - `trail: [{op, at, via, client?, reason?}]` records each add/edit/void made through a connector (who, when, why). Append only; never edit or remove entries.
40
41
 
41
42
  ## Account types
42
43
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.0 (2026-11-22)
4
+
5
+ - Transactions record where they came from: `trail` gets one entry per add/edit/void made through the MCP
6
+ connector (`op`, `at`, `via`, `client`, `reason`). Imports keep `src`; rows without a trail are unchanged.
7
+ - `add_transaction`, `edit_transaction` and `void_transaction` now require `reason`: one line saying what the
8
+ owner asked for. It is shown in the preview, kept on the trail and added to the commit message
9
+ (`Reason: …` / `Via: mcp (<app>)`).
10
+ - The connected app's name is saved at sign-in and recorded on writes. Reconnect an app once to get it.
11
+ - `check` refuses a malformed `trail`.
12
+
3
13
  ## 1.0.0 (2026-11-22)
4
14
 
5
15
  First release.
@@ -15,6 +15,14 @@ export interface Planned {
15
15
  export declare class ActionError extends Error {
16
16
  }
17
17
  export declare function plan(files: FileMap, change: Change, message: string): Planned;
18
+ /** Who/what is making a write, recorded on the transaction's trail and in the commit message. */
19
+ export interface WriteMeta {
20
+ via: string;
21
+ client?: string;
22
+ reason?: string;
23
+ at?: string;
24
+ }
25
+ export declare const REASON_MAX = 200;
18
26
  export interface SimpleTx {
19
27
  date: string;
20
28
  time?: string | null;
@@ -33,9 +41,9 @@ export interface SimpleTx {
33
41
  category?: string;
34
42
  }
35
43
  export declare function linesOf(t: SimpleTx): Line[];
36
- export declare function addTransaction(files: FileMap, t: SimpleTx): Planned;
37
- export declare function editTransaction(files: FileMap, id: string, patch: Partial<SimpleTx>): Planned;
38
- export declare function voidTransaction(files: FileMap, id: string, reason?: string): Planned;
44
+ export declare function addTransaction(files: FileMap, t: SimpleTx, meta?: WriteMeta): Planned;
45
+ export declare function editTransaction(files: FileMap, id: string, patch: Partial<SimpleTx>, meta?: WriteMeta): Planned;
46
+ export declare function voidTransaction(files: FileMap, id: string, reason?: string, meta?: WriteMeta): Planned;
39
47
  export declare function addAccount(files: FileMap, a: Account): Planned;
40
48
  export declare function editAccount(files: FileMap, id: string, set: Record<string, unknown>): Planned;
41
49
  export declare function addPlan(files: FileMap, p: Plan): Planned;
@@ -25,6 +25,28 @@ export function plan(files, change, message) {
25
25
  warnings: r.warnings.filter((w) => !before.has(`${w.file}|${w.where}|${w.message}`)),
26
26
  };
27
27
  }
28
+ export const REASON_MAX = 200;
29
+ function trailed(t, op, meta) {
30
+ if (!meta)
31
+ return t;
32
+ const reason = meta.reason?.trim().replace(/\s+/g, " ");
33
+ if (reason && reason.length > REASON_MAX)
34
+ throw new ActionError(`reason is too long (max ${REASON_MAX} characters)`);
35
+ const e = {
36
+ op,
37
+ at: meta.at ?? new Date().toISOString().replace(/\.\d{3}Z$/, "Z"),
38
+ via: meta.via,
39
+ ...(meta.client ? { client: meta.client } : {}),
40
+ ...(reason ? { reason } : {}),
41
+ };
42
+ return { ...t, trail: [...(Array.isArray(t.trail) ? t.trail : []), e] };
43
+ }
44
+ function withMeta(message, meta) {
45
+ if (!meta)
46
+ return message;
47
+ const lines = [meta.reason?.trim() ? `Reason: ${meta.reason.trim().replace(/\s+/g, " ")}` : "", `Via: ${meta.via}${meta.client ? ` (${meta.client})` : ""}`].filter(Boolean);
48
+ return `${message}\n\n${lines.join("\n")}`;
49
+ }
28
50
  export function linesOf(t) {
29
51
  if (t.lines?.length)
30
52
  return t.lines;
@@ -44,7 +66,7 @@ export function linesOf(t) {
44
66
  ? [{ account: t.account, amount: a }, { category: t.category, amount: -a }]
45
67
  : [{ account: t.account, amount: -a }, { category: t.category, amount: a }];
46
68
  }
47
- export function addTransaction(files, t) {
69
+ export function addTransaction(files, t, meta) {
48
70
  if (!isDate(t.date))
49
71
  throw new ActionError("date must be yyyy-mm-dd");
50
72
  const tx = {
@@ -58,7 +80,7 @@ export function addTransaction(files, t) {
58
80
  ...(t.plan ? { plan: t.plan } : {}),
59
81
  lines: linesOf(t),
60
82
  };
61
- return plan(files, { addTransactions: [tx] }, `Add: ${t.date} ${t.note ?? ""}`.trim());
83
+ return plan(files, { addTransactions: [trailed(tx, "add", meta)] }, withMeta(`Add: ${t.date} ${t.note ?? ""}`.trim(), meta));
62
84
  }
63
85
  function findTx(files, id) {
64
86
  for (const [p, text] of Object.entries(files)) {
@@ -70,7 +92,7 @@ function findTx(files, id) {
70
92
  }
71
93
  throw new ActionError(`no transaction ${id}`);
72
94
  }
73
- export function editTransaction(files, id, patch) {
95
+ export function editTransaction(files, id, patch, meta) {
74
96
  const old = findTx(files, id);
75
97
  const next = { ...old };
76
98
  for (const k of ["date", "time", "note", "who", "event", "tags", "plan"]) {
@@ -82,7 +104,7 @@ export function editTransaction(files, id, patch) {
82
104
  }
83
105
  if (!isDate(next.date))
84
106
  throw new ActionError("date must be yyyy-mm-dd");
85
- return plan(files, { replaceTransactions: [next] }, `Edit: ${next.date} ${next.note ?? ""}`.trim());
107
+ return plan(files, { replaceTransactions: [trailed(next, "edit", meta)] }, withMeta(`Edit: ${next.date} ${next.note ?? ""}`.trim(), meta));
86
108
  }
87
109
  /** Best-effort simple view of a transaction (to let an edit change just one field). */
88
110
  function simpleOf(t) {
@@ -99,12 +121,12 @@ function simpleOf(t) {
99
121
  }
100
122
  return { lines: t.lines };
101
123
  }
102
- export function voidTransaction(files, id, reason) {
124
+ export function voidTransaction(files, id, reason, meta) {
103
125
  const old = findTx(files, id);
104
126
  if (old.void)
105
127
  throw new ActionError(`${id} is already void`);
106
128
  const next = { ...old, void: true, ...(reason ? { void_reason: reason } : {}) };
107
- return plan(files, { replaceTransactions: [next] }, `Void: ${old.date} ${old.note ?? ""}`.trim());
129
+ return plan(files, { replaceTransactions: [trailed(next, "void", meta)] }, withMeta(`Void: ${old.date} ${old.note ?? ""}`.trim(), meta));
108
130
  }
109
131
  /* ------------------------------------------------------------------ accounts, plans, prices */
110
132
  export function addAccount(files, a) {
@@ -171,6 +171,15 @@ export function checkLedger(l) {
171
171
  err(file, w, `same import key as ${srcKeys.get(k)}`);
172
172
  srcKeys.set(k, t.id);
173
173
  }
174
+ if (t.trail !== undefined) {
175
+ if (!Array.isArray(t.trail))
176
+ err(file, w, "trail must be a list");
177
+ else
178
+ t.trail.forEach((e, j) => {
179
+ if (!e || typeof e !== "object" || typeof e.op !== "string" || typeof e.at !== "string" || typeof e.via !== "string")
180
+ err(file, `${w} trail ${j + 1}`, "trail entry needs op, at and via");
181
+ });
182
+ }
174
183
  if (!Array.isArray(t.lines) || t.lines.length < 2) {
175
184
  err(file, w, "needs at least two lines");
176
185
  continue;
@@ -71,6 +71,16 @@ export interface Transaction {
71
71
  key: string;
72
72
  [k: string]: unknown;
73
73
  };
74
+ /** How the transaction got its current form: one entry per add/edit/void made through a client (MCP...). */
75
+ trail?: TrailEntry[];
76
+ [k: string]: unknown;
77
+ }
78
+ export interface TrailEntry {
79
+ op: "add" | "edit" | "void";
80
+ at: string;
81
+ via: string;
82
+ client?: string;
83
+ reason?: string;
74
84
  [k: string]: unknown;
75
85
  }
76
86
  export type PlanKind = "instalment" | "bnpl" | "loan_taken" | "loan_given" | "insurance_premium" | "deposit" | string;
@@ -75,6 +75,12 @@ export async function sessionLogin(req, env) {
75
75
  return s && allowed(env, s.login) ? s.login : null;
76
76
  }
77
77
  /* ------------------------------------------------------------------ MCP client authorization (/authorize) */
78
+ /** The registered app's name, kept in the token props so writes can say which app made them. */
79
+ async function clientName(oauth, clientId) {
80
+ const c = await oauth.lookupClient(clientId).catch(() => null);
81
+ const name = (c?.clientName || clientId || "").slice(0, 60);
82
+ return name ? { client: name } : {};
83
+ }
78
84
  export async function authorizeGet(req, env) {
79
85
  const oauth = env.OAUTH_PROVIDER;
80
86
  let request;
@@ -105,7 +111,7 @@ export async function authorizePost(req, env) {
105
111
  }
106
112
  const approved = await oauth.approveConsent(req, handle);
107
113
  if (env.DEV_LOGIN) {
108
- const { redirectTo } = await oauth.completeAuthorization({ request: approved.request, userId: env.DEV_LOGIN, metadata: { login: env.DEV_LOGIN }, scope: approved.request.scope, props: { login: env.DEV_LOGIN } });
114
+ const { redirectTo } = await oauth.completeAuthorization({ request: approved.request, userId: env.DEV_LOGIN, metadata: { login: env.DEV_LOGIN }, scope: approved.request.scope, props: { login: env.DEV_LOGIN, ...(await clientName(oauth, approved.request.clientId)) } });
109
115
  approved.headers.set("Location", redirectTo);
110
116
  return new Response(null, { status: 302, headers: approved.headers });
111
117
  }
@@ -141,7 +147,7 @@ export async function oauthCallback(req, env) {
141
147
  const login = await githubLogin(env.GITHUB_CLIENT_ID, env.GITHUB_CLIENT_SECRET, url.searchParams.get("code") ?? "", resumed.data.verifier, new URL("/oauth/callback", req.url).toString());
142
148
  if (!allowed(env, login))
143
149
  return deny(`${login} is not allowed on this ledger`);
144
- const { redirectTo } = await oauth.completeAuthorization({ request: resumed.request, userId: login, metadata: { login }, scope: resumed.request.scope, props: { login } });
150
+ const { redirectTo } = await oauth.completeAuthorization({ request: resumed.request, userId: login, metadata: { login }, scope: resumed.request.scope, props: { login, ...(await clientName(oauth, resumed.request.clientId)) } });
145
151
  resumed.headers.set("Location", redirectTo);
146
152
  return new Response(null, { status: 302, headers: resumed.headers });
147
153
  }
@@ -21,5 +21,7 @@ export interface Env {
21
21
  }
22
22
  export interface Props {
23
23
  login: string;
24
+ /** The connected app's name (from its OAuth registration), recorded on writes. Missing on tokens issued before 1.1.0. */
25
+ client?: string;
24
26
  }
25
27
  export declare function allowed(env: Env, login: string): boolean;
@@ -27,6 +27,7 @@ function compactTx(t) {
27
27
  ...(t.tags?.length ? { tags: t.tags } : {}),
28
28
  ...(t.plan ? { plan: t.plan } : {}),
29
29
  ...(t.void ? { void: true } : {}),
30
+ ...(t.trail?.length ? { reason: t.trail[t.trail.length - 1].reason } : {}),
30
31
  lines: t.lines.map((l) => [l.account ?? l.category, l.amount, ...(l.qty !== undefined ? [`${l.qty} ${l.asset ?? ""}`.trim()] : [])]),
31
32
  };
32
33
  }
@@ -52,12 +53,19 @@ const txFields = {
52
53
  tags: z.array(z.string()).optional(),
53
54
  plan: z.string().optional().describe("plan id this pays (instalment, loan, premium)"),
54
55
  };
56
+ const reason = z
57
+ .string()
58
+ .trim()
59
+ .min(3)
60
+ .max(A.REASON_MAX)
61
+ .describe("Required. One line: what the owner asked for, close to their own words (kept on the transaction's trail and in the commit).");
55
62
  export function buildServer(env, props, src = sourceFor(env)) {
56
63
  const server = new McpServer({ name: "ownledger", version: VERSION }, { instructions: INSTRUCTIONS });
57
64
  const tz = env.TIMEZONE || "Asia/Ho_Chi_Minh";
58
65
  const now = () => todayIn(tz);
59
66
  const snap = () => snapshot(env, src);
60
67
  const ro = { readOnlyHint: true, openWorldHint: false };
68
+ const meta = (reason) => ({ via: "mcp", ...(props.client ? { client: props.client } : {}), reason });
61
69
  const wrap = (fn) => async (args) => {
62
70
  try {
63
71
  return out(await fn(args));
@@ -111,6 +119,7 @@ export function buildServer(env, props, src = sourceFor(env)) {
111
119
  "Amounts are positive whole numbers in the base currency in the simple form; lines are signed and sum to 0.",
112
120
  "Moves between the owner's accounts (card payments, savings, investments, loans) are transfers, never expense or income.",
113
121
  "Correct a mistake with edit_transaction or void_transaction; never add a reversing entry unless asked.",
122
+ "Every add_/edit_/void_transaction needs reason: one line saying what the owner asked, close to their own words (it is kept on the transaction and in the commit).",
114
123
  ],
115
124
  base: s.ledger.meta.base,
116
125
  categories: {
@@ -238,11 +247,11 @@ export function buildServer(env, props, src = sourceFor(env)) {
238
247
  const pv = { readOnlyHint: true, openWorldHint: false }; // previews change nothing
239
248
  server.registerTool("add_transaction", {
240
249
  description: "PREVIEW a new transaction (writes nothing). Simple form: kind + amount + account (+ category or to_account). Full form: lines.",
241
- inputSchema: z.object(txFields),
250
+ inputSchema: z.object({ ...txFields, reason }),
242
251
  annotations: pv,
243
- }, wrap(async (a) => preview((f) => A.addTransaction(f, a))));
244
- server.registerTool("edit_transaction", { description: "PREVIEW changes to a transaction by id (only the fields given change).", inputSchema: z.object({ id: z.string(), ...txFields, date: z.string().optional() }), annotations: pv }, wrap(async ({ id, ...patch }) => preview((f) => A.editTransaction(f, id, patch))));
245
- server.registerTool("void_transaction", { description: "PREVIEW voiding a transaction (kept in history, excluded everywhere).", inputSchema: z.object({ id: z.string(), reason: z.string().optional() }), annotations: pv }, wrap(async ({ id, reason }) => preview((f) => A.voidTransaction(f, id, reason))));
252
+ }, wrap(async ({ reason, ...a }) => preview((f) => A.addTransaction(f, a, meta(reason)))));
253
+ server.registerTool("edit_transaction", { description: "PREVIEW changes to a transaction by id (only the fields given change).", inputSchema: z.object({ id: z.string(), ...txFields, date: z.string().optional(), reason }), annotations: pv }, wrap(async ({ id, reason, ...patch }) => preview((f) => A.editTransaction(f, id, patch, meta(reason)))));
254
+ server.registerTool("void_transaction", { description: "PREVIEW voiding a transaction (kept in history, excluded everywhere).", inputSchema: z.object({ id: z.string(), reason }), annotations: pv }, wrap(async ({ id, reason }) => preview((f) => A.voidTransaction(f, id, reason, meta(reason)))));
246
255
  const accountFields = {
247
256
  name: z.string(),
248
257
  type: z.string().describe("cash, bank, ewallet, credit_card, bnpl, deposit, savings_goal, gold, fund, stock, etf, crypto, insurance, loan_given, loan_taken, other (or a new one)"),
@@ -1 +1 @@
1
- export declare const VERSION = "1.0.0";
1
+ export declare const VERSION = "1.1.0";
@@ -1,2 +1,2 @@
1
1
  // generated by scripts/version.mjs
2
- export const VERSION = "1.0.0";
2
+ export const VERSION = "1.1.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ownledger",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Personal finance ledger used through AI chat (MCP). Your data in your own private GitHub repo, served by your own Cloudflare Worker.",
5
5
  "license": "MIT",
6
6
  "author": "phucbm",