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.
package/src/sync.js CHANGED
@@ -3,7 +3,8 @@ import { loadConfig } from './config.js';
3
3
  import { listPlans, getApprovals, setApprovals } from './store.js';
4
4
  import { estimatePlan } from './estimate.js';
5
5
  import { evaluatePlan } from './policy.js';
6
- import { client, collectEvents } from './github.js';
6
+ import { client, collectEvents, nativeDigests } from './github.js';
7
+ import { expandEvents } from './review.js';
7
8
 
8
9
  const sh = (cmd, args, cwd) => { try { return execFileSync(cmd, args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return null; } };
9
10
 
@@ -14,12 +15,13 @@ export function parseRemote(url) {
14
15
 
15
16
  // Applies GitHub approvals to the LOCAL plan files. An approval only counts if its digest matches the local file,
16
17
  // so a plan edited locally after approval is pending again.
17
- export function applyEvents(root, { events, prAuthor, prNumber }) {
18
+ export function applyEvents(root, { events, prAuthor, prNumber, digestAt = {} }) {
18
19
  const config = loadConfig(root);
19
20
  const store = getApprovals(root);
20
21
  const results = [];
21
22
  for (const plan of listPlans(root)) {
22
- const r = evaluatePlan({ plan, estimate: estimatePlan(plan.body, config), events, prAuthor, config });
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 });
23
25
  store[plan.id] = { digest: plan.digest, state: r.state, approvers: r.approvers, blockers: r.blockers, pr: prNumber ?? null, syncedAt: new Date().toISOString() };
24
26
  results.push(r);
25
27
  }
@@ -42,5 +44,7 @@ export async function syncFromGitHub(root, { pr, token, fetchImpl } = {}) {
42
44
  }
43
45
  const prObj = await gh.req('GET', `/pulls/${number}`);
44
46
  const events = await collectEvents(gh, number);
45
- return { pr: number, results: applyEvents(root, { events, prAuthor: prObj.user.login, prNumber: 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 }) };
46
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
+ }
@@ -0,0 +1,104 @@
1
+ // Reads review state for plans from GitHub PRs and writes review actions back as PR comments.
2
+ // Browser-safe: used by the Lake review UI (directly or through `lake-gate ui`'s local proxy) and by the MCP server.
3
+ import { parseConfig } from './config-core.js';
4
+ import { resolveBudgetApprovers } from './github.js';
5
+ import { applyPatch } from './models.js';
6
+ import { splitFrontmatter, renderPlanFile, readPlanText } from './plan.js';
7
+ import { estimatePlan, renderEstimate } from './estimate.js';
8
+ import { buildPlanReview, versionsFromSnapshots, normalizeIssueComment, normalizeReview, normalizeLineComment,
9
+ commentBody, replyBody, resolveBody, verdictBody, suggestionBody, acceptBody } from './review.js';
10
+
11
+ export const isPlanFile = (f) => /^\.lake\/plans\/[^/]+\.md$/.test(f) && !f.endsWith('/README.md');
12
+ const MAX_COMMITS = 60;
13
+
14
+ export async function loadPr(gh, number, { pr: prIn } = {}) {
15
+ const pr = prIn && prIn.base ? prIn : await gh.req('GET', `/pulls/${number}`);
16
+ const [cfgText, files, commitsAll, comments, reviews, lines] = await Promise.all([
17
+ gh.file('.lake/config.json', pr.base.sha), gh.all(`/pulls/${number}/files`), gh.all(`/pulls/${number}/commits`),
18
+ gh.all(`/issues/${number}/comments`), gh.all(`/pulls/${number}/reviews`), gh.all(`/pulls/${number}/comments`)]);
19
+ const config = parseConfig(cfgText);
20
+ const commits = commitsAll.slice(-MAX_COMMITS);
21
+ const events = [...comments.map(normalizeIssueComment), ...reviews.filter((r) => r.state !== 'DISMISSED' && r.state !== 'PENDING').map(normalizeReview), ...lines.map(normalizeLineComment)];
22
+ const requestedReviewers = (pr.requested_reviewers || []).map((u) => u.login);
23
+ const budgetApprovers = await resolveBudgetApprovers(gh, config);
24
+ const plans = [];
25
+ for (const f of files.filter((x) => isPlanFile(x.filename) && x.status !== 'removed')) {
26
+ const path = f.filename; const fallbackId = path.split('/').pop().slice(0, -3);
27
+ // Which PR commits touched this file? One call, then one content read per touching commit.
28
+ const touching = new Set(((await gh.req('GET', `/commits?sha=${encodeURIComponent(pr.head.sha)}&path=${encodeURIComponent(path)}&per_page=100`)) || []).map((c) => c.sha));
29
+ const snaps = []; const digestAt = {}; let lastText = null;
30
+ for (const c of commits) {
31
+ if (touching.has(c.sha) || lastText === null) {
32
+ const text = await gh.file(path, c.sha);
33
+ if (text != null) { lastText = text; snaps.push({ text, sha: c.sha, at: c.commit?.committer?.date || c.commit?.author?.date || null, author: c.author?.login || c.commit?.author?.name || null }); }
34
+ }
35
+ if (lastText != null) digestAt[c.sha] = versionsFromSnapshots([{ text: lastText }], fallbackId)[0].digest;
36
+ }
37
+ const headText = await gh.file(path, pr.head.sha);
38
+ if (headText == null) continue;
39
+ snaps.push({ text: headText, sha: pr.head.sha, at: commits.at(-1)?.commit?.committer?.date || pr.updated_at, author: pr.user.login });
40
+ const versions = versionsFromSnapshots(snaps, fallbackId);
41
+ const plan = versions.find((v) => v.digest === versionsFromSnapshots([{ text: headText }], fallbackId)[0].digest);
42
+ digestAt[pr.head.sha] = plan.digest;
43
+ plans.push(buildPlanReview({ plan, versions, events, prAuthor: pr.user.login, config, digestAt, pr, requestedReviewers, budgetApprovers }));
44
+ }
45
+ return { pr, config, plans, events };
46
+ }
47
+
48
+ // All plans in recent PRs of a repo (open first). One page of PRs keeps API use predictable.
49
+ export async function loadWorkspace(gh, { state = 'all', limit = 20 } = {}) {
50
+ const prs = ((await gh.req('GET', `/pulls?state=${state}&sort=updated&direction=desc&per_page=${limit}`)) || []);
51
+ const out = [];
52
+ for (const pr of prs) {
53
+ const files = await gh.all(`/pulls/${pr.number}/files`);
54
+ if (!files.some((f) => isPlanFile(f.filename) && f.status !== 'removed')) continue;
55
+ const r = await loadPr(gh, pr.number);
56
+ out.push(...r.plans);
57
+ }
58
+ return { repo: gh.repo, plans: out };
59
+ }
60
+
61
+ // ---- Writes: everything is a PR comment (or a reply on a native line comment) ----
62
+ async function postIssueComment(gh, number, body) {
63
+ const c = await gh.req('POST', `/issues/${number}/comments`, { body });
64
+ return normalizeIssueComment(c);
65
+ }
66
+
67
+ export const actions = {
68
+ comment: (gh, number, o) => postIssueComment(gh, number, commentBody(o)),
69
+ reply: async (gh, number, o) => {
70
+ if (String(o.thread).startsWith('l')) { // native GitHub line comment thread: reply natively
71
+ const c = await gh.req('POST', `/pulls/${number}/comments/${String(o.thread).slice(1)}/replies`, { body: o.text });
72
+ return normalizeLineComment({ ...c, in_reply_to_id: c.in_reply_to_id || Number(String(o.thread).slice(1)) });
73
+ }
74
+ return postIssueComment(gh, number, replyBody(o));
75
+ },
76
+ resolve: (gh, number, o) => postIssueComment(gh, number, resolveBody(o)),
77
+ verdict: (gh, number, o) => postIssueComment(gh, number, verdictBody(o)),
78
+ suggest: (gh, number, o) => postIssueComment(gh, number, suggestionBody(o)),
79
+ // Author accepts a suggestion: commit the patched plan file to the PR branch, then mark the thread accepted.
80
+ accept: async (gh, number, o) => {
81
+ const pr = await gh.req('GET', `/pulls/${number}`);
82
+ const path = `.lake/plans/${o.planId}.md`;
83
+ const cur = await gh.req('GET', `/contents/${path.split('/').map(encodeURIComponent).join('/')}?ref=${encodeURIComponent(pr.head.ref)}`);
84
+ if (!cur) throw new Error(`${path} not found on ${pr.head.ref}`);
85
+ const config = parseConfig(await gh.file('.lake/config.json', pr.base.sha));
86
+ const text = patchPlanFile(fromB64(cur.content), o.patch, config);
87
+ await gh.req('PUT', `/contents/${path.split('/').map(encodeURIComponent).join('/')}`, { message: `Plan ${o.planId}: ${o.title || 'apply suggestion'}`, content: toB64(text), sha: cur.sha, branch: pr.head.ref });
88
+ const nv = readPlanText(text).digest;
89
+ return postIssueComment(gh, number, acceptBody({ ...o, newVersion: nv }));
90
+ },
91
+ };
92
+
93
+ // The whole plan file with a suggestion applied and its estimate block regenerated.
94
+ export function patchPlanFile(fileText, patch, config) {
95
+ const { meta, body } = splitFrontmatter(fileText);
96
+ const next = applyPatch(body.replace(/<!-- lake:estimate:start[\s\S]*?<!-- lake:estimate:end -->\n?/, '').replace(/\s+$/, '') + '\n', patch);
97
+ return renderPlanFile({ id: meta.id, title: meta.title || readPlanText(fileText).title, author: meta.author, source: meta.source, created: meta.created, body: next, estimateMd: renderEstimate(estimatePlan(next, config), config) });
98
+ }
99
+ const fromB64 = (b) => new TextDecoder().decode(Uint8Array.from(atob(String(b).replace(/\s/g, '')), (c) => c.charCodeAt(0)));
100
+ const toB64 = (t) => { const u = new TextEncoder().encode(t); let s = ''; for (const x of u) s += String.fromCharCode(x); return btoa(s); };
101
+
102
+ export async function viewer(gh) {
103
+ try { return await gh.req('GET', '~/user'); } catch { return null; }
104
+ }
@@ -11,7 +11,7 @@ on:
11
11
  types: [created, edited, deleted]
12
12
  permissions:
13
13
  contents: read
14
- pull-requests: read
14
+ pull-requests: write # to post and update the summary comment
15
15
  issues: write
16
16
  statuses: write
17
17
  concurrency: