lake-gate 0.0.0-stage → 0.2.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/src/review.js ADDED
@@ -0,0 +1,319 @@
1
+ // Review model: plan versions (rounds), anchored comment threads, verdicts and an activity timeline.
2
+ // Pure and browser-safe. The source of truth stays on the PR: every comment, reply, resolve and verdict
3
+ // is an ordinary PR comment carrying a small hidden marker, so it survives without any Lake server and
4
+ // is readable by humans on GitHub. Native GitHub line comments on the plan file and native PR reviews
5
+ // (Approve / Request changes) are mapped into the same model.
6
+ import { readPlanText, splitFrontmatter, stripEstimate } from './plan.js';
7
+ import { estimatePlan } from './estimate.js';
8
+ import { costSuggestions, modelOptions } from './models.js';
9
+ import { evaluatePlan, parseCommands } from './policy.js';
10
+
11
+ const MARK = /<!--\s*lake:(c|resolve|v|proxy)\s+(\{[\s\S]*?\})\s*-->/g;
12
+ export const PROXY_LOGIN = 'github-actions[bot]';
13
+
14
+ export function encodeMarker(kind, data) {
15
+ // "--" can't appear inside an HTML comment; JSON-escape it.
16
+ return `<!-- lake:${kind} ${JSON.stringify(data).replace(/--/g, '\\u002d\\u002d')} -->`;
17
+ }
18
+
19
+ export function parseMarkers(body) {
20
+ const out = [];
21
+ for (const m of String(body || '').matchAll(MARK)) {
22
+ try { out.push({ kind: m[1], data: JSON.parse(m[2]) }); } catch { /* ignore broken marker */ }
23
+ }
24
+ return out;
25
+ }
26
+
27
+ const CMD_LINE = /^\s*\/lake\s+(approve|reject|revoke)\b.*$/gim;
28
+ // Human text of a comment: no markers, no /lake command lines, no quoted anchor preview we generated.
29
+ export function messageOf(body) {
30
+ return String(body || '').replace(MARK, '').replace(CMD_LINE, '')
31
+ .replace(/^<sub>.*lake-gate.*<\/sub>$/gim, '')
32
+ .replace(/^\*\*(Comment on|Reply on|Resolved|Reopened|Suggestion on|Accepted suggestion) [^\n]*\*\*.*$/gim, '')
33
+ .replace(/^>.*$/gm, '').trim();
34
+ }
35
+
36
+ export const shortOf = (d) => String(d || '').slice(0, 8);
37
+ export function newId(n = 8) {
38
+ const a = 'abcdefghijkmnpqrstuvwxyz23456789';
39
+ let s = ''; for (let i = 0; i < n; i++) s += a[Math.floor(Math.random() * a.length)];
40
+ return s;
41
+ }
42
+
43
+ const quoteBlock = (q) => String(q || '').split('\n').slice(0, 4).map((l) => `> ${l}`).join('\n');
44
+ const footer = (via) => `<sub>via lake-gate${via ? ` · ${via}` : ''}</sub>`;
45
+
46
+ // ---- Bodies that the UI, the MCP server and the CLI post to the PR ----
47
+ export function commentBody({ planId, version, anchor, text, thread = newId(), via }) {
48
+ const where = anchor?.heading ? ` · ${anchor.heading}` : anchor ? ` · line ${anchor.start}${anchor.end > anchor.start ? `–${anchor.end}` : ''}` : '';
49
+ return [`**Comment on \`${planId}\` v${shortOf(version)}${where}**`, anchor?.quote ? quoteBlock(anchor.quote) : null, '', String(text).trim(), '', footer(via),
50
+ encodeMarker('c', { p: planId, v: shortOf(version), t: thread, ...(anchor ? { a: { s: anchor.start, e: anchor.end || anchor.start, q: String(anchor.quote || '').slice(0, 300), h: anchor.heading || undefined } } : {}) })]
51
+ .filter((x) => x !== null).join('\n');
52
+ }
53
+ // A structured suggestion (model change, cheaper steps, cap, drop a step). The author applies it in one click,
54
+ // which commits a new plan version; the thread then shows as accepted.
55
+ export function suggestionBody({ planId, version, title, patch, saving, text, thread = newId(), via, anchor }) {
56
+ const save = saving && saving[1] > 0.005 ? ` · saves up to $${saving[1] < 10 ? saving[1].toFixed(2) : Math.round(saving[1])}` : '';
57
+ return [`**Suggestion on \`${planId}\` v${shortOf(version)}: ${String(title).replace(/\*/g, '')}**${save}`, '', text ? String(text).trim() : null, text ? '' : null, footer(via),
58
+ encodeMarker('c', { p: planId, v: shortOf(version), t: thread, s: { title: String(title).slice(0, 140), patch, save: saving || null }, ...(anchor ? { a: { s: anchor.start, e: anchor.end || anchor.start, q: String(anchor.quote || '').slice(0, 300) } } : {}) })]
59
+ .filter((x) => x !== null).join('\n');
60
+ }
61
+ export function acceptBody({ planId, thread, title, newVersion, via }) {
62
+ return [`**Accepted suggestion on \`${planId}\`: ${String(title || '').replace(/\*/g, '')}** → v${shortOf(newVersion)}`, '', 'This is a new plan version, so earlier approvals no longer apply.', '', footer(via),
63
+ encodeMarker('resolve', { p: planId, t: thread, r: true, acc: 1, nv: shortOf(newVersion) })].join('\n');
64
+ }
65
+ export function replyBody({ planId, thread, text, via }) {
66
+ return [`**Reply on \`${planId}\`**`, '', String(text).trim(), '', footer(via), encodeMarker('c', { p: planId, t: thread, re: 1 })].join('\n');
67
+ }
68
+ export function resolveBody({ planId, thread, resolved = true, text, via }) {
69
+ return [`**${resolved ? 'Resolved' : 'Reopened'} a thread on \`${planId}\`**`, text ? `\n${String(text).trim()}` : null, '', footer(via), encodeMarker('resolve', { p: planId, t: thread, r: resolved })]
70
+ .filter((x) => x !== null).join('\n');
71
+ }
72
+ // approve | reject. The /lake line is what lake-gate's policy counts; the rest is the reviewer's note.
73
+ export function verdictBody({ action, planId, version, text, via, resolves = [] }) {
74
+ const cmd = action === 'approve' ? 'approve' : 'reject';
75
+ return [`/lake ${cmd} ${planId}@${shortOf(version)}`, text && String(text).trim() ? `\n${String(text).trim()}` : null, '', footer(via),
76
+ via ? encodeMarker('v', { via }) : null, ...resolves.map((t) => encodeMarker('resolve', { p: planId, t, r: true }))].filter((x) => x !== null).join('\n');
77
+ }
78
+
79
+ // ---- Normalizing GitHub REST objects ----
80
+ export function normalizeIssueComment(c) {
81
+ return { id: `c${c.id}`, ghId: c.id, source: 'comment', login: c.user.login, type: c.user.type, association: c.author_association, body: c.body || '', createdAt: c.created_at, url: c.html_url };
82
+ }
83
+ export function normalizeReview(r) {
84
+ return { id: `r${r.id}`, ghId: r.id, source: 'review', login: r.user.login, type: r.user.type, association: r.author_association, body: r.body || '', createdAt: r.submitted_at, state: r.state, commitId: r.commit_id, url: r.html_url };
85
+ }
86
+ export function normalizeLineComment(c) {
87
+ return { id: `l${c.id}`, ghId: c.id, source: 'line', login: c.user.login, type: c.user.type, association: c.author_association, body: c.body || '', createdAt: c.created_at,
88
+ path: c.path, line: c.line ?? c.original_line, startLine: c.start_line ?? c.original_start_line ?? null, commitId: c.original_commit_id || c.commit_id, inReplyTo: c.in_reply_to_id ? `l${c.in_reply_to_id}` : null, url: c.html_url };
89
+ }
90
+
91
+ // One plan file at one commit.
92
+ export function versionFromText(text, { sha = null, at = null, author = null, fallbackId } = {}) {
93
+ const p = readPlanText(text, fallbackId);
94
+ const fm = String(text).replace(/\r\n?/g, '\n').match(/^---\n[\s\S]*?\n---\n?/);
95
+ return { id: p.id, title: p.title, digest: p.digest, short: p.short, body: p.body, meta: p.meta, offset: fm ? fm[0].split('\n').length - 1 : 0, sha, at, author };
96
+ }
97
+
98
+ // Chronological unique versions from a list of {text, sha, at, author} snapshots.
99
+ export function versionsFromSnapshots(snaps, fallbackId) {
100
+ const out = [];
101
+ for (const s of snaps) {
102
+ if (s.text == null) continue;
103
+ const v = versionFromText(s.text, { ...s, fallbackId });
104
+ if (!out.length || out[out.length - 1].digest !== v.digest) {
105
+ if (!out.some((o) => o.digest === v.digest)) out.push(v);
106
+ }
107
+ }
108
+ return out;
109
+ }
110
+
111
+ const NATIVE = { APPROVED: 'approve', CHANGES_REQUESTED: 'reject' };
112
+
113
+ // Makes the event list policy-ready for ONE plan:
114
+ // - a native GitHub review (Approve / Request changes) without a /lake line counts for the plan version at the reviewed commit;
115
+ // - a check-button click relayed by the Action (bot comment with a proxy marker) counts as the clicking user.
116
+ export function expandEvents(events, { planId, digestAt = {}, config = {} }) {
117
+ const out = [];
118
+ for (const ev of events) {
119
+ if (ev.source === 'line') continue;
120
+ let e = ev;
121
+ const proxy = parseMarkers(ev.body).find((m) => m.kind === 'proxy');
122
+ if (proxy && ev.login === PROXY_LOGIN && ev.type === 'Bot' && proxy.data.by) {
123
+ e = { ...ev, login: proxy.data.by, type: 'User', association: proxy.data.assoc || 'NONE', via: 'GitHub check button' };
124
+ }
125
+ if (config.nativeReviews !== false && ev.source === 'review' && NATIVE[ev.state] && !parseCommands(ev.body).length) {
126
+ const d = ev.commitId && digestAt[ev.commitId];
127
+ if (d) e = { ...e, body: `/lake ${NATIVE[ev.state]} ${planId}@${d}\n${ev.body || ''}`, via: 'GitHub review', native: true };
128
+ }
129
+ out.push(e);
130
+ }
131
+ return out;
132
+ }
133
+
134
+ // ---- Diff ----
135
+ export function lineDiff(a, b) {
136
+ const A = clean(a).split('\n'); const B = clean(b).split('\n');
137
+ const n = A.length; const m = B.length;
138
+ const L = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
139
+ for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = A[i] === B[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
140
+ const out = []; let i = 0; let j = 0;
141
+ while (i < n && j < m) {
142
+ if (A[i] === B[j]) { out.push({ op: 'same', text: A[i], a: i + 1, b: j + 1 }); i++; j++; }
143
+ else if (L[i + 1][j] >= L[i][j + 1]) { out.push({ op: 'del', text: A[i], a: i + 1 }); i++; }
144
+ else { out.push({ op: 'add', text: B[j], b: j + 1 }); j++; }
145
+ }
146
+ while (i < n) { out.push({ op: 'del', text: A[i], a: i + 1 }); i++; }
147
+ while (j < m) { out.push({ op: 'add', text: B[j], b: j + 1 }); j++; }
148
+ return out;
149
+ }
150
+ function clean(body) { return stripEstimate(String(body)).replace(/\s+$/, ''); }
151
+
152
+ // Word-level spans for a changed line pair: [{op:'same'|'add'|'del', text}]
153
+ export function wordDiff(a, b) {
154
+ const A = a.split(/(\s+)/); const B = b.split(/(\s+)/);
155
+ const n = A.length; const m = B.length;
156
+ if (n * m > 40000) return [{ op: 'del', text: a }, { op: 'add', text: b }];
157
+ const L = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
158
+ for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = A[i] === B[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
159
+ const out = []; let i = 0; let j = 0;
160
+ const push = (op, text) => { const last = out[out.length - 1]; if (last && last.op === op) last.text += text; else out.push({ op, text }); };
161
+ while (i < n && j < m) {
162
+ if (A[i] === B[j]) { push('same', A[i]); i++; j++; } else if (L[i + 1][j] >= L[i][j + 1]) { push('del', A[i]); i++; } else { push('add', B[j]); j++; }
163
+ }
164
+ while (i < n) push('del', A[i++]);
165
+ while (j < m) push('add', B[j++]);
166
+ return out;
167
+ }
168
+
169
+ export function diffStats(diff) {
170
+ return { added: diff.filter((d) => d.op === 'add').length, removed: diff.filter((d) => d.op === 'del').length };
171
+ }
172
+
173
+ // Where does an anchor (from an older version) land in another version's body? null = outdated.
174
+ export function relocateAnchor(anchor, body) {
175
+ if (!anchor) return null;
176
+ const lines = String(body).split('\n');
177
+ const q = String(anchor.quote || '').trim();
178
+ if (!q) return anchor.start <= lines.length ? { start: anchor.start, end: anchor.end } : null;
179
+ const first = q.split('\n')[0].trim().replace(/^([-*+]|\d+[.)])\s+/, '');
180
+ const hits = [];
181
+ lines.forEach((l, i) => { if (l.includes(first)) hits.push(i + 1); });
182
+ if (!hits.length) return null;
183
+ const best = hits.reduce((a, h) => (Math.abs(h - anchor.start) < Math.abs(a - anchor.start) ? h : a), hits[0]);
184
+ return { start: best, end: best + (anchor.end - anchor.start) };
185
+ }
186
+
187
+ function headingFor(body, line) {
188
+ const lines = String(body).split('\n');
189
+ for (let i = Math.min(line, lines.length) - 1; i >= 0; i--) { const m = lines[i].match(/^#{1,4}\s+(.+)$/); if (m) return m[1].trim(); }
190
+ return null;
191
+ }
192
+
193
+ // ---- The model ----
194
+ // plan: current plan ({id, title, body, digest, short, meta}); versions: chronological [{digest, body, at, sha, author, offset}]
195
+ // events: normalized events (comments, reviews, line comments); digestAt: {commitSha: digest} for this plan's file
196
+ export function buildPlanReview({ plan, versions = [], events = [], prAuthor = null, config, digestAt = {}, pr = null, requestedReviewers = [], budgetApprovers }) {
197
+ const vs = versions.length ? [...versions] : [];
198
+ if (!vs.some((v) => v.digest === plan.digest)) vs.push({ ...plan, offset: plan.offset || 0, at: plan.at || null, author: plan.author || null });
199
+ const byPrefix = (p) => (p ? vs.find((v) => v.digest.startsWith(String(p).toLowerCase())) : null);
200
+ const vIndex = (d) => vs.findIndex((v) => v.digest === d);
201
+ const current = vs[vIndex(plan.digest)];
202
+ const estimate = estimatePlan(plan.body, config);
203
+ const expanded = expandEvents(events, { planId: plan.id, digestAt, config });
204
+ const policy = evaluatePlan({ plan, estimate, events: expanded, prAuthor, config, budgetApprovers });
205
+ const sorted = [...events].sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
206
+ const expandedById = new Map(expanded.map((e) => [e.id, e]));
207
+
208
+ const verdicts = []; const threads = new Map(); const timeline = []; const resolves = [];
209
+ const planPath = `.lake/plans/${plan.id}.md`;
210
+
211
+ for (const raw of sorted) {
212
+ const ev = expandedById.get(raw.id) || raw;
213
+ const markers = parseMarkers(raw.body);
214
+ const viaMarker = markers.find((m) => m.kind === 'v');
215
+ // verdicts
216
+ for (const c of parseCommands(ev.body)) {
217
+ if (c.id !== plan.id) continue;
218
+ const v = byPrefix(c.digest);
219
+ const item = { login: ev.login, action: c.action, version: v ? v.digest : null, short: v ? v.short : shortOf(c.digest), n: v ? vIndex(v.digest) + 1 : null,
220
+ text: messageOf(raw.body), at: ev.createdAt, via: ev.via || viaMarker?.data.via || (raw.source === 'review' ? 'GitHub review' : 'PR comment'),
221
+ self: !!(prAuthor && ev.login.toLowerCase() === prAuthor.toLowerCase()), bot: ev.type === 'Bot', url: raw.url, eventId: raw.id };
222
+ verdicts.push(item);
223
+ timeline.push({ kind: c.action, login: item.login, at: item.at, short: item.short, n: item.n, text: item.text, via: item.via, self: item.self });
224
+ }
225
+ // Lake marker threads
226
+ for (const m of markers) {
227
+ if (m.data.p !== plan.id) continue;
228
+ if (m.kind === 'c' && !m.data.re && m.data.t) {
229
+ const v = byPrefix(m.data.v) || current;
230
+ const a = m.data.a ? { start: m.data.a.s, end: m.data.a.e ?? m.data.a.s, quote: m.data.a.q || '', heading: m.data.a.h || headingFor(v.body, m.data.a.s) } : null;
231
+ threads.set(m.data.t, { id: m.data.t, version: v.digest, short: v.short, n: vIndex(v.digest) + 1, anchor: a, comments: [], resolved: false, resolvedBy: null, source: 'lake',
232
+ suggestion: m.data.s ? { title: String(m.data.s.title || ''), patch: m.data.s.patch, saving: m.data.s.save || null, by: raw.login, accepted: false } : null });
233
+ threads.get(m.data.t).comments.push({ login: raw.login, text: messageOf(raw.body), at: raw.createdAt, id: raw.id, url: raw.url });
234
+ timeline.push({ kind: 'comment', login: raw.login, at: raw.createdAt, short: v.short, n: vIndex(v.digest) + 1, text: messageOf(raw.body), thread: m.data.t, where: a?.heading || null });
235
+ } else if (m.kind === 'c' && m.data.re && threads.has(m.data.t)) {
236
+ threads.get(m.data.t).comments.push({ login: raw.login, text: messageOf(raw.body), at: raw.createdAt, id: raw.id, url: raw.url });
237
+ timeline.push({ kind: 'reply', login: raw.login, at: raw.createdAt, text: messageOf(raw.body), thread: m.data.t });
238
+ } else if (m.kind === 'resolve') {
239
+ resolves.push({ t: m.data.t, r: m.data.r !== false, login: raw.login, at: raw.createdAt, acc: !!m.data.acc, nv: m.data.nv || null });
240
+ }
241
+ }
242
+ // Native GitHub line comments on the plan file
243
+ if (raw.source === 'line' && raw.path === planPath) {
244
+ if (!raw.inReplyTo) {
245
+ const v = (raw.commitId && byPrefix(digestAt[raw.commitId])) || current;
246
+ const start = Math.max(1, (raw.startLine || raw.line) - (v.offset || 0)); const end = Math.max(start, raw.line - (v.offset || 0));
247
+ const quote = String(v.body).split('\n').slice(start - 1, end).join('\n');
248
+ threads.set(raw.id, { id: raw.id, version: v.digest, short: v.short, n: vIndex(v.digest) + 1, anchor: { start, end, quote, heading: headingFor(v.body, start) }, comments: [], resolved: false, resolvedBy: null, source: 'github' });
249
+ timeline.push({ kind: 'comment', login: raw.login, at: raw.createdAt, short: v.short, n: vIndex(v.digest) + 1, text: raw.body, thread: raw.id, where: headingFor(v.body, start) });
250
+ } else if (threads.has(raw.inReplyTo)) timeline.push({ kind: 'reply', login: raw.login, at: raw.createdAt, text: raw.body, thread: raw.inReplyTo });
251
+ const t = threads.get(raw.inReplyTo || raw.id);
252
+ if (t) t.comments.push({ login: raw.login, text: raw.body, at: raw.createdAt, id: raw.id, url: raw.url });
253
+ }
254
+ }
255
+ for (const r of resolves) {
256
+ const t = threads.get(r.t); if (!t) continue;
257
+ t.resolved = r.r; t.resolvedBy = r.r ? r.login : null; t.resolvedAt = r.r ? r.at : null;
258
+ if (t.suggestion && r.acc) { t.suggestion = { ...t.suggestion, accepted: true, acceptedBy: r.login, newVersion: r.nv }; timeline.push({ kind: 'accept', login: r.login, at: r.at, thread: r.t, text: t.suggestion.title, short: r.nv }); continue; }
259
+ timeline.push({ kind: r.r ? 'resolve' : 'reopen', login: r.login, at: r.at, thread: r.t });
260
+ }
261
+ // Where each thread sits on the current version
262
+ const allThreads = [...threads.values()].map((t) => {
263
+ if (t.version === plan.digest) return { ...t, outdated: false, current: t.anchor ? { start: t.anchor.start, end: t.anchor.end } : null };
264
+ const loc = relocateAnchor(t.anchor, plan.body);
265
+ return { ...t, outdated: !loc && !!t.anchor, current: loc };
266
+ });
267
+ for (const v of vs) timeline.push({ kind: 'version', login: v.author || null, at: v.at, short: v.short, n: vIndex(v.digest) + 1 });
268
+ timeline.sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')));
269
+
270
+ // Reviewers: latest verdict per person; people asked to review but silent are "waiting"
271
+ const reviewers = new Map();
272
+ for (const r of requestedReviewers) reviewers.set(r, { login: r, verdict: 'waiting', at: null, current: false });
273
+ for (const v of verdicts) {
274
+ if (v.self || v.bot) continue;
275
+ if (v.action === 'revoke') { reviewers.set(v.login, { login: v.login, verdict: 'revoked', at: v.at, current: false }); continue; }
276
+ reviewers.set(v.login, { login: v.login, verdict: v.action === 'approve' ? 'approved' : 'changes-requested', at: v.at, short: v.short, n: v.n, current: v.version === plan.digest, text: v.text, via: v.via });
277
+ }
278
+ if (policy.budget?.required) {
279
+ for (const b of policy.budget.approvers) {
280
+ if (prAuthor && b.toLowerCase() === prAuthor.toLowerCase()) continue;
281
+ const r = reviewers.get(b);
282
+ reviewers.set(b, { ...(r || { login: b, verdict: 'waiting', at: null, current: false }), budget: true });
283
+ }
284
+ }
285
+ for (const t of allThreads) for (const c of t.comments) {
286
+ if (c.login === prAuthor) continue;
287
+ const r = reviewers.get(c.login);
288
+ if (!r) reviewers.set(c.login, { login: c.login, verdict: 'commented', at: c.at, current: false });
289
+ else if (r.verdict === 'waiting') reviewers.set(c.login, { ...r, verdict: 'commented', at: c.at });
290
+ }
291
+
292
+ const rounds = vs.map((v, i) => {
293
+ const vv = verdicts.filter((x) => x.version === v.digest);
294
+ const isCur = v.digest === plan.digest;
295
+ let outcome = isCur ? policy.state : vv.some((x) => x.action === 'reject') ? 'changes-requested' : vv.some((x) => x.action === 'approve') ? 'approved-then-edited' : 'superseded';
296
+ if (isCur && outcome === 'pending' && pr?.draft) outcome = 'draft';
297
+ const prev = vs[i - 1];
298
+ return { n: i + 1, digest: v.digest, short: v.short, at: v.at, author: v.author, sha: v.sha, current: isCur, verdicts: vv,
299
+ threads: allThreads.filter((t) => t.version === v.digest), estimate: estimatePlan(v.body, config), outcome, body: v.body,
300
+ stats: prev ? diffStats(lineDiff(prev.body, v.body)) : null };
301
+ });
302
+
303
+ const passing = policy.state === 'approved' || policy.state === 'auto-approved';
304
+ const status = passing ? policy.state : policy.state === 'changes-requested' ? 'changes-requested' : (!pr || pr.draft) ? 'draft' : policy.state === 'needs-budget' ? 'needs-budget' : 'in-review';
305
+ const last = timeline.filter((t) => t.at).slice(-1)[0];
306
+ return {
307
+ id: plan.id, title: plan.title, path: planPath, digest: plan.digest, short: plan.short, body: plan.body, meta: plan.meta || {},
308
+ author: prAuthor || plan.meta?.author || null, pr: pr ? { number: pr.number, title: pr.title, url: pr.html_url, draft: !!pr.draft, state: pr.merged_at ? 'merged' : pr.state, branch: pr.head?.ref } : null,
309
+ status, policy, estimate, rounds, round: rounds.length, threads: allThreads, verdicts, timeline, reviewers: [...reviewers.values()],
310
+ openThreads: allThreads.filter((t) => !t.resolved && !t.outdated).length, lastActivity: last ? last.at : null,
311
+ approveLine: `/lake approve ${plan.id}@${plan.short}`,
312
+ suggestions: costSuggestions(estimate, config).filter((x) => !allThreads.some((t) => t.suggestion && !t.resolved && t.version === plan.digest && JSON.stringify(t.suggestion.patch) === JSON.stringify(x.patch))),
313
+ modelOptions: modelOptions(estimate, config),
314
+ budget: policy.budget,
315
+ };
316
+ }
317
+
318
+ export function sectionText(body) { return stripEstimate(String(body)); }
319
+ export { splitFrontmatter };
package/src/sha256.js ADDED
@@ -0,0 +1,37 @@
1
+ // Small synchronous SHA-256 (UTF-8 string in, hex out). Pure JS so the same plan digest code runs
2
+ // in Node, in the browser review UI and in the GitHub Action, with identical results.
3
+ const K = new Uint32Array([
4
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
5
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
6
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
7
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
8
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
9
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]);
10
+
11
+ export function sha256Hex(str) {
12
+ const bytes = new TextEncoder().encode(String(str));
13
+ const len = bytes.length;
14
+ const total = ((len + 9 + 63) >> 6) << 6;
15
+ const buf = new Uint8Array(total);
16
+ buf.set(bytes); buf[len] = 0x80;
17
+ const dv = new DataView(buf.buffer);
18
+ dv.setUint32(total - 8, Math.floor(len / 0x20000000)); dv.setUint32(total - 4, (len << 3) >>> 0);
19
+ const H = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
20
+ const W = new Uint32Array(64);
21
+ const rot = (x, n) => (x >>> n) | (x << (32 - n));
22
+ for (let off = 0; off < total; off += 64) {
23
+ for (let i = 0; i < 16; i++) W[i] = dv.getUint32(off + i * 4);
24
+ for (let i = 16; i < 64; i++) {
25
+ const a = W[i - 15], b = W[i - 2];
26
+ W[i] = (W[i - 16] + (rot(a, 7) ^ rot(a, 18) ^ (a >>> 3)) + W[i - 7] + (rot(b, 17) ^ rot(b, 19) ^ (b >>> 10))) >>> 0;
27
+ }
28
+ let [a, b, c, d, e, f, g, h] = H;
29
+ for (let i = 0; i < 64; i++) {
30
+ const t1 = (h + (rot(e, 6) ^ rot(e, 11) ^ rot(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + W[i]) >>> 0;
31
+ const t2 = ((rot(a, 2) ^ rot(a, 13) ^ rot(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
32
+ h = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;
33
+ }
34
+ H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h;
35
+ }
36
+ return [...H].map((x) => x.toString(16).padStart(8, '0')).join('');
37
+ }
package/src/store.js ADDED
@@ -0,0 +1,90 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { loadConfig } from './config.js';
5
+ import { readPlanText, renderPlanFile, slugify, titleOf, splitFrontmatter } from './plan.js';
6
+ import { estimatePlan, renderEstimate, autoApproveVerdict } from './estimate.js';
7
+
8
+ function git(cwd, args) {
9
+ try { return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return null; }
10
+ }
11
+
12
+ export function repoRoot(cwd = process.cwd()) {
13
+ return git(cwd, ['rev-parse', '--show-toplevel']) || path.resolve(cwd);
14
+ }
15
+
16
+ // Local state lives inside .git so it is never committed and never part of a PR.
17
+ export function stateDir(root) {
18
+ const gd = git(root, ['rev-parse', '--absolute-git-dir']);
19
+ const dir = gd ? path.join(gd, 'lake') : path.join(root, '.lake', '.local');
20
+ fs.mkdirSync(dir, { recursive: true });
21
+ return dir;
22
+ }
23
+
24
+ const readJson = (p, d) => { try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return d; } };
25
+ const writeJson = (p, v) => fs.writeFileSync(p, JSON.stringify(v, null, 2) + '\n');
26
+
27
+ export const plansDir = (root) => path.join(root, '.lake', 'plans');
28
+ export const planPath = (root, id) => path.join(plansDir(root), `${id}.md`);
29
+
30
+ export function getState(root) { return readJson(path.join(stateDir(root), 'state.json'), { active: null, sessions: {} }); }
31
+ export function setState(root, s) { writeJson(path.join(stateDir(root), 'state.json'), s); }
32
+ export function getApprovals(root) { return readJson(path.join(stateDir(root), 'approvals.json'), {}); }
33
+ export function setApprovals(root, a) { writeJson(path.join(stateDir(root), 'approvals.json'), a); }
34
+
35
+ export function listPlans(root) {
36
+ const d = plansDir(root);
37
+ if (!fs.existsSync(d)) return [];
38
+ return fs.readdirSync(d).filter((f) => f.endsWith('.md') && f !== 'README.md').map((f) => loadPlan(root, f.slice(0, -3)));
39
+ }
40
+
41
+ export function loadPlan(root, id) {
42
+ const p = planPath(root, id);
43
+ if (!fs.existsSync(p)) return null;
44
+ return { ...readPlanText(fs.readFileSync(p, 'utf8'), id), path: p };
45
+ }
46
+
47
+ function uniqueId(root, base) {
48
+ let id = base; let n = 2;
49
+ while (fs.existsSync(planPath(root, id))) id = `${base}-${n++}`;
50
+ return id;
51
+ }
52
+
53
+ // Writes (or re-versions) a plan file with a fresh estimate. Returns the loaded plan + estimate.
54
+ export function exportPlan(root, markdown, { id, source, sessionId, author } = {}) {
55
+ const config = loadConfig(root);
56
+ const state = getState(root);
57
+ const incoming = splitFrontmatter(markdown).body;
58
+ let planId = id || (sessionId && state.sessions[sessionId]) || null;
59
+ let created = new Date().toISOString();
60
+ if (planId && fs.existsSync(planPath(root, planId))) {
61
+ const prev = splitFrontmatter(fs.readFileSync(planPath(root, planId), 'utf8')).meta;
62
+ created = prev.created || created;
63
+ author = author || prev.author;
64
+ } else {
65
+ planId = uniqueId(root, planId || slugify(titleOf(incoming)));
66
+ }
67
+ author = author || git(root, ['config', 'user.email']) || undefined;
68
+ const est = estimatePlan(incoming, config);
69
+ fs.mkdirSync(plansDir(root), { recursive: true });
70
+ fs.writeFileSync(planPath(root, planId), renderPlanFile({ id: planId, title: titleOf(incoming), author, source, created, body: incoming, estimateMd: renderEstimate(est, config) }));
71
+ state.active = planId;
72
+ if (sessionId) state.sessions[sessionId] = planId;
73
+ setState(root, state);
74
+ return { plan: loadPlan(root, planId), estimate: est, config };
75
+ }
76
+
77
+ // Local approval status of a plan, based on the last `lake-gate sync` from GitHub and the local auto-approve policy.
78
+ export function localStatus(root, plan, config = loadConfig(root)) {
79
+ const est = estimatePlan(plan.body, config);
80
+ const rec = getApprovals(root)[plan.id];
81
+ if (rec && rec.digest === plan.digest && (rec.state === 'approved' || rec.state === 'auto-approved')) return { state: rec.state, approvers: rec.approvers || [], estimate: est, synced: rec, trial: !!rec.trial };
82
+ if (rec && rec.digest === plan.digest && rec.state === 'changes-requested') return { state: 'changes-requested', approvers: [], blockers: rec.blockers, estimate: est, synced: rec };
83
+ const a = config.autoApprove || {};
84
+ if (a.mode === 'on') {
85
+ const v = autoApproveVerdict(est, config);
86
+ if (v.eligible) return { state: 'auto-approved', approvers: [], estimate: est };
87
+ }
88
+ const stale = rec && rec.digest !== plan.digest && (rec.state === 'approved' || rec.state === 'auto-approved');
89
+ return { state: 'pending', stale, approvers: [], estimate: est };
90
+ }
package/src/sync.js ADDED
@@ -0,0 +1,50 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { loadConfig } from './config.js';
3
+ import { listPlans, getApprovals, setApprovals } from './store.js';
4
+ import { estimatePlan } from './estimate.js';
5
+ import { evaluatePlan } from './policy.js';
6
+ import { client, collectEvents, nativeDigests } from './github.js';
7
+ import { expandEvents } from './review.js';
8
+
9
+ const sh = (cmd, args, cwd) => { try { return execFileSync(cmd, args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return null; } };
10
+
11
+ export function parseRemote(url) {
12
+ const m = String(url || '').match(/github\.com[:/]([^/]+)\/([^/]+?)(\.git)?$/);
13
+ return m ? `${m[1]}/${m[2]}` : null;
14
+ }
15
+
16
+ // Applies GitHub approvals to the LOCAL plan files. An approval only counts if its digest matches the local file,
17
+ // so a plan edited locally after approval is pending again.
18
+ export function applyEvents(root, { events, prAuthor, prNumber, digestAt = {} }) {
19
+ const config = loadConfig(root);
20
+ const store = getApprovals(root);
21
+ const results = [];
22
+ for (const plan of listPlans(root)) {
23
+ const planEvents = expandEvents(events.map((e, i) => ({ ...e, id: e.id ?? i })), { planId: plan.id, digestAt: digestAt[plan.id] || {}, config });
24
+ const r = evaluatePlan({ plan, estimate: estimatePlan(plan.body, config), events: planEvents, prAuthor, config });
25
+ store[plan.id] = { digest: plan.digest, state: r.state, approvers: r.approvers, blockers: r.blockers, pr: prNumber ?? null, syncedAt: new Date().toISOString() };
26
+ results.push(r);
27
+ }
28
+ setApprovals(root, store);
29
+ return results;
30
+ }
31
+
32
+ export async function syncFromGitHub(root, { pr, token, fetchImpl } = {}) {
33
+ const repo = parseRemote(sh('git', ['remote', 'get-url', 'origin'], root));
34
+ if (!repo) throw new Error('No GitHub remote named origin.');
35
+ token = token || process.env.GITHUB_TOKEN || process.env.GH_TOKEN || sh('gh', ['auth', 'token'], root);
36
+ if (!token) throw new Error('Need GitHub read access: set GITHUB_TOKEN or run `gh auth login`.');
37
+ const gh = client({ token, repo, fetchImpl });
38
+ let number = pr;
39
+ if (!number) {
40
+ const branch = sh('git', ['rev-parse', '--abbrev-ref', 'HEAD'], root);
41
+ const prs = await gh.req('GET', `/pulls?state=open&head=${encodeURIComponent(`${gh.owner}:${branch}`)}`);
42
+ if (!prs || !prs.length) throw new Error(`No open PR for branch ${branch}. Push and open one, then run sync again.`);
43
+ number = prs[0].number;
44
+ }
45
+ const prObj = await gh.req('GET', `/pulls/${number}`);
46
+ const events = await collectEvents(gh, number);
47
+ const config = loadConfig(root); const digestAt = {};
48
+ for (const plan of listPlans(root)) digestAt[plan.id] = await nativeDigests(gh, events, `.lake/plans/${plan.id}.md`, { headSha: prObj.head.sha, config });
49
+ return { pr: number, results: applyEvents(root, { events, prAuthor: prObj.user.login, prNumber: number, digestAt }) };
50
+ }
@@ -0,0 +1,81 @@
1
+ // `lake-gate ui`: serves the Lake review UI on localhost for the current repo.
2
+ // - Static UI from ../ui and the browser-safe core modules from ./ (same code the CLI and Action use).
3
+ // - /gh/* is a narrow proxy to api.github.com for THIS repo only, using the token already on this machine
4
+ // (GITHUB_TOKEN, GH_TOKEN or `gh auth token`). The browser never sees the token.
5
+ // - /api/local lists plan files in the working tree with their git history (drafts that aren't on a PR yet).
6
+ // Every API call needs a per-run random key that is only embedded in the served page (blocks other sites).
7
+ import http from 'node:http';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import crypto from 'node:crypto';
11
+ import { execFileSync } from 'node:child_process';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { parseRemote } from './sync.js';
14
+ import { plansDir } from './store.js';
15
+
16
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
17
+ const UI_DIR = path.join(HERE, '..', 'ui');
18
+ export const CORE_FILES = ['plan.js', 'sha256.js', 'estimate.js', 'policy.js', 'config-core.js', 'review.js', 'workspace.js', 'github.js', 'models.js', 'meter-core.js'];
19
+ const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.png': 'image/png', '.json': 'application/json' };
20
+ const sh = (cmd, args, cwd) => { try { return execFileSync(cmd, args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 32 * 1024 * 1024 }); } catch { return null; } };
21
+
22
+ export function localPlans(root) {
23
+ const dir = plansDir(root);
24
+ const files = fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.endsWith('.md') && f !== 'README.md') : [];
25
+ const plans = files.map((f) => {
26
+ const rel = `.lake/plans/${f}`;
27
+ const log = (sh('git', ['log', '--format=%H%x09%aI%x09%an', '--', rel], root) || '').trim().split('\n').filter(Boolean).reverse().slice(-30);
28
+ const snapshots = log.map((l) => { const [sha, at, author] = l.split('\t'); return { sha, at, author, text: sh('git', ['show', `${sha}:${rel}`], root) }; }).filter((s) => s.text != null);
29
+ const work = fs.readFileSync(path.join(dir, f), 'utf8');
30
+ snapshots.push({ sha: null, at: fs.statSync(path.join(dir, f)).mtime.toISOString(), author: (sh('git', ['config', 'user.name'], root) || '').trim() || null, text: work });
31
+ return { id: f.slice(0, -3), snapshots };
32
+ });
33
+ const cfg = path.join(root, '.lake', 'config.json');
34
+ return { branch: (sh('git', ['rev-parse', '--abbrev-ref', 'HEAD'], root) || '').trim(), config: fs.existsSync(cfg) ? fs.readFileSync(cfg, 'utf8') : null, plans };
35
+ }
36
+
37
+ export function createUiServer({ root, token, api = 'https://api.github.com', fetchImpl = globalThis.fetch, key = crypto.randomBytes(16).toString('hex') } = {}) {
38
+ const repo = parseRemote((sh('git', ['remote', 'get-url', 'origin'], root) || '').trim());
39
+ const index = fs.readFileSync(path.join(UI_DIR, 'index.html'), 'utf8').replace('<!--LAKE_KEY-->', `<meta name="lake-key" content="${key}">`);
40
+ const send = (res, code, body, type = 'application/json') => { res.writeHead(code, { 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' }); res.end(body); };
41
+ const json = (res, code, v) => send(res, code, JSON.stringify(v));
42
+
43
+ const server = http.createServer(async (req, res) => {
44
+ try {
45
+ const url = new URL(req.url, 'http://localhost');
46
+ const p = decodeURIComponent(url.pathname);
47
+ const isApi = p.startsWith('/api/') || p.startsWith('/gh/');
48
+ if (isApi && req.headers['x-lake-key'] !== key) return json(res, 403, { message: 'Missing or wrong UI key' });
49
+ if (p === '/api/env') return json(res, 200, { mode: 'local', repo, root: path.basename(root), hasToken: !!token });
50
+ if (p === '/api/local') return json(res, 200, localPlans(root));
51
+ if (p.startsWith('/gh/')) {
52
+ // Only this repo's endpoints (and /user), only the methods the UI needs.
53
+ const target = p.slice(3);
54
+ const allowed = target === '/user' || (repo && target.startsWith(`/repos/${repo}/`));
55
+ if (!allowed || !['GET', 'POST', 'PATCH'].includes(req.method)) return json(res, 403, { message: 'Not allowed through the local proxy' });
56
+ if (req.method !== 'GET' && !/^\/repos\/[^/]+\/[^/]+\/(issues\/\d+\/comments|pulls\/\d+\/comments\/\d+\/replies)$/.test(target)) return json(res, 403, { message: 'Only posting comments is allowed' });
57
+ if (!token) return json(res, 401, { message: 'No GitHub token: set GITHUB_TOKEN or run `gh auth login`, then restart lake-gate ui.' });
58
+ let body; if (req.method !== 'GET') { const chunks = []; for await (const c of req) chunks.push(c); body = Buffer.concat(chunks).toString('utf8'); }
59
+ const r = await fetchImpl(`${api}${target}${url.search}`, { method: req.method, headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'lake-gate-ui', Authorization: `Bearer ${token}`, ...(body ? { 'Content-Type': 'application/json' } : {}) }, body });
60
+ return send(res, r.status, await r.text(), 'application/json');
61
+ }
62
+ if (req.method !== 'GET') return json(res, 405, { message: 'Method not allowed' });
63
+ if (p === '/' || p === '/index.html') return send(res, 200, index, TYPES['.html']);
64
+ let file;
65
+ if (p.startsWith('/core/')) { const name = p.slice(6); if (!CORE_FILES.includes(name)) return send(res, 404, 'Not found', 'text/plain'); file = path.join(HERE, name); }
66
+ else { file = path.join(UI_DIR, path.normalize(p).replace(/^([/\\])+/, '')); if (!file.startsWith(UI_DIR + path.sep)) return send(res, 404, 'Not found', 'text/plain'); }
67
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return send(res, 404, 'Not found', 'text/plain');
68
+ return send(res, 200, fs.readFileSync(file), TYPES[path.extname(file)] || 'application/octet-stream');
69
+ } catch (e) { return json(res, 500, { message: e.message }); }
70
+ });
71
+ return { server, key, repo };
72
+ }
73
+
74
+ export async function startUi({ root, port = 4848, host = '127.0.0.1', open = true, token } = {}) {
75
+ token = token || process.env.GITHUB_TOKEN || process.env.GH_TOKEN || (sh('gh', ['auth', 'token'], root) || '').trim() || null;
76
+ const { server, repo } = createUiServer({ root, token });
77
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
78
+ const url = `http://${host}:${server.address().port}/#/local`;
79
+ if (open) { const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open'; try { execFileSync(cmd, [url], { stdio: 'ignore' }); } catch { /* print only */ } }
80
+ return { server, url, repo, hasToken: !!token };
81
+ }