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/LICENSE +21 -0
- package/README.md +152 -2
- package/action.yml +21 -0
- package/bin/lake-gate.js +3 -0
- package/package.json +48 -4
- package/src/action.js +75 -0
- package/src/cli.js +124 -0
- package/src/config-core.js +38 -0
- package/src/config.js +10 -0
- package/src/estimate.js +70 -0
- package/src/github.js +170 -0
- package/src/hook.js +73 -0
- package/src/index.js +10 -0
- package/src/init.js +62 -0
- package/src/mcp.js +312 -0
- package/src/meter-core.js +535 -0
- package/src/models.js +193 -0
- package/src/plan.js +90 -0
- package/src/policy.js +57 -0
- package/src/review.js +319 -0
- package/src/sha256.js +37 -0
- package/src/store.js +90 -0
- package/src/sync.js +50 -0
- package/src/ui-server.js +81 -0
- package/src/workspace.js +104 -0
- package/templates/lake-gate.yml +28 -0
- package/templates/plans-README.md +10 -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
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { parseConfig } from './config-core.js';
|
|
2
|
+
import { readPlanText } from './plan.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';
|
|
7
|
+
|
|
8
|
+
export const STATUS_CONTEXT = 'lake/plan-approval';
|
|
9
|
+
export const MARKER = '<!-- lake-gate:summary -->';
|
|
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
|
+
|
|
17
|
+
export function client({ token, repo, api = 'https://api.github.com', fetchImpl = globalThis.fetch }) {
|
|
18
|
+
const [owner, name] = repo.split('/');
|
|
19
|
+
async function req(method, url, body) {
|
|
20
|
+
const full = url.startsWith('http') ? url : url.startsWith('~/') ? `${api}${url.slice(1)}` : `${api}/repos/${owner}/${name}${url}`;
|
|
21
|
+
const res = await fetchImpl(full, {
|
|
22
|
+
method,
|
|
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' } : {}) },
|
|
24
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
25
|
+
});
|
|
26
|
+
if (res.status === 404 && method === 'GET') return null;
|
|
27
|
+
if (!res.ok) throw new Error(`GitHub ${method} ${url} -> ${res.status} ${await res.text()}`);
|
|
28
|
+
return res.status === 204 ? null : res.json();
|
|
29
|
+
}
|
|
30
|
+
async function all(url) {
|
|
31
|
+
const out = [];
|
|
32
|
+
for (let page = 1; page < 50; page++) {
|
|
33
|
+
const chunk = await req('GET', `${url}${url.includes('?') ? '&' : '?'}per_page=100&page=${page}`);
|
|
34
|
+
if (!chunk || !chunk.length) break;
|
|
35
|
+
out.push(...chunk);
|
|
36
|
+
if (chunk.length < 100) break;
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
async function file(p, ref) {
|
|
41
|
+
const r = await req('GET', `/contents/${p.split('/').map(encodeURIComponent).join('/')}?ref=${encodeURIComponent(ref)}`);
|
|
42
|
+
return r && r.content ? fromBase64(r.content) : null;
|
|
43
|
+
}
|
|
44
|
+
return { req, all, file, owner, name, repo, api };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function collectEvents(gh, number) {
|
|
48
|
+
const [comments, reviews] = await Promise.all([gh.all(`/issues/${number}/comments`), gh.all(`/pulls/${number}/reviews`)]);
|
|
49
|
+
return [
|
|
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 })),
|
|
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 })),
|
|
52
|
+
];
|
|
53
|
+
}
|
|
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
|
+
|
|
81
|
+
const isPlanPath = (f) => /^\.lake\/plans\/[^/]+\.md$/.test(f) && !f.endsWith('/README.md');
|
|
82
|
+
const isCodePath = (f) => !f.startsWith('.lake/') && !/\.(md|txt)$/i.test(f) && !f.startsWith('docs/');
|
|
83
|
+
|
|
84
|
+
// Evaluates every plan file touched by the PR. Config is read from the BASE branch so a PR cannot loosen its own policy.
|
|
85
|
+
export async function evaluatePr(gh, number) {
|
|
86
|
+
const pr = await gh.req('GET', `/pulls/${number}`);
|
|
87
|
+
const config = parseConfig(await gh.file('.lake/config.json', pr.base.sha));
|
|
88
|
+
const files = await gh.all(`/pulls/${number}/files`);
|
|
89
|
+
const planFiles = files.filter((f) => isPlanPath(f.filename) && f.status !== 'removed').map((f) => f.filename);
|
|
90
|
+
const codeChanged = files.some((f) => isCodePath(f.filename));
|
|
91
|
+
const events = await collectEvents(gh, number);
|
|
92
|
+
const budgetApprovers = await resolveBudgetApprovers(gh, config);
|
|
93
|
+
const results = [];
|
|
94
|
+
for (const p of planFiles) {
|
|
95
|
+
const text = await gh.file(p, pr.head.sha);
|
|
96
|
+
if (text == null) continue;
|
|
97
|
+
const plan = readPlanText(text, p.split('/').pop().slice(0, -3));
|
|
98
|
+
const estimate = estimatePlan(plan.body, config);
|
|
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 });
|
|
102
|
+
}
|
|
103
|
+
return { pr, config, results, codeChanged, repo: gh.repo, ...summarize(results, codeChanged, config) };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function summarize(results, codeChanged, config) {
|
|
107
|
+
if (!results.length) {
|
|
108
|
+
if (!codeChanged || config.requirePlan === 'off') return { state: 'success', description: 'No plan in this PR' };
|
|
109
|
+
return config.requirePlan === 'fail'
|
|
110
|
+
? { state: 'failure', description: 'Code changed without a plan in .lake/plans/' }
|
|
111
|
+
: { state: 'success', description: 'Warning: code changed without a plan in .lake/plans/' };
|
|
112
|
+
}
|
|
113
|
+
const bad = results.filter((r) => !isPassing(r));
|
|
114
|
+
if (!bad.length) return { state: 'success', description: `${results.length} plan(s) approved for their current version` };
|
|
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) };
|
|
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) };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function renderSummary(ev) {
|
|
121
|
+
const lines = [MARKER, '### Lake plan gate', ''];
|
|
122
|
+
if (!ev.results.length) { lines.push(ev.description + '.'); return lines.join('\n'); }
|
|
123
|
+
lines.push('| Plan | Version | Status | Complexity | Est. cost |', '|---|---|---|---|---|');
|
|
124
|
+
for (const r of ev.results) {
|
|
125
|
+
const status = r.state === 'approved' ? `approved by ${r.approvers.map((a) => '@' + a).join(', ')}` :
|
|
126
|
+
r.state === 'auto-approved' ? 'auto-approved by policy' :
|
|
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}`);
|
|
140
|
+
}
|
|
141
|
+
const pending = ev.results.filter((r) => !isPassing(r));
|
|
142
|
+
if (pending.length) {
|
|
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}`), '```',
|
|
154
|
+
'Approval is bound to this exact version. Editing the plan file needs a fresh approval.');
|
|
155
|
+
}
|
|
156
|
+
const shadow = ev.results.filter((r) => r.auto.mode === 'shadow' && r.auto.eligible && !isPassing(r));
|
|
157
|
+
if (shadow.length) lines.push('', `Shadow auto-approve: ${shadow.map((r) => r.id).join(', ')} would pass the auto-approve policy. It is in shadow mode, so a human still decides.`);
|
|
158
|
+
const notes = ev.results.flatMap((r) => r.notes);
|
|
159
|
+
if (notes.length) lines.push('', '<details><summary>Ignored commands</summary>', '', ...notes.map((n) => `- ${n}`), '', '</details>');
|
|
160
|
+
return lines.join('\n');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export async function publish(gh, ev, { comment = true } = {}) {
|
|
164
|
+
await gh.req('POST', `/statuses/${ev.pr.head.sha}`, { state: ev.state, context: STATUS_CONTEXT, description: ev.description.slice(0, 140) });
|
|
165
|
+
if (!comment || (!ev.results.length && ev.state === 'success' && !/Warning/.test(ev.description))) return;
|
|
166
|
+
const body = renderSummary(ev);
|
|
167
|
+
const existing = (await gh.all(`/issues/${ev.pr.number}/comments`)).find((c) => c.user.type === 'Bot' && String(c.body).startsWith(MARKER));
|
|
168
|
+
if (existing) { if (existing.body !== body) await gh.req('PATCH', `/issues/comments/${existing.id}`, { body }); }
|
|
169
|
+
else await gh.req('POST', `/issues/${ev.pr.number}/comments`, { body });
|
|
170
|
+
}
|
package/src/hook.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { loadConfig } from './config.js';
|
|
3
|
+
import { repoRoot, stateDir, getState, setState, loadPlan, exportPlan, localStatus } from './store.js';
|
|
4
|
+
import { range } from './estimate.js';
|
|
5
|
+
|
|
6
|
+
const FILE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
|
|
7
|
+
const inside = (p, dir) => { const r = path.relative(dir, p); return r === '' || (!r.startsWith('..') && !path.isAbsolute(r)); };
|
|
8
|
+
|
|
9
|
+
function out(decision, reason, extra = {}) {
|
|
10
|
+
if (!decision) return extra.systemMessage ? { systemMessage: extra.systemMessage } : null;
|
|
11
|
+
return { ...(extra.systemMessage ? { systemMessage: extra.systemMessage } : {}),
|
|
12
|
+
hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: decision, permissionDecisionReason: reason } };
|
|
13
|
+
}
|
|
14
|
+
|
|
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).`;
|
|
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`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Pure decision for one Claude Code PreToolUse payload. Returns the JSON object to print (or null for "no opinion").
|
|
21
|
+
export function handleClaudePreToolUse(input, env = process.env) {
|
|
22
|
+
if (env.LAKE_GATE === 'off') return null;
|
|
23
|
+
const root = repoRoot(input.cwd || env.CLAUDE_PROJECT_DIR || process.cwd());
|
|
24
|
+
const config = loadConfig(root);
|
|
25
|
+
const tool = input.tool_name;
|
|
26
|
+
const ti = input.tool_input || {};
|
|
27
|
+
|
|
28
|
+
if (tool === 'ExitPlanMode') {
|
|
29
|
+
if (!ti.plan || !String(ti.plan).trim()) return null;
|
|
30
|
+
const { plan, estimate } = exportPlan(root, ti.plan, { source: 'claude-code', sessionId: input.session_id });
|
|
31
|
+
const st = localStatus(root, plan, config);
|
|
32
|
+
const gateNote = st.state === 'approved' || st.state === 'auto-approved' ? `Already ${st.state}` : 'Implementation is gated until a teammate approves this version';
|
|
33
|
+
return out(null, null, { systemMessage: `Lake: plan saved to .lake/plans/${plan.id}.md (version ${plan.short}, ${estimate.complexity} complexity, est. ${range(estimate.usd)}). ${gateNote}.` });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (config.localGate === 'off' || !config.gatedTools.includes(tool)) return null;
|
|
37
|
+
if (input.permission_mode === 'plan') return null; // plan mode is read-only already
|
|
38
|
+
|
|
39
|
+
const sdir = stateDir(root);
|
|
40
|
+
if (FILE_TOOLS.has(tool)) {
|
|
41
|
+
const fp = path.resolve(root, ti.file_path || ti.notebook_path || '');
|
|
42
|
+
if (inside(fp, sdir)) return out('deny', 'Lake: local approval state cannot be edited by the agent.');
|
|
43
|
+
if (inside(fp, path.join(root, '.lake', 'plans'))) return null; // editing a plan is allowed; it creates a new version
|
|
44
|
+
if (!inside(fp, root)) return null; // outside the repo is out of scope
|
|
45
|
+
}
|
|
46
|
+
if (tool === 'Bash') {
|
|
47
|
+
const cmd = String(ti.command || '');
|
|
48
|
+
if (/\.git\/lake|lake[\\/]+(state|approvals)\.json/.test(cmd)) return out('deny', 'Lake: local approval state cannot be edited by the agent.');
|
|
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.');
|
|
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, ''));
|
|
52
|
+
if (ro) return null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const decision = config.localGate === 'ask' ? 'ask' : 'deny';
|
|
56
|
+
const state = getState(root);
|
|
57
|
+
const activeId = (input.session_id && state.sessions[input.session_id]) || state.active;
|
|
58
|
+
const plan = activeId && loadPlan(root, activeId);
|
|
59
|
+
if (!plan) {
|
|
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.' });
|
|
67
|
+
}
|
|
68
|
+
const st = localStatus(root, plan, config);
|
|
69
|
+
if (st.state === 'approved' || st.state === 'auto-approved') return null;
|
|
70
|
+
const why = st.state === 'changes-requested' ? `changes were requested by ${(st.blockers || []).map((b) => '@' + b).join(', ')}` :
|
|
71
|
+
st.stale ? 'the plan was edited after it was approved, so the approval no longer applies' : 'it is not approved yet';
|
|
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)}`);
|
|
73
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export * from './config.js';
|
|
2
|
+
export * from './plan.js';
|
|
3
|
+
export * from './estimate.js';
|
|
4
|
+
export * from './policy.js';
|
|
5
|
+
export * from './store.js';
|
|
6
|
+
export * from './hook.js';
|
|
7
|
+
export * from './github.js';
|
|
8
|
+
export * from './sync.js';
|
|
9
|
+
export * from './init.js';
|
|
10
|
+
export * from './models.js';
|
package/src/init.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { DEFAULT_CONFIG } from './config.js';
|
|
5
|
+
|
|
6
|
+
export const ACTION_REF = 'getlake/lake-gate@v0';
|
|
7
|
+
const TEMPLATES = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'templates');
|
|
8
|
+
|
|
9
|
+
export const HOOK_COMMAND = 'if [ -x "$CLAUDE_PROJECT_DIR/node_modules/.bin/lake-gate" ]; then exec "$CLAUDE_PROJECT_DIR/node_modules/.bin/lake-gate" hook claude; elif command -v lake-gate >/dev/null 2>&1; then exec lake-gate hook claude; else exec npx -y lake-gate@0 hook claude; fi';
|
|
10
|
+
const MATCHER = 'ExitPlanMode|Edit|Write|MultiEdit|NotebookEdit|Bash';
|
|
11
|
+
|
|
12
|
+
export function mergeClaudeSettings(settings) {
|
|
13
|
+
const s = settings && typeof settings === 'object' ? structuredClone(settings) : {};
|
|
14
|
+
s.hooks = s.hooks || {};
|
|
15
|
+
const list = (s.hooks.PreToolUse = s.hooks.PreToolUse || []);
|
|
16
|
+
const already = list.some((g) => (g.hooks || []).some((h) => String(h.command || '').includes('lake-gate')));
|
|
17
|
+
if (!already) list.push({ matcher: MATCHER, hooks: [{ type: 'command', command: HOOK_COMMAND, timeout: 30, onFailure: 'block' }] });
|
|
18
|
+
return { settings: s, changed: !already };
|
|
19
|
+
}
|
|
20
|
+
|
|
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 } = {}) {
|
|
31
|
+
const done = [];
|
|
32
|
+
const write = (rel, content, overwrite = force) => {
|
|
33
|
+
const p = path.join(root, rel);
|
|
34
|
+
if (fs.existsSync(p) && !overwrite) { done.push(`kept ${rel} (exists)`); return; }
|
|
35
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
36
|
+
fs.writeFileSync(p, content);
|
|
37
|
+
done.push(`wrote ${rel}`);
|
|
38
|
+
};
|
|
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');
|
|
42
|
+
write('.lake/plans/README.md', fs.readFileSync(path.join(TEMPLATES, 'plans-README.md'), 'utf8'));
|
|
43
|
+
write('.github/workflows/lake-gate.yml', fs.readFileSync(path.join(TEMPLATES, 'lake-gate.yml'), 'utf8').replace('__ACTION_REF__', actionRef));
|
|
44
|
+
|
|
45
|
+
const sp = path.join(root, '.claude', 'settings.json');
|
|
46
|
+
let current = {};
|
|
47
|
+
if (fs.existsSync(sp)) { try { current = JSON.parse(fs.readFileSync(sp, 'utf8')); } catch { throw new Error('.claude/settings.json is not valid JSON; fix it and run init again.'); } }
|
|
48
|
+
const { settings, changed } = mergeClaudeSettings(current);
|
|
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)'); }
|
|
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
|
+
}
|
|
61
|
+
return done;
|
|
62
|
+
}
|