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/models.js
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// Model choice, cost-cutting suggestions and budget exposure for a plan. Pure and browser-safe.
|
|
2
|
+
// A plan declares its model in the plan text, so the choice is part of the approved version:
|
|
3
|
+
// Model: sonnet-5.5 (whole plan; also "**Model:** Opus 5.5" or "Agent: Claude Code · Model: opus")
|
|
4
|
+
// 3. Rename the flag (model: haiku) (one step)
|
|
5
|
+
// Budget cap: $12 (the run stops here; budget approval looks at the cap, not the upper estimate)
|
|
6
|
+
// Steps marked "(optional)" can be dropped by a suggestion.
|
|
7
|
+
import { stripEstimate, normalizeBody } from './plan.js';
|
|
8
|
+
import { splitPlan, costOfBudget, resolveModel as meterResolve } from './meter-core.js';
|
|
9
|
+
import { pricesFor } from './estimate.js';
|
|
10
|
+
|
|
11
|
+
// Models and prices come from the shared Lake price table (lake-meter's prices.json, see meter-core.js).
|
|
12
|
+
// quality by tier: light 2, standard 3, heavy 4, frontier 5. A step of complexity level n needs NEED_LEVEL[n].
|
|
13
|
+
const QUALITY = { light: 2, standard: 3, heavy: 4, frontier: 5 };
|
|
14
|
+
const NEED_LEVEL = { 1: 2, 2: 2, 3: 3, 4: 4, 5: 4 };
|
|
15
|
+
export const NEED = { low: 2, medium: 3, high: 4 };
|
|
16
|
+
const need = (s) => NEED_LEVEL[s.level] ?? NEED[s.complexity];
|
|
17
|
+
const TIER_ALIAS = { fast: 'light', light: 'light', balanced: 'standard', standard: 'standard', frontier: 'heavy', heavy: 'heavy', max: 'frontier' };
|
|
18
|
+
// Current models shown as options (older ones still resolve and price).
|
|
19
|
+
const CURRENT = (prices) => [...new Set(Object.values(prices.recommend || {}).flatMap((r) => Object.values(r)))];
|
|
20
|
+
|
|
21
|
+
export function catalogOf(config) {
|
|
22
|
+
const prices = pricesFor(config);
|
|
23
|
+
const out = {};
|
|
24
|
+
for (const [k, m] of Object.entries(prices.models)) out[k] = { ...m, name: m.label || k, quality: m.quality ?? QUALITY[m.tier] ?? 3 };
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
const norm = (s) => String(s || '').toLowerCase().replace(/[`*_]/g, '').replace(/^claude[\s-]+/, '').trim();
|
|
28
|
+
export function resolveModel(text, config) {
|
|
29
|
+
const q = norm(text); if (!q) return null;
|
|
30
|
+
const prices = pricesFor(config); const cat = catalogOf(config);
|
|
31
|
+
const hit = (k) => (k && cat[k] ? { key: k, ...cat[k] } : null);
|
|
32
|
+
if (cat[text]) return hit(text);
|
|
33
|
+
if (TIER_ALIAS[q]) return hit(prices.recommend[config.provider || 'anthropic'][TIER_ALIAS[q]]);
|
|
34
|
+
for (const [k, m] of Object.entries(cat)) if (norm(m.name) === q || norm(m.alias) === q) return hit(k);
|
|
35
|
+
return hit(meterResolve(q.replace(/\s+/g, '-'), prices));
|
|
36
|
+
}
|
|
37
|
+
export function recommendedKey(level, config) {
|
|
38
|
+
const prices = pricesFor(config);
|
|
39
|
+
const lv = typeof level === 'number' ? level : { low: 2, medium: 3, high: 4 }[level] || 3;
|
|
40
|
+
return prices.recommend[config.provider || 'anthropic'][prices.assumptions.complexityToTier[String(lv)]];
|
|
41
|
+
}
|
|
42
|
+
// Cost of one step's token budget on a model, the same way lake-meter prices it.
|
|
43
|
+
function stepUsd(s, key, prices) {
|
|
44
|
+
const b = prices.assumptions.stepTokens[String(s.level)] || prices.assumptions.stepTokens['3'];
|
|
45
|
+
const mult = prices.assumptions.tierTokenMultiplier[prices.models[key].tier] ?? 1;
|
|
46
|
+
return [0, 1].map((i) => costOfBudget(key, b.input[i] * mult, b.output[i] * mult, prices));
|
|
47
|
+
}
|
|
48
|
+
const NAME_OF = (key, config) => catalogOf(config)[key]?.name || key;
|
|
49
|
+
|
|
50
|
+
const PLAN_MODEL = /^\s*(?:[-*>]\s*)?(?:\*\*)?(?:agent\s*[^\n]*?·\s*)?model(?:\*\*)?\s*:(?:\*\*)?\s*(.+?)\s*$/im;
|
|
51
|
+
const STEP_MODEL = /\s*[([]\s*model\s*:\s*([^)\]]+)[)\]]/i;
|
|
52
|
+
const CAP = /^\s*(?:[-*>]\s*)?(?:\*\*)?budget\s*cap(?:\*\*)?\s*:(?:\*\*)?\s*\$?\s*([\d.,]+)/im;
|
|
53
|
+
const OPTIONAL = /\((?:optional|nice to have)\)|\boptional:/i;
|
|
54
|
+
|
|
55
|
+
export function declarations(body) {
|
|
56
|
+
const b = stripEstimate(String(body));
|
|
57
|
+
const pm = b.match(PLAN_MODEL);
|
|
58
|
+
const cap = b.match(CAP);
|
|
59
|
+
return { model: pm ? pm[1].replace(/\*+$/, '').trim() : null, cap: cap ? Number(cap[1].replace(/,/g, '')) : null };
|
|
60
|
+
}
|
|
61
|
+
export function stepModelTag(text) { const m = String(text).match(STEP_MODEL); return m ? m[1].trim() : null; }
|
|
62
|
+
export const isOptionalStep = (text) => OPTIONAL.test(String(text));
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
// Adds the declared model per step and its cost to an estimate from estimatePlan.
|
|
66
|
+
export function applyDeclarations(est, body, config) {
|
|
67
|
+
const d = declarations(body);
|
|
68
|
+
const planModel = d.model ? resolveModel(d.model, config) : null;
|
|
69
|
+
const notes = [];
|
|
70
|
+
if (d.model && !planModel) notes.push(`Unknown model "${d.model}". Add it to "catalog" in .lake/config.json to price it.`);
|
|
71
|
+
const prices = pricesFor(config); const cat = catalogOf(config);
|
|
72
|
+
const raw = splitPlan(normalizeBody(body)).map((x) => ({ text: `${x.title}\n${x.body || ''}` }));
|
|
73
|
+
const steps = est.steps.map((s, i) => {
|
|
74
|
+
const tag = stepModelTag(raw[i]?.text || '');
|
|
75
|
+
const tagged = tag ? resolveModel(tag, config) : null;
|
|
76
|
+
if (tag && !tagged) notes.push(`Step ${s.n}: unknown model "${tag}".`);
|
|
77
|
+
const m = tagged || planModel;
|
|
78
|
+
const rec = s.modelKey || recommendedKey(s.level, config);
|
|
79
|
+
const planned = m ? { key: m.key, name: m.name, quality: m.quality, usd: stepUsd(s, m.key, prices), source: tagged ? 'step' : 'plan' } : null;
|
|
80
|
+
const fit = !m ? 'ok' : m.quality < need(s) ? 'risky' : m.quality > (cat[rec]?.quality ?? 9) ? 'overkill' : 'ok';
|
|
81
|
+
return { ...s, recommendedKey: rec, planned, fit, optional: isOptionalStep(raw[i]?.text || ''), title: s.title.replace(STEP_MODEL, '').trim() };
|
|
82
|
+
});
|
|
83
|
+
const sum = (i) => steps.reduce((a, s) => a + (s.planned ? s.planned.usd[i] : s.usd[i]), 0);
|
|
84
|
+
const plannedUsd = [sum(0), sum(1)];
|
|
85
|
+
const declared = steps.some((s) => s.planned);
|
|
86
|
+
const exposure = d.cap != null ? Math.min(d.cap, plannedUsd[1]) : plannedUsd[1];
|
|
87
|
+
return { ...est, steps, model: planModel ? { key: planModel.key, name: planModel.name } : null, declared, plannedUsd, cap: d.cap, exposure, modelNotes: notes };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Whole-plan options for the model picker: cost if every step ran on that model, and how it fits.
|
|
91
|
+
export function modelOptions(est, config) {
|
|
92
|
+
const prices = pricesFor(config); const cat = catalogOf(config);
|
|
93
|
+
const top = Math.max(2, ...est.steps.map(need));
|
|
94
|
+
const keys = [...new Set([...CURRENT(prices), ...(est.model ? [est.model.key] : [])])].filter((k) => cat[k]);
|
|
95
|
+
const opts = keys.map((key) => {
|
|
96
|
+
const m = cat[key];
|
|
97
|
+
const usd = [0, 1].map((i) => est.steps.reduce((a, s) => a + stepUsd(s, key, prices)[i], 0));
|
|
98
|
+
const weak = est.steps.filter((s) => m.quality < need(s)).length;
|
|
99
|
+
const fit = weak ? 'risky' : m.quality > top ? 'overkill' : 'good';
|
|
100
|
+
const note = weak ? `${weak} step${weak > 1 ? 's' : ''} may need retries or a human fix` : fit === 'overkill' ? 'Top quality, pays for headroom you may not use' : top >= 4 ? 'Strong enough for the hard steps' : 'Enough for every step';
|
|
101
|
+
return { key, name: m.name, provider: m.provider, quality: m.quality, usd, fit, note };
|
|
102
|
+
});
|
|
103
|
+
const mix = { key: 'lake-mix', name: 'Lake mix', provider: 'Per step', quality: null, usd: est.usd, fit: 'good', note: 'Cheapest model that fits each step', recommended: true };
|
|
104
|
+
return [mix, ...opts.sort((a, b) => a.usd[1] - b.usd[1])];
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Cost-cutting suggestions. Each one has a machine-applicable patch (see applyPatch).
|
|
108
|
+
export function costSuggestions(est, config) {
|
|
109
|
+
const b = config.budget || {};
|
|
110
|
+
const out = [];
|
|
111
|
+
const cat = catalogOf(config);
|
|
112
|
+
const over = est.steps.filter((s) => s.planned && s.planned.quality > cat[s.recommendedKey].quality);
|
|
113
|
+
if (over.length) {
|
|
114
|
+
const saving = [0, 1].map((i) => over.reduce((a, s) => a + s.planned.usd[i] - s.usd[i], 0));
|
|
115
|
+
out.push({ id: `models-${over.map((s) => s.n).join('-')}`, kind: 'model', title: over.length === 1 ? `Run step ${over[0].n} on ${cat[over[0].recommendedKey].name}` : over.length === est.steps.length ? 'Use the Lake pick for each step' : `Cheaper models for ${over.length} simpler steps`,
|
|
116
|
+
detail: over.map((s) => `${s.n}. ${s.title.slice(0, 40)}: ${s.planned.name} → ${cat[s.recommendedKey].name}`).join('\n'), saving,
|
|
117
|
+
patch: { type: 'stepModels', steps: over.map((s) => ({ n: s.n, title: s.title, model: cat[s.recommendedKey].name })) } });
|
|
118
|
+
}
|
|
119
|
+
for (const s of est.steps.filter((x) => x.optional)) {
|
|
120
|
+
const u = s.planned ? s.planned.usd : s.usd;
|
|
121
|
+
out.push({ id: `drop-${s.n}`, kind: 'drop', title: `Drop optional step ${s.n}`, detail: s.title, saving: u, patch: { type: 'dropStep', n: s.n, title: s.title } });
|
|
122
|
+
}
|
|
123
|
+
const capAbove = b.suggestCapAbove ?? 10;
|
|
124
|
+
if (est.cap == null && est.plannedUsd[1] > capAbove) {
|
|
125
|
+
const mid = (est.plannedUsd[0] + est.plannedUsd[1]) / 2;
|
|
126
|
+
const cap = Math.max(1, Math.ceil(mid * 1.15));
|
|
127
|
+
if (cap < est.plannedUsd[1]) out.push({ id: `cap-${cap}`, kind: 'cap', title: `Cap the run at $${cap}`, detail: 'The agent stops and asks before spending more. Budget approval looks at the cap.', saving: [0, est.plannedUsd[1] - cap], patch: { type: 'cap', usd: cap } });
|
|
128
|
+
}
|
|
129
|
+
const min = b.suggestAbove ?? 0;
|
|
130
|
+
return est.plannedUsd[1] >= min ? out.filter((s) => s.saving[1] > 0.005) : [];
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ---- Applying a patch to plan text (body without frontmatter) ----
|
|
134
|
+
const plain = (x) => String(x).replace(STEP_MODEL, '').replace(/[`*_]/g, '').trim();
|
|
135
|
+
function stepLine(lines, title) {
|
|
136
|
+
const t = plain(title).slice(0, 50);
|
|
137
|
+
return lines.findIndex((l) => /^\s{0,3}(\d+[.)]|[-*]|#{2,4})\s+/.test(l) && plain(l).includes(t));
|
|
138
|
+
}
|
|
139
|
+
export function setPlanModel(body, key) {
|
|
140
|
+
const lines = String(body).split('\n');
|
|
141
|
+
const i = lines.findIndex((l) => PLAN_MODEL.test(l) && !/^\s{0,3}\d+[.)]/.test(l));
|
|
142
|
+
const line = `Model: ${key}`;
|
|
143
|
+
if (i >= 0) lines[i] = line;
|
|
144
|
+
else { const h = lines.findIndex((l) => /^#\s+/.test(l)); lines.splice(h + 1, 0, '', line); }
|
|
145
|
+
// a plan-level choice replaces per-step overrides
|
|
146
|
+
return lines.map((l) => (/^\s{0,3}(\d+[.)]|[-*])\s+/.test(l) ? l.replace(STEP_MODEL, '') : l)).join('\n').replace(/\n{3,}/g, '\n\n');
|
|
147
|
+
}
|
|
148
|
+
export function applyPatch(body, patch) {
|
|
149
|
+
const lines = String(body).split('\n');
|
|
150
|
+
if (patch.type === 'planModel') return setPlanModel(body, patch.model);
|
|
151
|
+
if (patch.type === 'stepModels') {
|
|
152
|
+
for (const s of patch.steps) { const i = stepLine(lines, s.title); if (i >= 0) lines[i] = `${lines[i].replace(STEP_MODEL, '').replace(/\s+$/, '')} (model: ${s.model})`; }
|
|
153
|
+
return lines.join('\n');
|
|
154
|
+
}
|
|
155
|
+
if (patch.type === 'cap') {
|
|
156
|
+
const i = lines.findIndex((l) => CAP.test(l));
|
|
157
|
+
if (i >= 0) lines[i] = `Budget cap: $${patch.usd}`;
|
|
158
|
+
else { const m = lines.findIndex((l) => PLAN_MODEL.test(l)); const h = m >= 0 ? m : lines.findIndex((l) => /^#\s+/.test(l)); lines.splice(h + 1, 0, ...(m >= 0 ? [] : ['']), `Budget cap: $${patch.usd}`); }
|
|
159
|
+
return lines.join('\n');
|
|
160
|
+
}
|
|
161
|
+
if (patch.type === 'dropStep') {
|
|
162
|
+
const i = stepLine(lines, patch.title); if (i < 0) return body;
|
|
163
|
+
let j = i + 1; while (j < lines.length && /^\s{2,}\S/.test(lines[j])) j++;
|
|
164
|
+
lines.splice(i, j - i);
|
|
165
|
+
{ // renumber the rest of this list
|
|
166
|
+
for (let k = i; k < lines.length; k++) {
|
|
167
|
+
const m = lines[k].match(/^(\s{0,3})(\d+)([.)]\s+.*)$/);
|
|
168
|
+
if (m) lines[k] = `${m[1]}${Number(m[2]) - 1}${m[3]}`; else if (!/^\s{2,}\S/.test(lines[k]) && lines[k].trim()) break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return lines.join('\n');
|
|
172
|
+
}
|
|
173
|
+
throw new Error(`Unknown patch type ${patch.type}`);
|
|
174
|
+
}
|
|
175
|
+
export function describePatch(patch, config) {
|
|
176
|
+
const nm = (k) => NAME_OF(k, config);
|
|
177
|
+
if (patch.type === 'planModel') return `Run the plan on ${nm(patch.model)}`;
|
|
178
|
+
if (patch.type === 'stepModels') return patch.steps.length === 1 ? `Run step ${patch.steps[0].n} on ${nm(patch.steps[0].model)}` : `Cheaper models for steps ${patch.steps.map((s) => s.n).join(', ')}`;
|
|
179
|
+
if (patch.type === 'cap') return `Cap the run at $${patch.usd}`;
|
|
180
|
+
if (patch.type === 'dropStep') return `Drop step ${patch.n}`;
|
|
181
|
+
return patch.type;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ---- Budget approval ----
|
|
185
|
+
// config.budget = { approverAbove: 25, approvers: ['dana', '@acme/eng-managers'] }
|
|
186
|
+
export function budgetRule(est, config, resolvedApprovers) {
|
|
187
|
+
const b = config.budget || {};
|
|
188
|
+
if (b.approverAbove == null || !(b.approvers || []).length) return { required: false };
|
|
189
|
+
const exposure = est.exposure ?? est.usd[1];
|
|
190
|
+
const required = exposure > b.approverAbove;
|
|
191
|
+
const list = resolvedApprovers || b.approvers.filter((x) => !String(x).includes('/')).map((x) => String(x).replace(/^@/, ''));
|
|
192
|
+
return { required, threshold: b.approverAbove, exposure, approvers: list, teams: b.approvers.filter((x) => String(x).includes('/')) };
|
|
193
|
+
}
|
package/src/plan.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { sha256Hex } from './sha256.js';
|
|
2
|
+
|
|
3
|
+
export const EST_START = '<!-- lake:estimate:start (generated, not part of the approved digest) -->';
|
|
4
|
+
export const EST_END = '<!-- lake:estimate:end -->';
|
|
5
|
+
|
|
6
|
+
export function slugify(s) {
|
|
7
|
+
return String(s || 'plan').toLowerCase().normalize('NFKD').replace(/[^\w\s-]/g, '')
|
|
8
|
+
.trim().replace(/[\s_]+/g, '-').replace(/-+/g, '-').slice(0, 48).replace(/-$/, '') || 'plan';
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function splitFrontmatter(text) {
|
|
12
|
+
const t = String(text).replace(/\r\n?/g, '\n');
|
|
13
|
+
const m = t.match(/^---\n([\s\S]*?)\n---\n?/);
|
|
14
|
+
if (!m) return { meta: {}, body: t };
|
|
15
|
+
const meta = {};
|
|
16
|
+
for (const line of m[1].split('\n')) {
|
|
17
|
+
const kv = line.match(/^([\w-]+):\s*(.*)$/);
|
|
18
|
+
if (kv) meta[kv[1]] = kv[2].replace(/^"(.*)"$/, '$1');
|
|
19
|
+
}
|
|
20
|
+
return { meta, body: t.slice(m[0].length) };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function stripEstimate(body) {
|
|
24
|
+
const s = body.indexOf(EST_START);
|
|
25
|
+
if (s === -1) return body;
|
|
26
|
+
const e = body.indexOf(EST_END, s);
|
|
27
|
+
return e === -1 ? body.slice(0, s) : body.slice(0, s) + body.slice(e + EST_END.length);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// The digest covers only the human/agent-authored plan text: no frontmatter, no generated estimate,
|
|
31
|
+
// normalized line endings and trailing whitespace. Any other edit produces a new version.
|
|
32
|
+
export function normalizeBody(body) {
|
|
33
|
+
return stripEstimate(body).replace(/\r\n?/g, '\n').split('\n').map((l) => l.replace(/\s+$/, '')).join('\n').trim() + '\n';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function digestOf(body) {
|
|
37
|
+
return sha256Hex(normalizeBody(body));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function titleOf(body) {
|
|
41
|
+
const h = body.match(/^#\s+(.+)$/m);
|
|
42
|
+
if (h) return h[1].trim();
|
|
43
|
+
const first = body.split('\n').find((l) => l.trim());
|
|
44
|
+
return (first || 'Untitled plan').replace(/^[#>*\-\s]+/, '').slice(0, 80);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const SKIP_HEADINGS = /^(context|summary|overview|background|goal|goals|notes?|risks?|open questions|verification|testing plan|out of scope)\b/i;
|
|
48
|
+
|
|
49
|
+
export function extractSteps(body) {
|
|
50
|
+
const lines = normalizeBody(body).split('\n');
|
|
51
|
+
// 1) top-level numbered list items, with indented continuation lines
|
|
52
|
+
const steps = [];
|
|
53
|
+
let cur = null;
|
|
54
|
+
for (const l of lines) {
|
|
55
|
+
const m = l.match(/^\s{0,3}(\d+)[.)]\s+(.+)$/);
|
|
56
|
+
if (m) { cur = { title: m[2].trim(), text: m[2] }; steps.push(cur); continue; }
|
|
57
|
+
if (cur && /^\s{2,}\S/.test(l)) { cur.text += '\n' + l.trim(); continue; }
|
|
58
|
+
if (cur && /^\s*$/.test(l)) continue;
|
|
59
|
+
cur = null;
|
|
60
|
+
}
|
|
61
|
+
if (steps.length) return steps;
|
|
62
|
+
// 2) ## / ### headings that are not context sections
|
|
63
|
+
let sec = null;
|
|
64
|
+
for (const l of lines) {
|
|
65
|
+
const m = l.match(/^#{2,4}\s+(.+)$/);
|
|
66
|
+
if (m) { sec = SKIP_HEADINGS.test(m[1].replace(/^(step\s*)?\d+[.:)]?\s*/i, '')) ? null : { title: m[1].trim(), text: m[1] }; if (sec) steps.push(sec); continue; }
|
|
67
|
+
if (sec) sec.text += '\n' + l;
|
|
68
|
+
}
|
|
69
|
+
if (steps.length) return steps;
|
|
70
|
+
// 3) top-level bullets
|
|
71
|
+
for (const l of lines) { const m = l.match(/^[-*]\s+(.+)$/); if (m) steps.push({ title: m[1].trim(), text: m[1] }); }
|
|
72
|
+
if (steps.length) return steps;
|
|
73
|
+
return [{ title: titleOf(body), text: body }];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function renderPlanFile({ id, title, author, source, created, body, estimateMd }) {
|
|
77
|
+
const fm = ['---', `id: ${id}`, `title: "${String(title).replace(/"/g, "'")}"`];
|
|
78
|
+
if (author) fm.push(`author: ${author}`);
|
|
79
|
+
if (source) fm.push(`source: ${source}`);
|
|
80
|
+
if (created) fm.push(`created: ${created}`);
|
|
81
|
+
fm.push('---', '');
|
|
82
|
+
const clean = stripEstimate(body).replace(/\s+$/, '');
|
|
83
|
+
return fm.join('\n') + clean + '\n\n' + EST_START + '\n' + estimateMd.trim() + '\n' + EST_END + '\n';
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function readPlanText(text, fallbackId) {
|
|
87
|
+
const { meta, body } = splitFrontmatter(text);
|
|
88
|
+
const digest = digestOf(body);
|
|
89
|
+
return { id: meta.id || fallbackId, title: meta.title || titleOf(body), meta, body, digest, short: digest.slice(0, 8) };
|
|
90
|
+
}
|
package/src/policy.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { autoApproveVerdict } from './estimate.js';
|
|
2
|
+
import { budgetRule } from './models.js';
|
|
3
|
+
|
|
4
|
+
// Commands, one per line, in a PR comment or review body:
|
|
5
|
+
// /lake approve <plan-id>@<digest-prefix>
|
|
6
|
+
// /lake reject <plan-id>@<digest-prefix> (request changes; blocks until the same person approves)
|
|
7
|
+
// /lake revoke <plan-id> (withdraw your approval of any version)
|
|
8
|
+
const CMD = /^\s*\/lake\s+(approve|reject|revoke)\b[ \t]*([^\s@]+)?(?:@([0-9a-f]{7,64}))?/gim;
|
|
9
|
+
|
|
10
|
+
export function parseCommands(body) {
|
|
11
|
+
const out = [];
|
|
12
|
+
for (const m of String(body || '').matchAll(CMD)) out.push({ action: m[1].toLowerCase(), id: m[2] || null, digest: m[3] ? m[3].toLowerCase() : null });
|
|
13
|
+
return out;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// events: [{ login, type: 'User'|'Bot', association, body, createdAt, source: 'comment'|'review' }]
|
|
17
|
+
export function evaluatePlan({ plan, estimate, events, prAuthor, config, budgetApprovers }) {
|
|
18
|
+
const approvals = new Map();
|
|
19
|
+
const blockers = new Map();
|
|
20
|
+
const notes = [];
|
|
21
|
+
const sorted = [...events].sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
|
|
22
|
+
for (const ev of sorted) {
|
|
23
|
+
for (const c of parseCommands(ev.body)) {
|
|
24
|
+
if (c.id && c.id !== plan.id) continue;
|
|
25
|
+
if (!c.id) { notes.push(`@${ev.login}: "/lake ${c.action}" needs a plan id, e.g. /lake ${c.action} ${plan.id}@${plan.short}`); continue; }
|
|
26
|
+
const who = ev.login;
|
|
27
|
+
const ineligible =
|
|
28
|
+
ev.type === 'Bot' ? 'bots and agents cannot approve' :
|
|
29
|
+
prAuthor && who.toLowerCase() === prAuthor.toLowerCase() ? 'the plan author cannot approve their own plan' :
|
|
30
|
+
(config.ignoreLogins || []).some((x) => x.toLowerCase() === who.toLowerCase()) ? 'listed in ignoreLogins' :
|
|
31
|
+
!config.allowedAssociations.includes(ev.association) ? `association ${ev.association} lacks write access` : null;
|
|
32
|
+
if (c.action === 'revoke') { approvals.delete(who); continue; }
|
|
33
|
+
if (ineligible) { notes.push(`ignored ${c.action} from @${who}: ${ineligible}`); continue; }
|
|
34
|
+
const matches = c.digest && plan.digest.startsWith(c.digest);
|
|
35
|
+
if (!matches) { notes.push(`ignored ${c.action} from @${who}: ${c.digest ? `refers to version ${c.digest.slice(0, 8)}, current is ${plan.short}` : 'missing version'} (edits invalidate approval)`); continue; }
|
|
36
|
+
if (c.action === 'approve') { approvals.set(who, ev.createdAt); blockers.delete(who); }
|
|
37
|
+
else { blockers.set(who, ev.createdAt); approvals.delete(who); }
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const auto = estimate ? autoApproveVerdict(estimate, config) : { eligible: false, mode: 'off', reasons: [] };
|
|
41
|
+
// Budget: above config.budget.approverAbove one of the budget approvers must approve this exact version too
|
|
42
|
+
// (their approval also counts toward requiredApprovals).
|
|
43
|
+
const rule = estimate ? budgetRule(estimate, config, budgetApprovers) : { required: false };
|
|
44
|
+
const lc = (x) => String(x).toLowerCase();
|
|
45
|
+
const budgetBy = rule.required ? [...approvals.keys()].filter((a) => rule.approvers.some((b) => lc(b) === lc(a))) : [];
|
|
46
|
+
const budget = rule.required ? { ...rule, approvedBy: budgetBy, satisfied: budgetBy.length > 0 } : { required: false, satisfied: true };
|
|
47
|
+
let state;
|
|
48
|
+
if (blockers.size) state = 'changes-requested';
|
|
49
|
+
else if (approvals.size >= config.requiredApprovals && budget.satisfied) state = 'approved';
|
|
50
|
+
else if (approvals.size >= config.requiredApprovals) state = 'needs-budget';
|
|
51
|
+
else if (auto.mode === 'on' && auto.eligible && !budget.required) state = 'auto-approved';
|
|
52
|
+
else state = 'pending';
|
|
53
|
+
return { id: plan.id, digest: plan.digest, short: plan.short, state, approvers: [...approvals.keys()], blockers: [...blockers.keys()], auto, notes, budget,
|
|
54
|
+
needed: Math.max(0, config.requiredApprovals - approvals.size) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const isPassing = (r) => r.state === 'approved' || r.state === 'auto-approved';
|