lake-gate 0.1.0 → 0.2.1

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.
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="112" height="36" viewBox="0 0 112 36" role="img" aria-label="Approve">
2
+ <rect x=".5" y=".5" width="111" height="35" rx="10" fill="#0E7C7B" stroke="#0E7C7B"/>
3
+ <g transform="translate(14 10)" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 8.5l4 4L14 4"/></g>
4
+ <text x="38" y="23" fill="#FFFFFF" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif" font-size="14" font-weight="600">Approve</text>
5
+ </svg>
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="168" height="36" viewBox="0 0 168 36" role="img" aria-label="Request changes">
2
+ <rect x=".5" y=".5" width="167" height="35" rx="10" fill="#FFFFFF" stroke="#E3C6CA"/>
3
+ <g transform="translate(14 10)" fill="none" stroke="#A8404C" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3L1.5 6.5 5 10"/><path d="M2 6.5h7.5a4.5 4.5 0 010 9H7"/></g>
4
+ <text x="38" y="23" fill="#A8404C" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif" font-size="14" font-weight="600">Request changes</text>
5
+ </svg>
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="132" height="36" viewBox="0 0 132 36" role="img" aria-label="Open review">
2
+ <rect x=".5" y=".5" width="131" height="35" rx="10" fill="#FFFFFF" stroke="#CFE2DD"/>
3
+ <g transform="translate(14 10)" fill="none" stroke="#073F4B" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 8s2.6-5 7-5 7 5 7 5-2.6 5-7 5-7-5-7-5z"/><circle cx="8" cy="8" r="2"/></g>
4
+ <text x="38" y="23" fill="#073F4B" font-family="-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif" font-size="14" font-weight="600">Open review</text>
5
+ </svg>
package/ui/data.js ADDED
@@ -0,0 +1,95 @@
1
+ // Data sources for the review UI. All of them produce the same workspace shape from core/review.js.
2
+ // demo – fictional team, in memory
3
+ // github – reads/writes a GitHub repo straight from the browser (token stays in this browser)
4
+ // local – served by `npx lake-gate ui`: GitHub calls go through a localhost proxy that holds your
5
+ // gh/GITHUB_TOKEN, plus plans in your working tree that aren't on a PR yet
6
+ import { client } from './core/github.js';
7
+ import { loadWorkspace, loadPr, actions, viewer as whoami } from './core/workspace.js';
8
+ import { buildPlanReview, versionsFromSnapshots } from './core/review.js';
9
+ import { parseConfig } from './core/config-core.js';
10
+ import { demoWorkspace, demoPost, demoReset, VIEWER, PEOPLE } from './demo.js';
11
+ import { commentBody, replyBody, resolveBody, verdictBody, suggestionBody, acceptBody } from './core/review.js';
12
+ import { demoAccept } from './demo.js';
13
+
14
+ const BODY = { comment: commentBody, reply: replyBody, resolve: resolveBody, verdict: verdictBody, suggest: suggestionBody, accept: acceptBody };
15
+ const TOKEN_KEY = 'lake.gh.token';
16
+
17
+ export const tokenStore = {
18
+ get: () => sessionStorage.getItem(TOKEN_KEY) || localStorage.getItem(TOKEN_KEY) || '',
19
+ set: (t, remember) => { sessionStorage.setItem(TOKEN_KEY, t); if (remember) localStorage.setItem(TOKEN_KEY, t); else localStorage.removeItem(TOKEN_KEY); },
20
+ clear: () => { sessionStorage.removeItem(TOKEN_KEY); localStorage.removeItem(TOKEN_KEY); },
21
+ };
22
+
23
+ export function demoSource() {
24
+ return {
25
+ mode: 'demo', repo: 'fernwood/payments-api', canWrite: true, viewer: VIEWER, people: PEOPLE,
26
+ async load() { return demoWorkspace(); },
27
+ async post(plan, kind, o) {
28
+ if (kind === 'accept') o = { ...o, newVersion: demoAccept(plan.pr.number, o.patch) };
29
+ const body = BODY[kind]({ ...o, via: 'Lake review' });
30
+ demoPost(plan.pr.number, body);
31
+ return { body, where: `PR #${plan.pr.number}` };
32
+ },
33
+ reset: demoReset,
34
+ };
35
+ }
36
+
37
+ function ghSource({ repo, gh, mode, extraPlans }) {
38
+ let ws = null; let me = null;
39
+ return {
40
+ mode, repo, people: {}, get canWrite() { return !!me; }, get viewer() { return me; },
41
+ async load() {
42
+ me = me || (await whoami(gh))?.login || null;
43
+ const r = await loadWorkspace(gh, { state: 'all', limit: 20 });
44
+ const local = extraPlans ? await extraPlans(r.plans) : [];
45
+ ws = { repo, plans: [...r.plans, ...local], viewer: me, people: {}, mode };
46
+ return ws;
47
+ },
48
+ async post(plan, kind, o) {
49
+ if (!plan.pr) throw new Error('This plan is not on a pull request yet. Push it and open a PR first.');
50
+ await actions[kind](gh, plan.pr.number, { ...o, via: 'Lake review' });
51
+ return { body: kind === 'accept' ? `Committed the change to ${plan.path} on ${plan.pr.branch}` : BODY[kind]({ ...o, via: 'Lake review' }), where: `PR #${plan.pr.number}` };
52
+ },
53
+ async reloadPr(number) { return loadPr(gh, number); },
54
+ };
55
+ }
56
+
57
+ export function githubSource(repo) {
58
+ const token = tokenStore.get();
59
+ const gh = client({ token: token || undefined, repo, fetchImpl: (u, o) => fetch(u, o) });
60
+ return ghSource({ repo, gh, mode: 'github' });
61
+ }
62
+
63
+ export async function localSource() {
64
+ const key = document.querySelector('meta[name="lake-key"]')?.content;
65
+ if (!key) return null;
66
+ const env = await fetch('/api/env', { headers: { 'X-Lake-Key': key } }).then((r) => (r.ok ? r.json() : null)).catch(() => null);
67
+ if (!env) return null;
68
+ const fetchImpl = (u, o = {}) => fetch(u, { ...o, headers: { ...(o.headers || {}), 'X-Lake-Key': key } });
69
+ const gh = env.repo ? client({ repo: env.repo, api: '/gh', fetchImpl }) : null;
70
+ // Local plans not on any PR (or edited locally) show as drafts.
71
+ const extraPlans = async (prPlans) => {
72
+ const local = await fetchImpl('/api/local').then((r) => r.json());
73
+ const config = parseConfig(local.config);
74
+ const out = [];
75
+ for (const lp of local.plans) {
76
+ const versions = versionsFromSnapshots(lp.snapshots, lp.id);
77
+ if (!versions.length) continue;
78
+ const cur = versions[versions.length - 1];
79
+ const onPr = prPlans.find((p) => p.id === cur.id && p.pr?.state === 'open');
80
+ if (onPr && onPr.digest === cur.digest) continue;
81
+ const m = buildPlanReview({ plan: cur, versions, events: [], config });
82
+ m.local = { branch: local.branch, unpushed: !!onPr, prNumber: onPr?.pr.number || null };
83
+ if (onPr) m.id = cur.id; // same id, local edit
84
+ out.push(m);
85
+ }
86
+ return out;
87
+ };
88
+ if (!gh) {
89
+ return { mode: 'local', repo: env.root, canWrite: false, viewer: null, people: {},
90
+ async load() { return { repo: env.root, plans: await extraPlans([]), viewer: null, people: {}, mode: 'local' }; }, async post() { throw new Error('No GitHub remote.'); } };
91
+ }
92
+ const s = ghSource({ repo: env.repo, gh, mode: 'local', extraPlans });
93
+ s.env = env;
94
+ return s;
95
+ }
package/ui/demo.js ADDED
@@ -0,0 +1,262 @@
1
+ // Demo workspace: a made-up team ("Fernwood", fictional people) and made-up plans.
2
+ // Raw inputs only (plan file versions + PR comments/reviews exactly as GitHub would return them);
3
+ // the real lake-gate data layer (core/review.js) builds every screen from them.
4
+ import { renderPlanFile } from './core/plan.js';
5
+ import { patchPlanFile } from './core/workspace.js';
6
+ import { suggestionBody } from './core/review.js';
7
+ import { parseConfig } from './core/config-core.js';
8
+ import { buildPlanReview, versionsFromSnapshots, commentBody, replyBody, resolveBody, verdictBody, encodeMarker } from './core/review.js';
9
+
10
+ export const PEOPLE = {
11
+ maya: { name: 'Maya Ortiz', role: 'Backend' },
12
+ noah: { name: 'Noah Brandt', role: 'Tech lead' },
13
+ ava: { name: 'Ava Lindqvist', role: 'Security' },
14
+ leo: { name: 'Leo Park', role: 'Platform' },
15
+ sam: { name: 'Sam Okafor', role: 'Data' },
16
+ ines: { name: 'Inés Duarte', role: 'Product' },
17
+ dana: { name: 'Dana Whitfield', role: 'Eng manager · budget' },
18
+ };
19
+ export const VIEWER = 'noah';
20
+ export const REPO = 'fernwood/payments-api';
21
+ const CONFIG = parseConfig(JSON.stringify({ requiredApprovals: 2, budget: { approverAbove: 20, approvers: ['dana'] } }));
22
+
23
+ const now = Date.now();
24
+ const ago = (min) => new Date(now - min * 60000).toISOString();
25
+ const file = (id, title, author, body) => renderPlanFile({ id, title, author, created: ago(4000), body, estimateMd: '' });
26
+ const bodyOf = (text) => text.replace(/^---\n[\s\S]*?\n---\n/, '');
27
+ function at(text, needle, span = 1) {
28
+ const lines = bodyOf(text).split('\n'); const i = lines.findIndex((l) => l.includes(needle));
29
+ if (i < 0) throw new Error('demo anchor not found: ' + needle);
30
+ return { start: i + 1, end: i + span, quote: lines.slice(i, i + span).join('\n') };
31
+ }
32
+ let seq = 1;
33
+ const ev = (login, body, min, extra = {}) => ({ id: `d${seq++}`, source: 'comment', login, type: 'User', association: 'MEMBER', body, createdAt: ago(min), ...extra });
34
+
35
+ // ---------- 1. Webhook retries: three rounds ----------
36
+ const W1 = file('add-webhook-retries', 'Add webhook retries', 'maya', `# Add webhook retries
37
+
38
+ Deliveries to customer endpoints fail silently today. When an endpoint times out we drop the event and the customer never hears about it.
39
+
40
+ ## Goal
41
+ Retry failed deliveries without ever sending the same event twice.
42
+
43
+ ## Steps
44
+ 1. Add a retry queue in \`src/webhooks/queue.ts\` that retries failed deliveries every 30 seconds, forever.
45
+ 2. Store the full payload on the delivery record so a retry can resend it as is.
46
+ 3. Add a \`retry_count\` column to \`webhook_deliveries\` (database migration).
47
+ 4. Add tests for the retry path.
48
+
49
+ ## Risks
50
+ - Customers with slow endpoints get more traffic.
51
+
52
+ ## Out of scope
53
+ - A dashboard for failed deliveries.
54
+ `);
55
+ const W2 = file('add-webhook-retries', 'Add webhook retries', 'maya', `# Add webhook retries
56
+
57
+ Deliveries to customer endpoints fail silently today. When an endpoint times out we drop the event and the customer never hears about it.
58
+
59
+ ## Goal
60
+ Retry failed deliveries without ever sending the same event twice.
61
+
62
+ ## Steps
63
+ 1. Add a bounded retry queue in \`src/webhooks/queue.ts\`: exponential backoff from 30s, capped at 6 attempts over about 2 hours.
64
+ 2. After the last attempt, move the delivery to a \`dead_letter\` state and notify the account owner by email.
65
+ 3. Store the full payload on the delivery record so a retry can resend it as is.
66
+ 4. Reuse the existing idempotency key on every attempt so a retry never double-charges.
67
+ 5. Add a \`retry_count\` column to \`webhook_deliveries\` (database migration).
68
+ 6. Add tests for backoff, dead-letter and idempotent replay.
69
+
70
+ ## Risks
71
+ - Customers with slow endpoints get more traffic.
72
+
73
+ ## Out of scope
74
+ - A dashboard for failed deliveries.
75
+ `);
76
+ const W3 = file('add-webhook-retries', 'Add webhook retries', 'maya', `# Add webhook retries
77
+
78
+ Deliveries to customer endpoints fail silently today. When an endpoint times out we drop the event and the customer never hears about it.
79
+
80
+ ## Goal
81
+ Retry failed deliveries without ever sending the same event twice, and never send a payload we can't vouch for.
82
+
83
+ ## Steps
84
+ 1. Add a bounded retry queue in \`src/webhooks/queue.ts\`: exponential backoff from 30s with jitter, capped at 6 attempts over about 2 hours.
85
+ 2. After the last attempt, move the delivery to a \`dead_letter\` state and notify the account owner by email.
86
+ 3. Store the event id and body on the delivery record, and re-sign every attempt with the current signing key. Refuse to send if that key has expired.
87
+ 4. Reuse the existing idempotency key on every attempt so a retry never double-charges.
88
+ 5. Add a \`retry_count\` column to \`webhook_deliveries\` (database migration, backfill 0).
89
+ 6. Emit \`webhook.retry\` and \`webhook.dead_letter\` metrics.
90
+ 7. Add tests for backoff, dead-letter, expired keys and idempotent replay.
91
+
92
+ ## Risks
93
+ - Customers with slow endpoints get more traffic. Jitter spreads it out.
94
+ - The backfill touches about 9M rows. Run it in batches of 50k off-peak.
95
+
96
+ ## Out of scope
97
+ - A dashboard for failed deliveries.
98
+ `);
99
+ const webhookEvents = [];
100
+ {
101
+ const t1 = 'w1forevr', t2 = 'w1idempo', t3 = 'w1paylod', t4 = 'w2resign', t5 = 'w3keyid';
102
+ webhookEvents.push(
103
+ ev('maya', `**Plan ready for review:** Add webhook retries\n@noah @ava\n\nFirst cut. Mostly worried about the migration size.\n<sub>via lake-gate · Claude Code (MCP)</sub>`, 2900),
104
+ ev('noah', commentBody({ planId: 'add-webhook-retries', version: v(W1), anchor: at(W1, 'forever'), text: 'Unbounded retries will hammer a dead endpoint for days. Cap the attempts, back off exponentially, then park it somewhere we can see.', thread: t1, via: 'Lake review' }), 2860),
105
+ ev('noah', commentBody({ planId: 'add-webhook-retries', version: v(W1), anchor: at(W1, 'Store the full payload'), text: 'What stops a retry from charging twice? We already have an idempotency key on deliveries, use it.', thread: t2, via: 'Lake review' }), 2855),
106
+ ev('ava', commentBody({ planId: 'add-webhook-retries', version: v(W1), anchor: at(W1, 'Store the full payload'), text: 'Resending the stored bytes "as is" means resending an old signature. Who signs the retry?', thread: t3, via: 'Lake review' }), 2840),
107
+ ev('noah', verdictBody({ action: 'reject', planId: 'add-webhook-retries', version: v(W1), text: 'Right problem. Needs a bound on retries and an answer on double charges before we build.', via: 'Lake review' }), 2830),
108
+ ev('maya', replyBody({ planId: 'add-webhook-retries', thread: t1, text: 'Agreed. 6 attempts over ~2h, then dead-letter with an email to the account owner.', via: 'Claude Code (MCP)' }), 1700),
109
+ ev('maya', `**Revised plan \`add-webhook-retries\` → v${v(W2).slice(0, 8)}.** Earlier approvals no longer apply.\n\nBounded backoff, dead-letter state, idempotency key on every attempt.\n<sub>via lake-gate · Claude Code (MCP)</sub>\n${encodeMarker('resolve', { p: 'add-webhook-retries', t: t1, r: true })}\n${encodeMarker('resolve', { p: 'add-webhook-retries', t: t2, r: true })}`, 1690),
110
+ ev('ava', commentBody({ planId: 'add-webhook-retries', version: v(W2), anchor: at(W2, 'Store the full payload'), text: 'Still replaying the stored signature. If we rotate the key mid-retry, customers get a payload they must reject. Re-sign every attempt with the current key, and refuse when it has expired.', thread: t4, via: 'Lake review' }), 1500),
111
+ ev('ava', verdictBody({ action: 'reject', planId: 'add-webhook-retries', version: v(W2), text: 'Blocking on signing only. The rest reads well.', via: 'Lake review' }), 1495),
112
+ ev('maya', replyBody({ planId: 'add-webhook-retries', thread: t3, text: 'Covered by step 3 in v3: we re-sign every attempt.', via: 'Lake review' }), 400),
113
+ ev('maya', `**Revised plan \`add-webhook-retries\` → v${v(W3).slice(0, 8)}.** Earlier approvals no longer apply.\n\nRe-sign on every attempt, refuse expired keys, jitter, batched backfill, metrics.\n<sub>via lake-gate · Claude Code (MCP)</sub>\n${encodeMarker('resolve', { p: 'add-webhook-retries', t: t3, r: true })}\n${encodeMarker('resolve', { p: 'add-webhook-retries', t: t4, r: true })}`, 395),
114
+ { id: 'd-native-review', source: 'review', state: 'APPROVED', login: 'leo', type: 'User', association: 'MEMBER', body: 'Backoff numbers and the batched backfill look right.', createdAt: ago(130), commitId: 'w3' },
115
+ ev('ava', commentBody({ planId: 'add-webhook-retries', version: v(W3), anchor: at(W3, 're-sign every attempt'), text: 'Nice. Small one: log the key id on each re-sign so we can trace rotations.', thread: t5, via: 'Claude Code (MCP)' }), 95),
116
+ ev('maya', replyBody({ planId: 'add-webhook-retries', thread: t5, text: 'Will do, it fits in step 6 with the metrics.', via: 'Lake review' }), 60),
117
+ { id: 'd-line-1', source: 'line', login: 'leo', type: 'User', association: 'MEMBER', body: 'Can we tag these with the endpoint host? Makes the noisy-customer view trivial.', createdAt: ago(125),
118
+ path: '.lake/plans/add-webhook-retries.md', line: at(W3, 'webhook.retry').start + offsetOf(W3), commitId: 'w3', inReplyTo: null },
119
+ );
120
+ }
121
+ function v(text) { return versionsFromSnapshots([{ text }], 'x')[0].digest; }
122
+ function offsetOf(text) { return text.match(/^---\n[\s\S]*?\n---\n?/)[0].split('\n').length - 1; }
123
+
124
+ // ---------- 2. CSV exports: changes requested ----------
125
+ const C1 = file('safer-csv-exports', 'Safer CSV exports', 'sam', `# Safer CSV exports
126
+
127
+ Large accounts time out when they export transactions, and the export includes card fingerprints it shouldn't.
128
+
129
+ ## Steps
130
+ 1. Load all matching rows into memory, then write the CSV in one pass.
131
+ 2. Drop \`card_fingerprint\` and \`ip_address\` from the export columns.
132
+ 3. Email a signed download link that expires after 24 hours.
133
+ 4. Add a test with a 10k-row account.
134
+ `);
135
+ const csvEvents = [
136
+ ev('maya', commentBody({ planId: 'safer-csv-exports', version: v(C1), anchor: at(C1, 'Load all matching rows'), text: 'Our biggest account has ~4M transactions. Stream rows from a cursor straight into the file instead.', thread: 'c1stream', via: 'Lake review' }), 210),
137
+ ev('maya', verdictBody({ action: 'reject', planId: 'safer-csv-exports', version: v(C1), text: 'Memory is the blocker. Column removal and expiring links are great.', via: 'Lake review' }), 205),
138
+ ev('sam', replyBody({ planId: 'safer-csv-exports', thread: 'c1stream', text: 'Makes sense, rewriting step 1 now.', via: 'Lake review' }), 180),
139
+ ];
140
+
141
+ // ---------- 3. Cursor pagination: approved, merged ----------
142
+ const P1 = file('cursor-pagination', 'Cursor-based pagination for /v2/charges', 'leo', `# Cursor-based pagination for /v2/charges
143
+
144
+ Offset pagination skips and repeats rows while new charges arrive.
145
+
146
+ ## Steps
147
+ 1. Add an opaque cursor (created_at, id) to \`GET /v2/charges\`.
148
+ 2. Keep \`offset\` working for one release and log its use.
149
+ 3. Update the SDK docs.
150
+ `);
151
+ const P2 = file('cursor-pagination', 'Cursor-based pagination for /v2/charges', 'leo', `# Cursor-based pagination for /v2/charges
152
+
153
+ Offset pagination skips and repeats rows while new charges arrive.
154
+
155
+ ## Steps
156
+ 1. Add an opaque, signed cursor (created_at, id) to \`GET /v2/charges\`.
157
+ 2. Keep \`offset\` working for one release and log its use.
158
+ 3. Add a composite index on (account_id, created_at, id).
159
+ 4. Update the SDK docs.
160
+ `);
161
+ const pagEvents = [
162
+ ev('noah', commentBody({ planId: 'cursor-pagination', version: v(P1), anchor: at(P1, 'opaque cursor'), text: 'Sign the cursor, or people will start hand-crafting them.', thread: 'p1sign', via: 'Lake review' }), 3300),
163
+ ev('leo', `**Revised plan \`cursor-pagination\`.**\n<sub>via lake-gate</sub>\n${encodeMarker('resolve', { p: 'cursor-pagination', t: 'p1sign', r: true })}`, 3200),
164
+ ev('noah', verdictBody({ action: 'approve', planId: 'cursor-pagination', version: v(P2), text: 'Index is the right call.', via: 'Lake review' }), 3100),
165
+ ev('maya', verdictBody({ action: 'approve', planId: 'cursor-pagination', version: v(P2), via: 'GitHub check button' }), 3050),
166
+ ];
167
+
168
+ // ---------- 4. Rotate API keys: draft ----------
169
+ const K1 = file('rotate-api-keys', 'Self-serve API key rotation', 'ava', `# Self-serve API key rotation
170
+
171
+ Customers open tickets to rotate keys. Let them do it with a grace period.
172
+
173
+ ## Steps
174
+ 1. Allow two active keys per account, each with a label and last-used time.
175
+ 2. Add \`POST /v2/keys/:id/roll\` that creates a new key and expires the old one after 24h.
176
+ 3. Audit-log every create, roll and revoke.
177
+ 4. Add tests for the grace period and audit entries.
178
+ `);
179
+
180
+ // ---------- 5. Usage alerts: fresh, needs you ----------
181
+ const U1 = file('usage-alerts', 'Usage alerts at 80% of plan', 'ines', `# Usage alerts at 80% of plan
182
+
183
+ Customers are surprised by overage charges. Warn them before they hit their limit.
184
+
185
+ ## Steps
186
+ 1. Add a nightly job that compares month-to-date usage with each account's plan limit.
187
+ 2. Send one email at 80% and one at 100%, at most once per month each.
188
+ 3. Add an "Alerts" toggle to account settings, on by default.
189
+ 4. Fix copy in the overage email.
190
+ `);
191
+ const usageEvents = [
192
+ ev('ines', `**Plan ready for review:** Usage alerts at 80% of plan\n@noah @leo\n\nWritten with Cursor. I'm not sure about the nightly job, happy to be told it's wrong.\n<sub>via lake-gate · Cursor (MCP)</sub>`, 48),
193
+ ev('leo', commentBody({ planId: 'usage-alerts', version: v(U1), anchor: at(U1, 'nightly job'), text: 'Nightly is fine to start. We already have hourly usage rollups if we want faster alerts later.', thread: 'u1night', via: 'Lake review' }), 22),
194
+ ];
195
+
196
+ // ---------- 6. Ledger: expensive, your plan, a model suggestion and a budget sign-off ----------
197
+ const L1 = file('double-entry-ledger', 'Move balances to a double-entry ledger', 'noah', `# Move balances to a double-entry ledger
198
+
199
+ Model: fable
200
+
201
+ Balances are a mutable column today. Two concurrent refunds can both read the old balance, and finance can't reconcile a month without a spreadsheet.
202
+
203
+ ## Steps
204
+ 1. Add a \`ledger_entries\` table (database migration) and backfill every historical charge and refund.
205
+ 2. Rewrite the balance service to sum ledger entries, with row locking for concurrent writes.
206
+ 3. Add a nightly reconciliation job that alerts on any drift.
207
+ 4. Rename the old balance columns to \`legacy_*\`.
208
+ 5. Update the README and the runbook (optional).
209
+
210
+ ## Risks
211
+ - The backfill is long. Run it in batches behind a flag.
212
+ `);
213
+ const ledgerEvents = [
214
+ ev('noah', `**Plan ready for review:** Move balances to a double-entry ledger\n@leo @ava @dana\n\nBig one. I asked for Fable because of the locking work.\n<sub>via lake-gate · Claude Code (MCP)</sub>`, 300),
215
+ ev('leo', commentBody({ planId: 'double-entry-ledger', version: v(L1), anchor: at(L1, 'backfill every historical'), text: 'Batch it by account and make it resumable. A 6-hour backfill will get interrupted.', thread: 'l1batch', via: 'Lake review' }), 240),
216
+ ev('ava', suggestionBody({ planId: 'double-entry-ledger', version: v(L1), title: 'Run the plan on Opus 5.5', patch: { type: 'planModel', model: 'Opus 5.5' }, saving: null, text: 'Opus handled our last locking change fine. Fable is a lot of money for a rename and a README.', thread: 'l1model', via: 'Lake review' }), 200),
217
+ ev('leo', verdictBody({ action: 'approve', planId: 'double-entry-ledger', version: v(L1), text: 'Solid. Batch the backfill.', via: 'GitHub review' }), 150),
218
+ ev('ava', verdictBody({ action: 'approve', planId: 'double-entry-ledger', version: v(L1), via: 'Lake review' }), 120),
219
+ ];
220
+
221
+ const PRS = [
222
+ { number: 421, title: 'Double-entry ledger', user: 'noah', draft: false, state: 'open', branch: 'noah/ledger', reviewers: ['leo', 'ava', 'dana'], versions: [[L1, 'l1', 310, 'noah']], events: ledgerEvents },
223
+ { number: 412, title: 'Webhook retries', user: 'maya', draft: false, state: 'open', branch: 'maya/webhook-retries', reviewers: ['noah', 'ava'], versions: [[W1, 'w1', 2920, 'maya'], [W2, 'w2', 1695, 'maya'], [W3, 'w3', 398, 'maya']], events: webhookEvents },
224
+ { number: 418, title: 'Usage alerts', user: 'ines', draft: false, state: 'open', branch: 'ines/usage-alerts', reviewers: ['noah', 'leo'], versions: [[U1, 'u1', 50, 'ines']], events: usageEvents },
225
+ { number: 409, title: 'Safer CSV exports', user: 'sam', draft: false, state: 'open', branch: 'sam/csv-exports', reviewers: ['maya'], versions: [[C1, 'c1', 260, 'sam']], events: csvEvents },
226
+ { number: 415, title: 'API key rotation', user: 'ava', draft: true, state: 'open', branch: 'ava/key-rotation', reviewers: [], versions: [[K1, 'k1', 75, 'ava']], events: [] },
227
+ { number: 397, title: 'Cursor pagination', user: 'leo', draft: false, state: 'closed', merged: true, branch: 'leo/cursor-pagination', reviewers: [], versions: [[P1, 'p1', 3400, 'leo'], [P2, 'p2', 3210, 'leo']], events: pagEvents },
228
+ ];
229
+
230
+ // Demo state is in memory; actions append events exactly as they would be posted to GitHub.
231
+ const extra = new Map();
232
+ export function demoPost(prNumber, body) {
233
+ const e = { id: `local${Date.now()}${Math.random().toString(36).slice(2, 6)}`, source: 'comment', login: VIEWER, type: 'User', association: 'MEMBER', body, createdAt: new Date().toISOString() };
234
+ if (!extra.has(prNumber)) extra.set(prNumber, []);
235
+ extra.get(prNumber).push(e);
236
+ return e;
237
+ }
238
+ const extraVersions = new Map();
239
+ // The author accepts a suggestion: the plan file gets a new version on the PR branch.
240
+ export function demoAccept(prNumber, patch) {
241
+ const p = PRS.find((x) => x.number === prNumber);
242
+ const all = [...p.versions, ...(extraVersions.get(prNumber) || [])];
243
+ const text = patchPlanFile(all[all.length - 1][0], patch, CONFIG);
244
+ if (!extraVersions.has(prNumber)) extraVersions.set(prNumber, []);
245
+ extraVersions.get(prNumber).push([text, `local${Date.now()}`, -(Date.now() - now) / 60000, VIEWER]);
246
+ return v(text);
247
+ }
248
+ export function demoReset() { extra.clear(); extraVersions.clear(); }
249
+
250
+ export function demoWorkspace() {
251
+ const plans = [];
252
+ for (const p of PRS) {
253
+ const vers = [...p.versions, ...(extraVersions.get(p.number) || [])];
254
+ const snaps = vers.map(([text, sha, min, author]) => ({ text, sha, at: ago(min), author }));
255
+ const versions = versionsFromSnapshots(snaps, 'x');
256
+ const digestAt = {}; vers.forEach(([text, sha]) => { digestAt[sha] = v(text); });
257
+ const plan = versions[versions.length - 1];
258
+ const pr = { number: p.number, title: p.title, html_url: `https://github.com/${REPO}/pull/${p.number}`, draft: p.draft, state: p.state, merged_at: p.merged ? ago(3000) : null, head: { ref: p.branch } };
259
+ plans.push(buildPlanReview({ plan, versions, events: [...p.events, ...(extra.get(p.number) || [])], prAuthor: p.user, config: CONFIG, digestAt, pr, requestedReviewers: p.reviewers }));
260
+ }
261
+ return { repo: REPO, plans, viewer: VIEWER, people: PEOPLE, config: CONFIG, mode: 'demo' };
262
+ }
package/ui/index.html ADDED
@@ -0,0 +1,55 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
6
+ <title>Lake review · lake-gate</title>
7
+ <meta name="description" content="Review your coding agent's plans: inline comments, review rounds, version-bound approval. Reads and writes your GitHub PR. No Lake server.">
8
+ <meta name="robots" content="noindex">
9
+ <meta name="theme-color" content="#F1F7F6">
10
+ <!--LAKE_KEY-->
11
+ <link rel="icon" href="logo-mark.svg" type="image/svg+xml">
12
+ <link rel="preload" href="inter.woff2" as="font" type="font/woff2" crossorigin>
13
+ <link rel="stylesheet" href="app.css">
14
+ </head>
15
+ <body>
16
+ <svg class="sprite" aria-hidden="true">
17
+ <symbol id="i-check" viewBox="0 0 24 24"><path d="M5 12.5l4.5 4.5L19 7.5"/></symbol>
18
+ <symbol id="i-spark" viewBox="0 0 24 24"><path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 16l.7 1.8 1.8.7-1.8.7-.7 1.8-.7-1.8-1.8-.7 1.8-.7z"/></symbol>
19
+ <symbol id="i-cpu" viewBox="0 0 24 24"><rect x="6.5" y="6.5" width="11" height="11" rx="2.5"/><path d="M10 10h4v4h-4zM9.5 3.5v3M14.5 3.5v3M9.5 17.5v3M14.5 17.5v3M3.5 9.5h3M3.5 14.5h3M17.5 9.5h3M17.5 14.5h3"/></symbol>
20
+ <symbol id="i-x" viewBox="0 0 24 24"><path d="M6 6l12 12M18 6L6 18"/></symbol>
21
+ <symbol id="i-msg" viewBox="0 0 24 24"><path d="M5 5h14a2 2 0 012 2v8a2 2 0 01-2 2h-7l-4.5 3.5V17H5a2 2 0 01-2-2V7a2 2 0 012-2z"/></symbol>
22
+ <symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 7.5V12l3 2"/></symbol>
23
+ <symbol id="i-pr" viewBox="0 0 24 24"><circle cx="6" cy="6" r="2.2"/><circle cx="6" cy="18" r="2.2"/><circle cx="18" cy="18" r="2.2"/><path d="M6 8.2v7.6M18 15.8V10a3 3 0 00-3-3h-4m2-2.5L10.5 7 13 9.5"/></symbol>
24
+ <symbol id="i-chev" viewBox="0 0 24 24"><path d="M9.5 6l6 6-6 6"/></symbol>
25
+ <symbol id="i-chevd" viewBox="0 0 24 24"><path d="M6 9.5l6 6 6-6"/></symbol>
26
+ <symbol id="i-arrow" viewBox="0 0 24 24"><path d="M5 12h13m-5-5.5L18.5 12 13 17.5"/></symbol>
27
+ <symbol id="i-back" viewBox="0 0 24 24"><path d="M19 12H6m5-5.5L5.5 12l5.5 5.5"/></symbol>
28
+ <symbol id="i-layers" viewBox="0 0 24 24"><path d="M12 3.5l8.5 4.5-8.5 4.5L3.5 8z"/><path d="M3.5 12.5l8.5 4.5 8.5-4.5"/><path d="M3.5 16.5l8.5 4.5 8.5-4.5" opacity=".5"/></symbol>
29
+ <symbol id="i-pulse" viewBox="0 0 24 24"><path d="M3 12h4l2.5-6 5 12 2.5-6h4"/></symbol>
30
+ <symbol id="i-inbox" viewBox="0 0 24 24"><path d="M4 13.5l2.2-7.2A2 2 0 018.1 5h7.8a2 2 0 011.9 1.3l2.2 7.2V18a2 2 0 01-2 2H6a2 2 0 01-2-2z"/><path d="M4 13.5h4.5l1.2 2.2h4.6l1.2-2.2H20"/></symbol>
31
+ <symbol id="i-diff" viewBox="0 0 24 24"><path d="M8 4v10M3 9h10M11 20h10"/><path d="M16 4l3 3-3 3" opacity="0"/></symbol>
32
+ <symbol id="i-kbd" viewBox="0 0 24 24"><rect x="3" y="6.5" width="18" height="11" rx="2.2"/><path d="M7 10.5h.01M10.5 10.5h.01M14 10.5h.01M17 10.5h.01M8 14h8"/></symbol>
33
+ <symbol id="i-search" viewBox="0 0 24 24"><circle cx="11" cy="11" r="6.5"/><path d="M16 16l4 4"/></symbol>
34
+ <symbol id="i-gh" viewBox="0 0 24 24"><path d="M9 19c-4 1.3-4-2-5.6-2.5M14.6 21v-3.4c0-1 .1-1.4-.5-2 2.8-.3 5.6-1.4 5.6-6.1a4.8 4.8 0 00-1.3-3.3 4.4 4.4 0 00-.1-3.3s-1.1-.3-3.5 1.3a12 12 0 00-6.2 0C6.2 2.6 5.1 2.9 5.1 2.9a4.4 4.4 0 00-.1 3.3 4.8 4.8 0 00-1.3 3.3c0 4.7 2.8 5.8 5.6 6.1-.6.6-.6 1.2-.5 2V21"/></symbol>
35
+ <symbol id="i-coin" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M14.5 9.2c-.4-.8-1.3-1.3-2.5-1.3-1.5 0-2.5.8-2.5 1.9 0 2.7 5.2 1.4 5.2 4.2 0 1.1-1.1 2-2.7 2-1.3 0-2.3-.6-2.7-1.5M12 6.5v1.4m0 8.2v1.4"/></symbol>
36
+ <symbol id="i-dot" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4" fill="currentColor" stroke="none"/></symbol>
37
+ <symbol id="i-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></symbol>
38
+ <symbol id="i-undo" viewBox="0 0 24 24"><path d="M9 7L4.5 11.5 9 16"/><path d="M5 11.5h9.5a5 5 0 010 10H12"/></symbol>
39
+ <symbol id="i-bot" viewBox="0 0 24 24"><rect x="4.5" y="8" width="15" height="11" rx="3"/><path d="M12 8V4.5M9 13h.01M15 13h.01M9.5 16.2h5"/></symbol>
40
+ <symbol id="i-lock" viewBox="0 0 24 24"><rect x="5" y="10.5" width="14" height="9.5" rx="2"/><path d="M8.5 10.5V8a3.5 3.5 0 017 0v2.5"/></symbol>
41
+ <symbol id="i-menu" viewBox="0 0 24 24"><path d="M4 7h16M4 12h16M4 17h10"/></symbol>
42
+ <symbol id="i-ext" viewBox="0 0 24 24"><path d="M14 4h6v6M20 4l-8.5 8.5M18 14v4a2 2 0 01-2 2H6a2 2 0 01-2-2V8a2 2 0 012-2h4"/></symbol>
43
+ <symbol id="i-file" viewBox="0 0 24 24"><path d="M7 3.5h7l4.5 4.5v12.5H7a1.5 1.5 0 01-1.5-1.5V5A1.5 1.5 0 017 3.5z"/><path d="M14 3.5V8h4.5M9 12.5h6M9 16h4"/></symbol>
44
+ <symbol id="i-pause" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M10 9v6M14 9v6"/></symbol>
45
+ <symbol id="i-refresh" viewBox="0 0 24 24"><path d="M19.5 12a7.5 7.5 0 11-2.2-5.3M19.5 4.5v4h-4"/></symbol>
46
+ </svg>
47
+ <div id="app" aria-live="polite"><div class="loading" style="min-height:60vh;display:grid;place-items:center;color:#5b767c;font:500 14px Inter,system-ui,sans-serif"><span>Loading Lake review…</span></div></div>
48
+ <div id="toast" role="status" aria-live="polite"></div>
49
+ <script type="module" src="app.js"></script>
50
+ <script>
51
+ // If the app module fails to load (old cache, blocked file), say so instead of a blank page.
52
+ window.__lakeBoot = setTimeout(function () { var a = document.getElementById('app'); if (a && a.textContent.indexOf('Loading Lake review') >= 0) a.innerHTML = '<div style="min-height:60vh;display:grid;place-items:center;text-align:center;font:500 14px Inter,system-ui,sans-serif;color:#073f4b"><div><b style="display:block;font-size:16px;margin-bottom:6px">Couldn\'t load the review app.</b>Reload the page, or run <code>npx lake-gate ui</code> in your repo.</div></div>'; }, 6000);
53
+ </script>
54
+ </body>
55
+ </html>
package/ui/inter.woff2 ADDED
Binary file
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128" role="img" aria-label="Lake"><defs><linearGradient id="water" x1="0" y1="0" x2="0.4" y2="1"><stop stop-color="#62B8A3"/><stop offset=".5" stop-color="#4CB7B1"/><stop offset="1" stop-color="#176A73"/></linearGradient><clipPath id="disc"><circle cx="64" cy="64" r="55"/></clipPath></defs><g clip-path="url(#disc)"><circle cx="64" cy="64" r="55" fill="url(#water)"/><path d="M4 51 C28 35 43 40 65 49 S103 57 124 43 L124 54 C102 70 85 67 63 59 S26 46 4 63 Z" fill="#F1F7F6"/><path d="M4 81 C28 65 43 70 65 79 S103 87 124 73 L124 84 C102 100 85 97 63 89 S26 76 4 93 Z" fill="#F1F7F6"/></g></svg>
package/ui/md.js ADDED
@@ -0,0 +1,82 @@
1
+ // Small markdown renderer that keeps source line ranges on every block and list item,
2
+ // so comments can be anchored to lines and survive re-rendering. No dependencies.
3
+ import { stripEstimate } from './core/plan.js';
4
+
5
+ export const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
6
+
7
+ export function inline(s) {
8
+ const codes = [];
9
+ let t = esc(s).replace(/`([^`]+)`/g, (_, c) => { codes.push(c); return `\u0000${codes.length - 1}\u0000`; });
10
+ t = t.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>').replace(/(^|[\s(])\*([^*\s][^*]*)\*/g, '$1<em>$2</em>').replace(/(^|[\s(])_([^_\s][^_]*)_/g, '$1<em>$2</em>')
11
+ .replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>')
12
+ .replace(/~~([^~]+)~~/g, '<del>$1</del>');
13
+ return t.replace(/\u0000(\d+)\u0000/g, (_, i) => `<code>${codes[i]}</code>`);
14
+ }
15
+
16
+ const LIST = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/;
17
+
18
+ // Returns [{type, start, end, html, text, level?, items?}] with 1-based line numbers of the plan body.
19
+ export function parseBlocks(body) {
20
+ const lines = stripEstimate(String(body)).split('\n');
21
+ const blocks = []; let i = 0;
22
+ const N = lines.length;
23
+ while (i < N) {
24
+ const l = lines[i];
25
+ if (!l.trim()) { i++; continue; }
26
+ const s = i + 1;
27
+ let m;
28
+ if ((m = l.match(/^```(\w*)/))) {
29
+ const buf = []; i++;
30
+ while (i < N && !/^```/.test(lines[i])) buf.push(lines[i++]);
31
+ i++;
32
+ blocks.push({ type: 'code', start: s, end: Math.min(i, N), lang: m[1], text: buf.join('\n'), html: `<pre><code>${esc(buf.join('\n'))}</code></pre>` });
33
+ continue;
34
+ }
35
+ if ((m = l.match(/^(#{1,6})\s+(.*)$/))) { blocks.push({ type: 'heading', level: m[1].length, start: s, end: s, text: m[2], html: inline(m[2]) }); i++; continue; }
36
+ if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(l)) { blocks.push({ type: 'hr', start: s, end: s, html: '<hr>' }); i++; continue; }
37
+ if (/^\s*\|.*\|\s*$/.test(l)) {
38
+ const rows = [];
39
+ while (i < N && /^\s*\|.*\|\s*$/.test(lines[i])) rows.push(lines[i++]);
40
+ const cells = (r) => r.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
41
+ const head = cells(rows[0]); const bodyRows = rows.slice(1).filter((r) => !/^\s*\|[\s:|-]+\|\s*$/.test(r));
42
+ blocks.push({ type: 'table', start: s, end: i, text: rows.join('\n'), html: `<div class="tbl"><table><thead><tr>${head.map((c) => `<th>${inline(c)}</th>`).join('')}</tr></thead><tbody>${bodyRows.map((r) => `<tr>${cells(r).map((c) => `<td>${inline(c)}</td>`).join('')}</tr>`).join('')}</tbody></table></div>` });
43
+ continue;
44
+ }
45
+ if (/^>\s?/.test(l)) {
46
+ const buf = [];
47
+ while (i < N && /^>\s?/.test(lines[i])) buf.push(lines[i++].replace(/^>\s?/, ''));
48
+ blocks.push({ type: 'quote', start: s, end: i, text: buf.join('\n'), html: `<blockquote>${inline(buf.join(' '))}</blockquote>` });
49
+ continue;
50
+ }
51
+ if ((m = l.match(LIST)) && m[1].length <= 3) {
52
+ const ordered = /\d/.test(m[2]); const items = [];
53
+ while (i < N) {
54
+ const lm = lines[i].match(LIST);
55
+ if (lm && lm[1].length <= 3) { items.push({ start: i + 1, end: i + 1, num: parseInt(lm[2], 10), text: lm[3], sub: [] }); i++; continue; }
56
+ if (items.length && /^\s{2,}\S/.test(lines[i])) {
57
+ const it = items[items.length - 1]; const sub = lines[i].trim();
58
+ const sm = sub.match(/^([-*+]|\d+[.)])\s+(.*)$/);
59
+ if (sm) it.sub.push(sm[2]); else it.text += ' ' + sub;
60
+ it.end = i + 1; i++; continue;
61
+ }
62
+ if (!lines[i].trim() && i + 1 < N && (LIST.test(lines[i + 1]) || /^\s{2,}\S/.test(lines[i + 1])) && items.length) { i++; continue; }
63
+ break;
64
+ }
65
+ blocks.push({ type: 'list', ordered, start: s, end: items[items.length - 1].end, items, text: items.map((x) => x.text).join('\n') });
66
+ continue;
67
+ }
68
+ const buf = [];
69
+ while (i < N && lines[i].trim() && !/^(#{1,6}\s|```|>|\s*\|)/.test(lines[i]) && !(LIST.test(lines[i]) && buf.length)) buf.push(lines[i++]);
70
+ if (!buf.length) { buf.push(lines[i++]); }
71
+ blocks.push({ type: 'p', start: s, end: s + buf.length - 1, text: buf.join(' '), html: `<p>${inline(buf.join(' '))}</p>` });
72
+ }
73
+ return blocks;
74
+ }
75
+
76
+ // Section outline (## headings) with line ranges.
77
+ export function outline(blocks) {
78
+ const out = [];
79
+ for (const b of blocks) if (b.type === 'heading' && b.level <= 3) out.push({ title: b.text, start: b.start, level: b.level });
80
+ out.forEach((o, k) => { o.end = out[k + 1] ? out[k + 1].start - 1 : Infinity; });
81
+ return out;
82
+ }