lake-gate 0.1.0 → 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/README.md +63 -21
- package/package.json +42 -10
- package/src/action.js +47 -1
- package/src/cli.js +33 -5
- package/src/config-core.js +38 -0
- package/src/config.js +2 -44
- package/src/estimate.js +33 -45
- package/src/github.js +73 -13
- package/src/hook.js +12 -4
- package/src/index.js +1 -0
- package/src/init.js +23 -3
- package/src/mcp.js +312 -0
- package/src/meter-core.js +535 -0
- package/src/models.js +193 -0
- package/src/plan.js +2 -2
- package/src/policy.js +12 -4
- package/src/review.js +319 -0
- package/src/sha256.js +37 -0
- package/src/store.js +1 -1
- package/src/sync.js +8 -4
- package/src/ui-server.js +81 -0
- package/src/workspace.js +104 -0
- package/ui/app.css +536 -0
- package/ui/app.js +836 -0
- package/ui/btn/approve.svg +5 -0
- package/ui/btn/changes.svg +5 -0
- package/ui/btn/open.svg +5 -0
- package/ui/data.js +95 -0
- package/ui/demo.js +262 -0
- package/ui/index.html +55 -0
- package/ui/inter.woff2 +0 -0
- package/ui/logo-mark.svg +1 -0
- package/ui/md.js +82 -0
package/src/github.js
CHANGED
|
@@ -1,17 +1,26 @@
|
|
|
1
|
-
import { parseConfig } from './config.js';
|
|
1
|
+
import { parseConfig } from './config-core.js';
|
|
2
2
|
import { readPlanText } from './plan.js';
|
|
3
|
-
import { estimatePlan, range } from './estimate.js';
|
|
4
|
-
import { evaluatePlan, isPassing } from './policy.js';
|
|
3
|
+
import { estimatePlan, range, money } from './estimate.js';
|
|
4
|
+
import { evaluatePlan, isPassing, parseCommands } from './policy.js';
|
|
5
|
+
import { expandEvents } from './review.js';
|
|
6
|
+
import { costSuggestions } from './models.js';
|
|
5
7
|
|
|
6
8
|
export const STATUS_CONTEXT = 'lake/plan-approval';
|
|
7
9
|
export const MARKER = '<!-- lake-gate:summary -->';
|
|
8
10
|
|
|
11
|
+
// Works in Node and in the browser review UI.
|
|
12
|
+
export function fromBase64(b64) {
|
|
13
|
+
const bin = atob(String(b64).replace(/\s/g, ''));
|
|
14
|
+
return new TextDecoder().decode(Uint8Array.from(bin, (ch) => ch.charCodeAt(0)));
|
|
15
|
+
}
|
|
16
|
+
|
|
9
17
|
export function client({ token, repo, api = 'https://api.github.com', fetchImpl = globalThis.fetch }) {
|
|
10
18
|
const [owner, name] = repo.split('/');
|
|
11
19
|
async function req(method, url, body) {
|
|
12
|
-
const
|
|
20
|
+
const full = url.startsWith('http') ? url : url.startsWith('~/') ? `${api}${url.slice(1)}` : `${api}/repos/${owner}/${name}${url}`;
|
|
21
|
+
const res = await fetchImpl(full, {
|
|
13
22
|
method,
|
|
14
|
-
headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'lake-gate', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
|
23
|
+
headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', ...(typeof window === 'undefined' ? { 'User-Agent': 'lake-gate' } : {}), ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
|
15
24
|
body: body ? JSON.stringify(body) : undefined,
|
|
16
25
|
});
|
|
17
26
|
if (res.status === 404 && method === 'GET') return null;
|
|
@@ -30,19 +39,45 @@ export function client({ token, repo, api = 'https://api.github.com', fetchImpl
|
|
|
30
39
|
}
|
|
31
40
|
async function file(p, ref) {
|
|
32
41
|
const r = await req('GET', `/contents/${p.split('/').map(encodeURIComponent).join('/')}?ref=${encodeURIComponent(ref)}`);
|
|
33
|
-
return r && r.content ?
|
|
42
|
+
return r && r.content ? fromBase64(r.content) : null;
|
|
34
43
|
}
|
|
35
|
-
return { req, all, file, owner, name };
|
|
44
|
+
return { req, all, file, owner, name, repo, api };
|
|
36
45
|
}
|
|
37
46
|
|
|
38
47
|
export async function collectEvents(gh, number) {
|
|
39
48
|
const [comments, reviews] = await Promise.all([gh.all(`/issues/${number}/comments`), gh.all(`/pulls/${number}/reviews`)]);
|
|
40
49
|
return [
|
|
41
50
|
...comments.map((c) => ({ login: c.user.login, type: c.user.type, association: c.author_association, body: c.body, createdAt: c.created_at, source: 'comment', id: c.id })),
|
|
42
|
-
...reviews.filter((r) => r.state !== 'DISMISSED').map((r) => ({ login: r.user.login, type: r.user.type, association: r.author_association, body: r.body, createdAt: r.submitted_at, source: 'review', id: r.id })),
|
|
51
|
+
...reviews.filter((r) => r.state !== 'DISMISSED').map((r) => ({ login: r.user.login, type: r.user.type, association: r.author_association, body: r.body, createdAt: r.submitted_at, source: 'review', id: r.id, state: r.state, commitId: r.commit_id })),
|
|
43
52
|
];
|
|
44
53
|
}
|
|
45
54
|
|
|
55
|
+
const NATIVE_STATES = new Set(['APPROVED', 'CHANGES_REQUESTED']);
|
|
56
|
+
// For native GitHub reviews (no /lake line): the plan digest at each reviewed commit.
|
|
57
|
+
export async function nativeDigests(gh, events, path, { headSha, headText, config }) {
|
|
58
|
+
const out = {};
|
|
59
|
+
if (config.nativeReviews === false) return out;
|
|
60
|
+
for (const ev of events) {
|
|
61
|
+
if (ev.source !== 'review' || !NATIVE_STATES.has(ev.state) || !ev.commitId || ev.commitId in out || parseCommands(ev.body).length) continue;
|
|
62
|
+
const t = ev.commitId === headSha && headText != null ? headText : await gh.file(path, ev.commitId);
|
|
63
|
+
out[ev.commitId] = t == null ? null : readPlanText(t).digest;
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Budget approvers: logins as listed, "@org/team" expanded through the API when the token may read the team
|
|
69
|
+
// (an Actions GITHUB_TOKEN usually may not; list logins then).
|
|
70
|
+
export async function resolveBudgetApprovers(gh, config) {
|
|
71
|
+
const b = config.budget || {};
|
|
72
|
+
if (b.approverAbove == null || !(b.approvers || []).length) return undefined;
|
|
73
|
+
const out = b.approvers.filter((x) => !String(x).includes('/')).map((x) => String(x).replace(/^@/, ''));
|
|
74
|
+
for (const t of b.approvers.filter((x) => String(x).includes('/'))) {
|
|
75
|
+
const [org, slug] = String(t).replace(/^@/, '').split('/');
|
|
76
|
+
try { out.push(...(await gh.all(`~/orgs/${org}/teams/${slug}/members`)).map((u) => u.login)); } catch { /* no access to the team */ }
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
46
81
|
const isPlanPath = (f) => /^\.lake\/plans\/[^/]+\.md$/.test(f) && !f.endsWith('/README.md');
|
|
47
82
|
const isCodePath = (f) => !f.startsWith('.lake/') && !/\.(md|txt)$/i.test(f) && !f.startsWith('docs/');
|
|
48
83
|
|
|
@@ -54,15 +89,18 @@ export async function evaluatePr(gh, number) {
|
|
|
54
89
|
const planFiles = files.filter((f) => isPlanPath(f.filename) && f.status !== 'removed').map((f) => f.filename);
|
|
55
90
|
const codeChanged = files.some((f) => isCodePath(f.filename));
|
|
56
91
|
const events = await collectEvents(gh, number);
|
|
92
|
+
const budgetApprovers = await resolveBudgetApprovers(gh, config);
|
|
57
93
|
const results = [];
|
|
58
94
|
for (const p of planFiles) {
|
|
59
95
|
const text = await gh.file(p, pr.head.sha);
|
|
60
96
|
if (text == null) continue;
|
|
61
97
|
const plan = readPlanText(text, p.split('/').pop().slice(0, -3));
|
|
62
98
|
const estimate = estimatePlan(plan.body, config);
|
|
63
|
-
|
|
99
|
+
const digestAt = await nativeDigests(gh, events, p, { headSha: pr.head.sha, headText: text, config });
|
|
100
|
+
const planEvents = expandEvents(events.map((e) => ({ ...e, id: `${e.source}${e.id}` })), { planId: plan.id, digestAt, config });
|
|
101
|
+
results.push({ ...evaluatePlan({ plan, estimate, events: planEvents, prAuthor: pr.user.login, config, budgetApprovers }), title: plan.title, path: p, estimate });
|
|
64
102
|
}
|
|
65
|
-
return { pr, config, results, codeChanged, ...summarize(results, codeChanged, config) };
|
|
103
|
+
return { pr, config, results, codeChanged, repo: gh.repo, ...summarize(results, codeChanged, config) };
|
|
66
104
|
}
|
|
67
105
|
|
|
68
106
|
export function summarize(results, codeChanged, config) {
|
|
@@ -75,6 +113,7 @@ export function summarize(results, codeChanged, config) {
|
|
|
75
113
|
const bad = results.filter((r) => !isPassing(r));
|
|
76
114
|
if (!bad.length) return { state: 'success', description: `${results.length} plan(s) approved for their current version` };
|
|
77
115
|
const r = bad[0];
|
|
116
|
+
if (r.state === 'needs-budget') return { state: 'failure', description: `Needs budget approval for ${r.id} (up to ${money(r.budget.exposure)} > ${money(r.budget.threshold)})`.slice(0, 140) };
|
|
78
117
|
return { state: 'failure', description: r.state === 'changes-requested' ? `Changes requested on ${r.id}` : `Waiting for approval: /lake approve ${r.id}@${r.short}`.slice(0, 140) };
|
|
79
118
|
}
|
|
80
119
|
|
|
@@ -85,12 +124,33 @@ export function renderSummary(ev) {
|
|
|
85
124
|
for (const r of ev.results) {
|
|
86
125
|
const status = r.state === 'approved' ? `approved by ${r.approvers.map((a) => '@' + a).join(', ')}` :
|
|
87
126
|
r.state === 'auto-approved' ? 'auto-approved by policy' :
|
|
88
|
-
r.state === 'changes-requested' ? `changes requested by ${r.blockers.map((a) => '@' + a).join(', ')}` :
|
|
89
|
-
|
|
127
|
+
r.state === 'changes-requested' ? `changes requested by ${r.blockers.map((a) => '@' + a).join(', ')}` :
|
|
128
|
+
r.state === 'needs-budget' ? `approved by ${r.approvers.map((a) => '@' + a).join(', ')}, **needs budget approval**` : `needs ${r.needed} approval(s)${r.budget?.required ? ' + budget approval' : ''}`;
|
|
129
|
+
const est = r.estimate;
|
|
130
|
+
const cost = `${range(est.declared ? est.plannedUsd : est.usd)}${est.model ? ` on ${est.model.name}` : ''}${est.cap != null ? ` (cap ${money(est.cap)})` : ''}`;
|
|
131
|
+
lines.push(`| [${r.title.replace(/\|/g, '/')}](${r.path}) | \`${r.short}\` | ${status} | ${est.complexity} | ${cost} |`);
|
|
132
|
+
}
|
|
133
|
+
for (const r of ev.results.filter((x) => x.budget?.required)) {
|
|
134
|
+
lines.push('', `**Budget approval** for \`${r.id}\`: up to ${money(r.budget.exposure)} is above the team threshold of ${money(r.budget.threshold)}. ${r.budget.satisfied ? `Approved by @${r.budget.approvedBy.join(', @')} for v${r.short}.` : `One of ${r.budget.approvers.map((a) => '@' + a).join(', ') || r.budget.teams.join(', ')} must approve v${r.short} too.`}`);
|
|
135
|
+
}
|
|
136
|
+
for (const r of ev.results) {
|
|
137
|
+
const sugg = costSuggestions(r.estimate, ev.config || {});
|
|
138
|
+
if (sugg.length && !isPassing(r)) lines.push('', `<details><summary>Lake can cut \`${r.id}\` by up to ${money(Math.max(...sugg.map((x) => x.saving[1])))}</summary>`, '', ...sugg.map((x) => `- ${x.title} (saves up to ${money(x.saving[1])})`), '', 'Apply in one click on the Lake review page, or ask your agent (lake_submit_revision).', '', '</details>');
|
|
139
|
+
for (const n of r.estimate.modelNotes || []) lines.push('', `Note on \`${r.id}\`: ${n}`);
|
|
90
140
|
}
|
|
91
141
|
const pending = ev.results.filter((r) => !isPassing(r));
|
|
92
142
|
if (pending.length) {
|
|
93
|
-
|
|
143
|
+
const base = ev.config?.reviewUrl;
|
|
144
|
+
if (base && ev.repo && ev.pr?.number) {
|
|
145
|
+
const img = (n, alt) => ``;
|
|
146
|
+
lines.push('', '**Review in one click** (opens the Lake review page for this PR, sign in with GitHub to post):', '');
|
|
147
|
+
for (const r of pending) {
|
|
148
|
+
const link = (act) => `${base}#/pr/${ev.repo}/${ev.pr.number}/${encodeURIComponent(r.id)}${act ? `?do=${act}&v=${r.short}` : ''}`;
|
|
149
|
+
lines.push(`${pending.length > 1 ? `\`${r.id}\` ` : ''}[${img('approve', `Approve v${r.short}`)}](${link('approve')}) [${img('changes', 'Request changes')}](${link('changes')}) [${img('open', 'Open plan review')}](${link('')})`, '');
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (ev.config?.nativeReviews !== false) lines.push('Or use GitHub\'s own **Review changes → Approve** on this PR. lake-gate counts it for the plan version at the reviewed commit.', '');
|
|
153
|
+
lines.push('Or comment (one line per plan):', '```', ...pending.map((r) => `/lake approve ${r.id}@${r.short}`), '```',
|
|
94
154
|
'Approval is bound to this exact version. Editing the plan file needs a fresh approval.');
|
|
95
155
|
}
|
|
96
156
|
const shadow = ev.results.filter((r) => r.auto.mode === 'shadow' && r.auto.eligible && !isPassing(r));
|
package/src/hook.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { loadConfig } from './config.js';
|
|
3
|
-
import { repoRoot, stateDir, getState, loadPlan, exportPlan, localStatus } from './store.js';
|
|
3
|
+
import { repoRoot, stateDir, getState, setState, loadPlan, exportPlan, localStatus } from './store.js';
|
|
4
4
|
import { range } from './estimate.js';
|
|
5
5
|
|
|
6
6
|
const FILE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
|
|
@@ -12,7 +12,8 @@ function out(decision, reason, extra = {}) {
|
|
|
12
12
|
hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: decision, permissionDecisionReason: reason } };
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
-
function approveHint(plan) {
|
|
15
|
+
function approveHint(plan, config) {
|
|
16
|
+
if (config?.try) return `Trial mode: the user can run \`npx lake-gate approve\` to approve it locally (does not count on the PR).`;
|
|
16
17
|
return `Commit .lake/plans/${plan.id}.md, push and open a PR. A teammate (not you) comments:\n /lake approve ${plan.id}@${plan.short}\nThen run: npx lake-gate sync`;
|
|
17
18
|
}
|
|
18
19
|
|
|
@@ -46,6 +47,7 @@ export function handleClaudePreToolUse(input, env = process.env) {
|
|
|
46
47
|
const cmd = String(ti.command || '');
|
|
47
48
|
if (/\.git\/lake|lake[\\/]+(state|approvals)\.json/.test(cmd)) return out('deny', 'Lake: local approval state cannot be edited by the agent.');
|
|
48
49
|
if (/lake-gate(@\S+)?\s+use\b/.test(cmd)) return out('deny', 'Lake: switching the active plan is a human action. Ask the user to run `npx lake-gate use <id>`.');
|
|
50
|
+
if (/lake-gate(@\S+)?\s+approve\b/.test(cmd)) return out('deny', 'Lake: approving is a human action. Ask the user to run `npx lake-gate approve` themselves.');
|
|
49
51
|
const ro = config.readOnlyBash.some((r) => new RegExp(r).test(cmd)) && !/[;&|`$()<>]/.test(cmd.replace(/2>&1|\|\s*(head|tail|wc|rg|grep|sort|uniq)\b[^|;&]*/g, ''));
|
|
50
52
|
if (ro) return null;
|
|
51
53
|
}
|
|
@@ -55,11 +57,17 @@ export function handleClaudePreToolUse(input, env = process.env) {
|
|
|
55
57
|
const activeId = (input.session_id && state.sessions[input.session_id]) || state.active;
|
|
56
58
|
const plan = activeId && loadPlan(root, activeId);
|
|
57
59
|
if (!plan) {
|
|
58
|
-
|
|
60
|
+
// Only planned work is gated, so installing lake-gate never blocks a typo fix. Teams that want every
|
|
61
|
+
// change planned set "gateWithoutPlan": true.
|
|
62
|
+
if (config.gateWithoutPlan) return out(decision, 'Lake: no plan for this work yet. Write a short plan first (Claude Code plan mode, then exit plan mode) or export one with `npx lake-gate plan <file.md>`. Implementation is gated until the plan is approved by a teammate.');
|
|
63
|
+
const sid = input.session_id || 'default';
|
|
64
|
+
if ((state.noticed || []).includes(sid)) return null;
|
|
65
|
+
state.noticed = [...(state.noticed || []).slice(-50), sid]; setState(root, state);
|
|
66
|
+
return out(null, null, { systemMessage: 'lake-gate: no plan for this task, so it is not gated. Use plan mode to gate bigger work.' });
|
|
59
67
|
}
|
|
60
68
|
const st = localStatus(root, plan, config);
|
|
61
69
|
if (st.state === 'approved' || st.state === 'auto-approved') return null;
|
|
62
70
|
const why = st.state === 'changes-requested' ? `changes were requested by ${(st.blockers || []).map((b) => '@' + b).join(', ')}` :
|
|
63
71
|
st.stale ? 'the plan was edited after it was approved, so the approval no longer applies' : 'it is not approved yet';
|
|
64
|
-
return out(decision, `Lake: plan "${plan.id}" version ${plan.short} blocks implementation because ${why}. Do not work around this gate; stop and tell the user.\n${approveHint(plan)}`);
|
|
72
|
+
return out(decision, `Lake: plan "${plan.id}" version ${plan.short} blocks implementation because ${why}. Do not work around this gate; stop and tell the user.\n${approveHint(plan, config)}`);
|
|
65
73
|
}
|
package/src/index.js
CHANGED
package/src/init.js
CHANGED
|
@@ -18,7 +18,16 @@ export function mergeClaudeSettings(settings) {
|
|
|
18
18
|
return { settings: s, changed: !already };
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
export
|
|
21
|
+
export const MCP_SERVER = { command: 'npx', args: ['-y', 'lake-gate@0', 'mcp'] };
|
|
22
|
+
export function mergeMcpConfig(cfg) {
|
|
23
|
+
const c = cfg && typeof cfg === 'object' ? structuredClone(cfg) : {};
|
|
24
|
+
c.mcpServers = c.mcpServers || {};
|
|
25
|
+
if (c.mcpServers['lake-gate']) return { config: c, changed: false };
|
|
26
|
+
c.mcpServers['lake-gate'] = MCP_SERVER;
|
|
27
|
+
return { config: c, changed: true };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function init(root, { actionRef = ACTION_REF, force = false, trial = false } = {}) {
|
|
22
31
|
const done = [];
|
|
23
32
|
const write = (rel, content, overwrite = force) => {
|
|
24
33
|
const p = path.join(root, rel);
|
|
@@ -27,8 +36,9 @@ export function init(root, { actionRef = ACTION_REF, force = false } = {}) {
|
|
|
27
36
|
fs.writeFileSync(p, content);
|
|
28
37
|
done.push(`wrote ${rel}`);
|
|
29
38
|
};
|
|
30
|
-
|
|
31
|
-
|
|
39
|
+
// Short config: sensible defaults live in the code; only what a team usually changes is written.
|
|
40
|
+
const d = DEFAULT_CONFIG;
|
|
41
|
+
write('.lake/config.json', JSON.stringify({ requiredApprovals: d.requiredApprovals, autoApprove: d.autoApprove, budget: { approverAbove: null, approvers: [] }, ...(trial ? { try: true } : {}) }, null, 2) + '\n');
|
|
32
42
|
write('.lake/plans/README.md', fs.readFileSync(path.join(TEMPLATES, 'plans-README.md'), 'utf8'));
|
|
33
43
|
write('.github/workflows/lake-gate.yml', fs.readFileSync(path.join(TEMPLATES, 'lake-gate.yml'), 'utf8').replace('__ACTION_REF__', actionRef));
|
|
34
44
|
|
|
@@ -38,5 +48,15 @@ export function init(root, { actionRef = ACTION_REF, force = false } = {}) {
|
|
|
38
48
|
const { settings, changed } = mergeClaudeSettings(current);
|
|
39
49
|
if (changed) { fs.mkdirSync(path.dirname(sp), { recursive: true }); fs.writeFileSync(sp, JSON.stringify(settings, null, 2) + '\n'); done.push('merged .claude/settings.json (PreToolUse hook)'); }
|
|
40
50
|
else done.push('kept .claude/settings.json (hook already present)');
|
|
51
|
+
|
|
52
|
+
// MCP server registration: Claude Code reads .mcp.json, Cursor reads .cursor/mcp.json
|
|
53
|
+
for (const rel of ['.mcp.json', path.join('.cursor', 'mcp.json')]) {
|
|
54
|
+
const p = path.join(root, rel);
|
|
55
|
+
let cur = {};
|
|
56
|
+
if (fs.existsSync(p)) { try { cur = JSON.parse(fs.readFileSync(p, 'utf8')); } catch { done.push(`kept ${rel} (not valid JSON, add lake-gate by hand)`); continue; } }
|
|
57
|
+
const { config, changed: ch } = mergeMcpConfig(cur);
|
|
58
|
+
if (ch) { fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, JSON.stringify(config, null, 2) + '\n'); done.push(`merged ${rel} (lake-gate MCP server)`); }
|
|
59
|
+
else done.push(`kept ${rel} (lake-gate MCP already present)`);
|
|
60
|
+
}
|
|
41
61
|
return done;
|
|
42
62
|
}
|
package/src/mcp.js
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// lake-gate MCP server (stdio). Lets Claude Code, Cursor or any MCP client:
|
|
2
|
+
// author side: request review on a plan, wait for the verdict, read anchored feedback, submit a revision;
|
|
3
|
+
// reviewer side: read a plan with its threads, reply, approve or request changes from the agent chat.
|
|
4
|
+
// Everything is read from and written to the PR (the single source of truth), with the GitHub token
|
|
5
|
+
// already on this machine (GITHUB_TOKEN, GH_TOKEN or `gh auth token`). No Lake server.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { execFileSync } from 'node:child_process';
|
|
9
|
+
import { repoRoot, loadPlan, getState, exportPlan, listPlans } from './store.js';
|
|
10
|
+
import { client } from './github.js';
|
|
11
|
+
import { parseRemote, applyEvents } from './sync.js';
|
|
12
|
+
import { collectEvents, nativeDigests } from './github.js';
|
|
13
|
+
import { loadPr, actions } from './workspace.js';
|
|
14
|
+
import { loadConfig } from './config.js';
|
|
15
|
+
import { range, money, estimatePlan } from './estimate.js';
|
|
16
|
+
import { costSuggestions, modelOptions, applyPatch, resolveModel, describePatch } from './models.js';
|
|
17
|
+
import { stripEstimate } from './plan.js';
|
|
18
|
+
import { acceptBody } from './review.js';
|
|
19
|
+
|
|
20
|
+
const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
21
|
+
const sh = (cmd, args, cwd) => { try { return execFileSync(cmd, args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); } catch { return null; } };
|
|
22
|
+
|
|
23
|
+
const S = (props, required = []) => ({ type: 'object', properties: props, required, additionalProperties: false });
|
|
24
|
+
const str = (d) => ({ type: 'string', description: d });
|
|
25
|
+
|
|
26
|
+
// Four tools, on purpose. Author side: request_review → review_status → submit_revision. Reviewer side: review.
|
|
27
|
+
export const TOOLS = [
|
|
28
|
+
{ name: 'lake_request_review', description: 'Save a plan (markdown) as a versioned lake-gate plan and ask teammates to review it on the PR. Returns the plan id, version, model and cost estimate, and the review link. Use after planning, before implementing. Tip: add a "Model: <name>" line to declare which model runs it.',
|
|
29
|
+
inputSchema: S({ plan_markdown: str('Full plan in markdown. Omit to request review of an existing plan.'), plan_id: str('Plan id (defaults to the active plan, or derived from the title)'),
|
|
30
|
+
reviewers: { type: 'array', items: { type: 'string' }, description: 'GitHub logins to request review from' }, note: str('Short note to reviewers'),
|
|
31
|
+
push: { type: 'boolean', description: 'Commit only the plan file and push the current branch (so the PR shows this version)' } }), annotations: { openWorldHint: true } },
|
|
32
|
+
{ name: 'lake_review_status', description: 'Review state of a plan: status, verdicts with notes, open comment threads anchored to plan lines, reviewer suggestions, budget approval, and the model/cost view with Lake\'s cost-cutting suggestion ids. Works locally before a PR exists. Set wait_seconds to wait for a decision or new feedback. Also syncs approvals so the lake-gate hook opens once approved.',
|
|
33
|
+
inputSchema: S({ plan_id: str('Plan id (defaults to the active plan)'), wait_seconds: { type: 'number', minimum: 0, maximum: 240, description: 'Wait up to this long for a change (polls every 20s)' } }), annotations: { readOnlyHint: true, openWorldHint: true } },
|
|
34
|
+
{ name: 'lake_submit_revision', description: 'As the author, save a new plan version (earlier approvals no longer apply) and tell reviewers. Either pass the full revised plan_markdown, or apply a suggestion in one step: thread_id (a reviewer suggestion), suggestion_id (from lake_review_status) or model (run the whole plan on that model). Can also reply to threads and mark them resolved.',
|
|
35
|
+
inputSchema: S({ plan_markdown: str('Full revised plan in markdown'), plan_id: str('Plan id (defaults to the active plan)'),
|
|
36
|
+
thread_id: str('Accept this reviewer suggestion thread'), suggestion_id: str('Apply this Lake suggestion, e.g. models-2-4, cap-12, drop-5'), model: str('Run the whole plan on this model, e.g. sonnet'),
|
|
37
|
+
addressed_threads: { type: 'array', items: { type: 'string' }, description: 'Thread ids this revision addresses (marked resolved)' },
|
|
38
|
+
note: str('What changed, for reviewers'), push: { type: 'boolean', description: 'Commit only the plan file and push' } }), annotations: { openWorldHint: true } },
|
|
39
|
+
{ name: 'lake_review', description: 'As a reviewer, act on a plan PR: approve, request_changes, comment (optionally on lines), reply (in a thread) or suggest (a structured change the author accepts in one click: suggestion_id or model). approve and request_changes post as the human GitHub account on this machine: ONLY use them when the user explicitly said so in this conversation, and pass the exact version they saw.',
|
|
40
|
+
inputSchema: S({ action: { type: 'string', enum: ['approve', 'request_changes', 'comment', 'reply', 'suggest'] }, plan_id: str('Plan id'), version: str('8-character version (approve / request_changes)'),
|
|
41
|
+
text: str('Comment, reply, or verdict note (required for request_changes)'), line: { type: 'number', description: 'First plan line to anchor a comment' }, end_line: { type: 'number' },
|
|
42
|
+
thread_id: str('Thread to reply in'), suggestion_id: str('Lake suggestion id to propose'), model: str('Propose running the plan on this model') }, ['action']), annotations: { openWorldHint: true } },
|
|
43
|
+
];
|
|
44
|
+
// Older tool names still work (not listed): lake_approve, lake_request_changes, lake_comment, lake_reply, lake_cost, lake_suggest, lake_apply_suggestion.
|
|
45
|
+
const ALIASES = {
|
|
46
|
+
lake_approve: (a) => ['lake_review', { ...a, action: 'approve', text: a.comment }],
|
|
47
|
+
lake_request_changes: (a) => ['lake_review', { ...a, action: 'request_changes', text: a.comment }],
|
|
48
|
+
lake_comment: (a) => ['lake_review', { ...a, action: 'comment' }],
|
|
49
|
+
lake_reply: (a) => ['lake_review', { ...a, action: 'reply' }],
|
|
50
|
+
lake_suggest: (a) => ['lake_review', { ...a, action: 'suggest', text: a.comment }],
|
|
51
|
+
lake_apply_suggestion: (a) => ['lake_submit_revision', a],
|
|
52
|
+
lake_cost: (a) => ['lake_cost', a],
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export function formatCost(est, config, sugg = costSuggestions(est, config), budget) {
|
|
56
|
+
const L = [];
|
|
57
|
+
L.push(`Cost: ${est.declared ? `${range(est.plannedUsd)} with the planned model${est.model ? ` (${est.model.name})` : 's'}` : `${range(est.usd)} with Lake's pick per step (no model declared; add a "Model: <name>" line)`}${est.cap != null ? `, capped at ${money(est.cap)}` : ''}.`);
|
|
58
|
+
L.push('Steps:', ...est.steps.map((s) => ` ${s.n}. ${s.title.slice(0, 70)} · ${s.complexity} · ${s.planned ? s.planned.name + (s.fit === 'risky' ? ' (may be too weak)' : s.fit === 'overkill' ? ' (more than needed)' : '') : 'not set'} · Lake pick ${s.model} · ${range(s.planned ? s.planned.usd : s.usd)}`));
|
|
59
|
+
L.push('Model options (whole plan):', ...modelOptions(est, config).slice(0, 7).map((o) => ` ${o.key}: ${range(o.usd)} · ${o.fit} · ${o.note}`));
|
|
60
|
+
if (sugg.length) L.push('Suggestions:', ...sugg.map((x) => ` [${x.id}] ${x.title}, saves up to ${money(x.saving[1])}`));
|
|
61
|
+
if (budget?.required) L.push(`Budget approval: up to ${money(budget.exposure)} > ${money(budget.threshold)}. ${budget.satisfied ? `Approved by @${budget.approvedBy.join(', @')}.` : `Needs one of ${budget.approvers.map((x) => '@' + x).join(', ')} to approve this version.`}`);
|
|
62
|
+
for (const n of est.modelNotes || []) L.push(`Note: ${n}`);
|
|
63
|
+
return L.join('\n');
|
|
64
|
+
}
|
|
65
|
+
function patchFor(a, est, config) {
|
|
66
|
+
if (a.model) { const m = resolveModel(a.model, config); if (!m) throw new Error(`Unknown model ${a.model}`); return { title: `Run the plan on ${m.name}`, patch: { type: 'planModel', model: m.name }, saving: null }; }
|
|
67
|
+
const s = costSuggestions(est, config).find((x) => x.id === a.suggestion_id);
|
|
68
|
+
if (!s) throw new Error(`No suggestion ${a.suggestion_id}. Current ones: ${costSuggestions(est, config).map((x) => x.id).join(', ') || 'none'}`);
|
|
69
|
+
return s;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Context: repo root + lazily resolved GitHub client and PR. Tests inject gh/prNumber/sleep.
|
|
73
|
+
export function createContext({ root = repoRoot(), gh, prNumber, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), clientName = 'MCP client', token } = {}) {
|
|
74
|
+
const ctx = { root, sleep, clientName };
|
|
75
|
+
ctx.github = () => {
|
|
76
|
+
if (gh) return gh;
|
|
77
|
+
const repo = parseRemote(sh('git', ['remote', 'get-url', 'origin'], root));
|
|
78
|
+
if (!repo) throw new Error('No GitHub remote named origin.');
|
|
79
|
+
const t = token || process.env.GITHUB_TOKEN || process.env.GH_TOKEN || sh('gh', ['auth', 'token'], root);
|
|
80
|
+
if (!t) throw new Error('Need GitHub access: set GITHUB_TOKEN or run `gh auth login`.');
|
|
81
|
+
gh = client({ token: t, repo });
|
|
82
|
+
return gh;
|
|
83
|
+
};
|
|
84
|
+
ctx.pr = async () => {
|
|
85
|
+
if (prNumber) return prNumber;
|
|
86
|
+
const g = ctx.github();
|
|
87
|
+
const branch = sh('git', ['rev-parse', '--abbrev-ref', 'HEAD'], root);
|
|
88
|
+
const prs = await g.req('GET', `/pulls?state=open&head=${encodeURIComponent(`${g.owner}:${branch}`)}`);
|
|
89
|
+
if (!prs || !prs.length) return null;
|
|
90
|
+
prNumber = prs[0].number;
|
|
91
|
+
return prNumber;
|
|
92
|
+
};
|
|
93
|
+
return ctx;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const reviewLink = (cfg, repo, pr, id, act) => (cfg.reviewUrl && repo && pr ? `${cfg.reviewUrl}#/pr/${repo}/${pr}/${encodeURIComponent(id)}${act ? `?do=${act}` : ''}` : null);
|
|
97
|
+
|
|
98
|
+
function resolveId(ctx, id) {
|
|
99
|
+
const pid = id || getState(ctx.root).active;
|
|
100
|
+
if (!pid) throw new Error('No plan id given and no active plan.');
|
|
101
|
+
return pid;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function pushPlan(ctx, id, message) {
|
|
105
|
+
const p = `.lake/plans/${id}.md`;
|
|
106
|
+
sh('git', ['add', p], ctx.root);
|
|
107
|
+
const c = sh('git', ['commit', '-m', message, '--only', p], ctx.root);
|
|
108
|
+
const pushed = sh('git', ['push', '-u', 'origin', 'HEAD'], ctx.root);
|
|
109
|
+
return c !== null && pushed !== null ? `Committed and pushed ${p}.` : `Could not commit/push ${p} automatically; commit and push it yourself.`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function prModel(ctx, id) {
|
|
113
|
+
const number = await ctx.pr();
|
|
114
|
+
if (!number) return { number: null, model: null };
|
|
115
|
+
const r = await loadPr(ctx.github(), number);
|
|
116
|
+
return { number, model: r.plans.find((p) => p.id === id) || null, config: r.config, events: r.events, pr: r.pr };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function formatReview(m, { localDigest, link } = {}) {
|
|
120
|
+
const L = [];
|
|
121
|
+
L.push(`Plan ${m.id} · v${m.short} (round ${m.round}) · status: ${m.status}${m.policy.needed && m.status === 'in-review' ? ` · needs ${m.policy.needed} more approval(s)` : ''}`);
|
|
122
|
+
L.push(`Estimate: ${m.estimate.complexity} complexity, ${range(m.estimate.declared ? m.estimate.plannedUsd : m.estimate.usd)}${m.estimate.model ? ` on ${m.estimate.model.name}` : ''}`);
|
|
123
|
+
if (m.budget?.required) L.push(`Budget approval: ${m.budget.satisfied ? `done by @${m.budget.approvedBy.join(', @')}` : `needed from one of ${m.budget.approvers.map((x) => '@' + x).join(', ')} (up to ${money(m.budget.exposure)} > ${money(m.budget.threshold)})`}`);
|
|
124
|
+
if (m.suggestions?.length) L.push(`Lake suggestions: ${m.suggestions.map((x) => `[${x.id}] ${x.title} (saves up to ${money(x.saving[1])})`).join('; ')}`);
|
|
125
|
+
const sg = m.threads.filter((t) => t.suggestion && !t.resolved);
|
|
126
|
+
if (sg.length) L.push(`Reviewer suggestions (accept with lake_submit_revision thread_id): ${sg.map((t) => `[${t.id}] ${t.suggestion.title} by @${t.suggestion.by}`).join('; ')}`);
|
|
127
|
+
if (localDigest && localDigest !== m.digest) L.push(`Note: your local plan file is a different version (${localDigest.slice(0, 8)}) than the PR (${m.short}). Push it so reviewers see it.`);
|
|
128
|
+
const cur = m.verdicts.filter((v) => v.version === m.digest && v.action !== 'revoke');
|
|
129
|
+
if (cur.length) { L.push('', 'Verdicts on this version:'); for (const v of cur) L.push(`- @${v.login} ${v.action === 'approve' ? 'approved' : 'requested changes'}${v.self ? ' (author, does not count)' : ''} via ${v.via}${v.text ? `: ${v.text.replace(/\n+/g, ' ')}` : ''}`); }
|
|
130
|
+
const prev = m.verdicts.filter((v) => v.version !== m.digest && v.action === 'reject');
|
|
131
|
+
if (prev.length) { L.push('', 'Earlier rounds:'); for (const v of prev) L.push(`- round ${v.n}: @${v.login} requested changes${v.text ? `: ${v.text.replace(/\n+/g, ' ')}` : ''}`); }
|
|
132
|
+
const open = m.threads.filter((t) => !t.resolved);
|
|
133
|
+
if (open.length) {
|
|
134
|
+
L.push('', `Open threads (${open.length}):`);
|
|
135
|
+
for (const t of open) {
|
|
136
|
+
const where = t.anchor ? `${t.anchor.heading ? `"${t.anchor.heading}", ` : ''}line ${t.current ? t.current.start : t.anchor.start}${t.outdated ? ' (outdated: text changed)' : ''}` : 'whole plan';
|
|
137
|
+
L.push(`- [${t.id}] round ${t.n}, ${where}${t.anchor?.quote ? ` on: "${t.anchor.quote.split('\n')[0].slice(0, 120)}"` : ''}`);
|
|
138
|
+
for (const c of t.comments) L.push(` @${c.login}: ${String(c.text).replace(/\n+/g, ' ')}`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const lines = String(m.body).split('\n');
|
|
142
|
+
L.push('', 'Plan text with line numbers (for anchoring comments):', ...lines.slice(0, 400).map((l, i) => `${String(i + 1).padStart(3)}| ${l}`).filter((l) => !/lake:estimate/.test(l)));
|
|
143
|
+
if (link) L.push('', `Review page: ${link}`);
|
|
144
|
+
return L.join('\n');
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export async function callTool(ctx, name, a = {}) {
|
|
148
|
+
if (ALIASES[name]) [name, a] = ALIASES[name](a);
|
|
149
|
+
if (!fs.existsSync(path.join(ctx.root, '.git'))) return `lake-gate: ${ctx.root} is not a git repository. Open your project folder (the repo with .lake/, set up with \`npx lake-gate init\`) in Claude Code or Cursor, then try again.`;
|
|
150
|
+
const via = `${ctx.clientName} (MCP)`;
|
|
151
|
+
if (name === 'lake_review') {
|
|
152
|
+
const act = a.action;
|
|
153
|
+
if (act === 'approve' || act === 'request_changes') return callTool(ctx, act === 'approve' ? '_approve' : '_changes', { ...a, comment: a.text });
|
|
154
|
+
if (act === 'comment') return callTool(ctx, '_comment', a);
|
|
155
|
+
if (act === 'reply') return callTool(ctx, '_reply', a);
|
|
156
|
+
if (act === 'suggest') return callTool(ctx, '_suggest', { ...a, comment: a.text });
|
|
157
|
+
throw new Error('action must be approve, request_changes, comment, reply or suggest');
|
|
158
|
+
}
|
|
159
|
+
if (name === 'lake_submit_revision' && !a.plan_markdown) {
|
|
160
|
+
if (a.thread_id || a.suggestion_id || a.model) return callTool(ctx, '_apply', a);
|
|
161
|
+
throw new Error('Pass plan_markdown, or one of thread_id / suggestion_id / model.');
|
|
162
|
+
}
|
|
163
|
+
switch (name) {
|
|
164
|
+
case 'lake_request_review': {
|
|
165
|
+
let plan; let note = '';
|
|
166
|
+
if (a.plan_markdown) { const r = exportPlan(ctx.root, a.plan_markdown, { id: a.plan_id, source: 'mcp' }); plan = r.plan; }
|
|
167
|
+
else { plan = loadPlan(ctx.root, resolveId(ctx, a.plan_id)); if (!plan) throw new Error(`No plan ${a.plan_id}`); }
|
|
168
|
+
const cfg = loadConfig(ctx.root);
|
|
169
|
+
if (a.push) note += '\n' + pushPlan(ctx, plan.id, `Plan: ${plan.title} (v${plan.short})`);
|
|
170
|
+
const number = await ctx.pr().catch(() => null);
|
|
171
|
+
if (!number) return `Saved .lake/plans/${plan.id}.md as v${plan.short}.${note}\nNo open PR for this branch yet: commit and push the plan, open a (draft) PR, then call lake_request_review again or lake_review_status.`;
|
|
172
|
+
const g = ctx.github();
|
|
173
|
+
if (a.reviewers?.length) await g.req('POST', `/pulls/${number}/requested_reviewers`, { reviewers: a.reviewers }).catch(() => null);
|
|
174
|
+
const link = reviewLink(cfg, g.repo, number, plan.id);
|
|
175
|
+
await g.req('POST', `/issues/${number}/comments`, { body: [`**Plan ready for review:** ${plan.title} · \`${plan.id}\` v${plan.short}`, a.reviewers?.length ? a.reviewers.map((r) => '@' + r).join(' ') : null,
|
|
176
|
+
a.note ? `\n${a.note}` : null, link ? `\n[Open the plan review](${link})` : null, `\n<sub>via lake-gate · ${via}</sub>`].filter(Boolean).join('\n') });
|
|
177
|
+
return `Review requested on PR #${number} for ${plan.id} v${plan.short}.${note}${link ? `\nReview page: ${link}` : ''}\nCall lake_review_status with wait_seconds to wait for feedback. Do not implement until it is approved.`;
|
|
178
|
+
}
|
|
179
|
+
case 'lake_review_status': {
|
|
180
|
+
const id = resolveId(ctx, a.plan_id);
|
|
181
|
+
const local = loadPlan(ctx.root, id);
|
|
182
|
+
let { number, model, config, events, pr } = await prModel(ctx, id);
|
|
183
|
+
const localCost = () => { if (!local) return ''; const cfg = loadConfig(ctx.root); return `\n\n${formatCost(estimatePlan(local.body, cfg), cfg)}`; };
|
|
184
|
+
if (!number) return `No open PR for this branch yet. Push the plan and open a PR so teammates can review it.${local ? ` Local plan ${id} is v${local.short}.` : ''}${localCost()}`;
|
|
185
|
+
if (!model) return `PR #${number} does not contain .lake/plans/${id}.md yet. Push the plan file.`;
|
|
186
|
+
const wait = Math.min(240, Math.max(0, Number(a.wait_seconds) || 0));
|
|
187
|
+
const sig = (m) => `${m.status}|${m.digest}|${m.verdicts.length}|${m.threads.reduce((n, t) => n + t.comments.length, 0)}`;
|
|
188
|
+
const start = sig(model); let waited = 0;
|
|
189
|
+
while (waited < wait && sig(model) === start) {
|
|
190
|
+
await ctx.sleep(20000); waited += 20;
|
|
191
|
+
({ model, config, events, pr } = await prModel(ctx, id));
|
|
192
|
+
}
|
|
193
|
+
// Sync locally so the Claude Code hook sees the decision.
|
|
194
|
+
try {
|
|
195
|
+
const digestAt = {}; const raw = await collectEvents(ctx.github(), number);
|
|
196
|
+
for (const p of listPlans(ctx.root)) digestAt[p.id] = await nativeDigests(ctx.github(), raw, `.lake/plans/${p.id}.md`, { headSha: pr.head.sha, config });
|
|
197
|
+
applyEvents(ctx.root, { events: raw, prAuthor: pr.user.login, prNumber: number, digestAt });
|
|
198
|
+
} catch { /* status is still useful without a local sync */ }
|
|
199
|
+
const changed = waited && sig(model) !== start ? `Changed after ${waited}s.\n` : waited ? `No change after ${waited}s.\n` : '';
|
|
200
|
+
return changed + formatReview(model, { localDigest: local?.digest, link: reviewLink(config, ctx.github().repo, number, id) });
|
|
201
|
+
}
|
|
202
|
+
case 'lake_submit_revision': {
|
|
203
|
+
const id = resolveId(ctx, a.plan_id);
|
|
204
|
+
const { plan } = exportPlan(ctx.root, a.plan_markdown, { id, source: 'mcp' });
|
|
205
|
+
let note = '';
|
|
206
|
+
if (a.push) note = '\n' + pushPlan(ctx, plan.id, `Plan revision: ${plan.title} (v${plan.short})`);
|
|
207
|
+
const number = await ctx.pr().catch(() => null);
|
|
208
|
+
if (number) {
|
|
209
|
+
const g = ctx.github();
|
|
210
|
+
await g.req('POST', `/issues/${number}/comments`, { body: [`**Revised plan \`${plan.id}\` → v${plan.short}.** Earlier approvals no longer apply.`, a.note ? `\n${a.note}` : null,
|
|
211
|
+
a.addressed_threads?.length ? `\nAddressed ${a.addressed_threads.length} thread(s).` : null, `\n<sub>via lake-gate · ${via}</sub>`,
|
|
212
|
+
...(a.addressed_threads || []).map((t) => `<!-- lake:resolve ${JSON.stringify({ p: plan.id, t, r: true })} -->`)].filter(Boolean).join('\n') });
|
|
213
|
+
}
|
|
214
|
+
return `Saved ${plan.id} v${plan.short}.${note}${number ? ` Posted the revision on PR #${number}.` : ' No PR found to notify.'}${a.push ? '' : ' Push the plan file so reviewers see this version.'} Call lake_review_status with wait_seconds to wait.`;
|
|
215
|
+
}
|
|
216
|
+
case '_reply': {
|
|
217
|
+
const number = await ctx.pr(); if (!number) throw new Error('No open PR for this branch.');
|
|
218
|
+
await actions.reply(ctx.github(), number, { planId: resolveId(ctx, a.plan_id), thread: a.thread_id, text: a.text, via });
|
|
219
|
+
return `Replied in thread ${a.thread_id} on PR #${number}.`;
|
|
220
|
+
}
|
|
221
|
+
case '_comment': {
|
|
222
|
+
const id = resolveId(ctx, a.plan_id);
|
|
223
|
+
const { number, model } = await prModel(ctx, id);
|
|
224
|
+
if (!model) throw new Error(`No PR with plan ${id}.`);
|
|
225
|
+
const lines = String(model.body).split('\n'); const s = Math.max(1, Math.floor(a.line)); const e = Math.max(s, Math.floor(a.end_line || s));
|
|
226
|
+
await actions.comment(ctx.github(), number, { planId: id, version: model.digest, anchor: { start: s, end: e, quote: lines.slice(s - 1, e).join('\n') }, text: a.text, via });
|
|
227
|
+
return `Commented on ${id} v${model.short}, line ${s}${e > s ? `–${e}` : ''}.`;
|
|
228
|
+
}
|
|
229
|
+
case '_approve': case '_changes': {
|
|
230
|
+
const id = a.plan_id;
|
|
231
|
+
const { number, model } = await prModel(ctx, id);
|
|
232
|
+
if (!model) throw new Error(`No open PR with plan ${id}.`);
|
|
233
|
+
const v = String(a.version || '').toLowerCase();
|
|
234
|
+
if (v.length < 7 || !model.digest.startsWith(v)) return `Not posted: version ${a.version || '(none)'} is not the current version of ${id}. The current version is ${model.short}. Show the user what changed and ask again.`;
|
|
235
|
+
if (name === '_changes' && !String(a.comment || '').trim()) return 'Not posted: say what needs to change.';
|
|
236
|
+
await actions.verdict(ctx.github(), number, { action: name === '_approve' ? 'approve' : 'reject', planId: id, version: model.digest, text: a.comment, via });
|
|
237
|
+
return `${name === '_approve' ? 'Approved' : 'Requested changes on'} ${id} v${model.short} on PR #${number}. The PR check updates in a few seconds. If you are the PR author it will not count.`;
|
|
238
|
+
}
|
|
239
|
+
case 'lake_cost': {
|
|
240
|
+
const id = resolveId(ctx, a.plan_id);
|
|
241
|
+
const plan = loadPlan(ctx.root, id); if (!plan) throw new Error(`No plan ${id}`);
|
|
242
|
+
const cfg = loadConfig(ctx.root); const est = estimatePlan(plan.body, cfg);
|
|
243
|
+
return `Plan ${id} v${plan.short}\n` + formatCost(est, cfg, undefined, est.exposure > (cfg.budget?.approverAbove ?? Infinity) ? { required: true, exposure: est.exposure, threshold: cfg.budget.approverAbove, approvers: (cfg.budget.approvers || []).map((x) => String(x).replace(/^@/, '')), satisfied: false } : null);
|
|
244
|
+
}
|
|
245
|
+
case '_suggest': {
|
|
246
|
+
const { number, model, config } = await prModel(ctx, a.plan_id);
|
|
247
|
+
if (!model) throw new Error(`No open PR with plan ${a.plan_id}.`);
|
|
248
|
+
const s = patchFor(a, model.estimate, config);
|
|
249
|
+
await actions.suggest(ctx.github(), number, { planId: model.id, version: model.digest, title: s.title, patch: s.patch, saving: s.saving, text: a.comment, via });
|
|
250
|
+
return `Suggested on PR #${number}: ${s.title}. The author can accept it in one click in Lake or with lake_submit_revision.`;
|
|
251
|
+
}
|
|
252
|
+
case '_apply': {
|
|
253
|
+
const id = resolveId(ctx, a.plan_id);
|
|
254
|
+
const plan = loadPlan(ctx.root, id); if (!plan) throw new Error(`No plan ${id}`);
|
|
255
|
+
const cfg = loadConfig(ctx.root);
|
|
256
|
+
let s; let number = null;
|
|
257
|
+
if (a.thread_id) {
|
|
258
|
+
const r = await prModel(ctx, id); number = r.number;
|
|
259
|
+
const t = r.model?.threads.find((x) => x.id === a.thread_id);
|
|
260
|
+
if (!t?.suggestion) throw new Error(`Thread ${a.thread_id} is not a suggestion.`);
|
|
261
|
+
s = { title: t.suggestion.title, patch: t.suggestion.patch };
|
|
262
|
+
} else s = patchFor(a, estimatePlan(plan.body, cfg), cfg);
|
|
263
|
+
const next = applyPatch(stripEstimate(plan.body).replace(/\s+$/, '') + '\n', s.patch);
|
|
264
|
+
const { plan: np, estimate } = exportPlan(ctx.root, next, { id, source: 'mcp' });
|
|
265
|
+
let note = '';
|
|
266
|
+
if (a.push) note = '\n' + pushPlan(ctx, id, `Plan ${id}: ${s.title || describePatch(s.patch, cfg)} (v${np.short})`);
|
|
267
|
+
if (a.thread_id && number) await ctx.github().req('POST', `/issues/${number}/comments`, { body: acceptBody({ planId: id, thread: a.thread_id, title: s.title, newVersion: np.digest, via }) });
|
|
268
|
+
return `Applied "${s.title}" to ${id}: new version v${np.short}, ${range(estimate.declared ? estimate.plannedUsd : estimate.usd)}.${note}${a.push ? '' : ' Push the plan file so reviewers see it.'} Earlier approvals no longer apply.`;
|
|
269
|
+
}
|
|
270
|
+
default: throw new Error(`Unknown tool ${name}`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Minimal MCP stdio transport: newline-delimited JSON-RPC 2.0.
|
|
275
|
+
export function serve({ input = process.stdin, output = process.stdout, ctxOptions = {} } = {}) {
|
|
276
|
+
let ctx = null;
|
|
277
|
+
const send = (m) => output.write(JSON.stringify(m) + '\n');
|
|
278
|
+
let buf = '';
|
|
279
|
+
const handle = async (msg) => {
|
|
280
|
+
const { id, method, params } = msg;
|
|
281
|
+
if (id === undefined) return; // notification
|
|
282
|
+
try {
|
|
283
|
+
if (method === 'initialize') {
|
|
284
|
+
ctx = createContext({ ...ctxOptions, clientName: params?.clientInfo?.name || 'MCP client' });
|
|
285
|
+
return send({ jsonrpc: '2.0', id, result: { protocolVersion: params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'lake-gate', version: VERSION },
|
|
286
|
+
instructions: 'Plan review for coding agents. Request review after planning, wait for approval with lake_review_status, revise with lake_submit_revision. Only approve when the human explicitly says so.' } });
|
|
287
|
+
}
|
|
288
|
+
if (method === 'ping') return send({ jsonrpc: '2.0', id, result: {} });
|
|
289
|
+
if (method === 'tools/list') return send({ jsonrpc: '2.0', id, result: { tools: TOOLS } });
|
|
290
|
+
if (method === 'tools/call') {
|
|
291
|
+
ctx = ctx || createContext(ctxOptions);
|
|
292
|
+
try {
|
|
293
|
+
const text = await callTool(ctx, params.name, params.arguments || {});
|
|
294
|
+
return send({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text }] } });
|
|
295
|
+
} catch (e) { return send({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: `lake-gate: ${e.message}` }], isError: true } }); }
|
|
296
|
+
}
|
|
297
|
+
send({ jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } });
|
|
298
|
+
} catch (e) { send({ jsonrpc: '2.0', id, error: { code: -32603, message: e.message } }); }
|
|
299
|
+
};
|
|
300
|
+
input.setEncoding?.('utf8');
|
|
301
|
+
input.on('data', (chunk) => {
|
|
302
|
+
buf += chunk;
|
|
303
|
+
let i;
|
|
304
|
+
while ((i = buf.indexOf('\n')) >= 0) {
|
|
305
|
+
const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1);
|
|
306
|
+
if (!line) continue;
|
|
307
|
+
let msg; try { msg = JSON.parse(line); } catch { send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); continue; }
|
|
308
|
+
handle(msg);
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
return new Promise((resolve) => input.on('end', resolve));
|
|
312
|
+
}
|