lake-gate 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -21
- package/action.yml +1 -1
- package/package.json +42 -10
- package/src/action.js +47 -1
- package/src/cli.js +34 -6
- package/src/config-core.js +38 -0
- package/src/config.js +2 -44
- package/src/estimate.js +33 -45
- package/src/github.js +81 -16
- package/src/hook.js +13 -5
- package/src/index.js +1 -0
- package/src/init.js +23 -3
- package/src/mcp.js +313 -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/templates/lake-gate.yml +1 -1
- 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
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { sha256Hex } from './sha256.js';
|
|
2
2
|
|
|
3
3
|
export const EST_START = '<!-- lake:estimate:start (generated, not part of the approved digest) -->';
|
|
4
4
|
export const EST_END = '<!-- lake:estimate:end -->';
|
|
@@ -34,7 +34,7 @@ export function normalizeBody(body) {
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
export function digestOf(body) {
|
|
37
|
-
return
|
|
37
|
+
return sha256Hex(normalizeBody(body));
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
export function titleOf(body) {
|
package/src/policy.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { autoApproveVerdict } from './estimate.js';
|
|
2
|
+
import { budgetRule } from './models.js';
|
|
2
3
|
|
|
3
4
|
// Commands, one per line, in a PR comment or review body:
|
|
4
5
|
// /lake approve <plan-id>@<digest-prefix>
|
|
@@ -13,7 +14,7 @@ export function parseCommands(body) {
|
|
|
13
14
|
}
|
|
14
15
|
|
|
15
16
|
// events: [{ login, type: 'User'|'Bot', association, body, createdAt, source: 'comment'|'review' }]
|
|
16
|
-
export function evaluatePlan({ plan, estimate, events, prAuthor, config }) {
|
|
17
|
+
export function evaluatePlan({ plan, estimate, events, prAuthor, config, budgetApprovers }) {
|
|
17
18
|
const approvals = new Map();
|
|
18
19
|
const blockers = new Map();
|
|
19
20
|
const notes = [];
|
|
@@ -37,12 +38,19 @@ export function evaluatePlan({ plan, estimate, events, prAuthor, config }) {
|
|
|
37
38
|
}
|
|
38
39
|
}
|
|
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 };
|
|
40
47
|
let state;
|
|
41
48
|
if (blockers.size) state = 'changes-requested';
|
|
42
|
-
else if (approvals.size >= config.requiredApprovals) state = 'approved';
|
|
43
|
-
else if (
|
|
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';
|
|
44
52
|
else state = 'pending';
|
|
45
|
-
return { id: plan.id, digest: plan.digest, short: plan.short, state, approvers: [...approvals.keys()], blockers: [...blockers.keys()], auto, notes,
|
|
53
|
+
return { id: plan.id, digest: plan.digest, short: plan.short, state, approvers: [...approvals.keys()], blockers: [...blockers.keys()], auto, notes, budget,
|
|
46
54
|
needed: Math.max(0, config.requiredApprovals - approvals.size) };
|
|
47
55
|
}
|
|
48
56
|
|
package/src/review.js
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
// Review model: plan versions (rounds), anchored comment threads, verdicts and an activity timeline.
|
|
2
|
+
// Pure and browser-safe. The source of truth stays on the PR: every comment, reply, resolve and verdict
|
|
3
|
+
// is an ordinary PR comment carrying a small hidden marker, so it survives without any Lake server and
|
|
4
|
+
// is readable by humans on GitHub. Native GitHub line comments on the plan file and native PR reviews
|
|
5
|
+
// (Approve / Request changes) are mapped into the same model.
|
|
6
|
+
import { readPlanText, splitFrontmatter, stripEstimate } from './plan.js';
|
|
7
|
+
import { estimatePlan } from './estimate.js';
|
|
8
|
+
import { costSuggestions, modelOptions } from './models.js';
|
|
9
|
+
import { evaluatePlan, parseCommands } from './policy.js';
|
|
10
|
+
|
|
11
|
+
const MARK = /<!--\s*lake:(c|resolve|v|proxy)\s+(\{[\s\S]*?\})\s*-->/g;
|
|
12
|
+
export const PROXY_LOGIN = 'github-actions[bot]';
|
|
13
|
+
|
|
14
|
+
export function encodeMarker(kind, data) {
|
|
15
|
+
// "--" can't appear inside an HTML comment; JSON-escape it.
|
|
16
|
+
return `<!-- lake:${kind} ${JSON.stringify(data).replace(/--/g, '\\u002d\\u002d')} -->`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function parseMarkers(body) {
|
|
20
|
+
const out = [];
|
|
21
|
+
for (const m of String(body || '').matchAll(MARK)) {
|
|
22
|
+
try { out.push({ kind: m[1], data: JSON.parse(m[2]) }); } catch { /* ignore broken marker */ }
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const CMD_LINE = /^\s*\/lake\s+(approve|reject|revoke)\b.*$/gim;
|
|
28
|
+
// Human text of a comment: no markers, no /lake command lines, no quoted anchor preview we generated.
|
|
29
|
+
export function messageOf(body) {
|
|
30
|
+
return String(body || '').replace(MARK, '').replace(CMD_LINE, '')
|
|
31
|
+
.replace(/^<sub>.*lake-gate.*<\/sub>$/gim, '')
|
|
32
|
+
.replace(/^\*\*(Comment on|Reply on|Resolved|Reopened|Suggestion on|Accepted suggestion) [^\n]*\*\*.*$/gim, '')
|
|
33
|
+
.replace(/^>.*$/gm, '').trim();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const shortOf = (d) => String(d || '').slice(0, 8);
|
|
37
|
+
export function newId(n = 8) {
|
|
38
|
+
const a = 'abcdefghijkmnpqrstuvwxyz23456789';
|
|
39
|
+
let s = ''; for (let i = 0; i < n; i++) s += a[Math.floor(Math.random() * a.length)];
|
|
40
|
+
return s;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const quoteBlock = (q) => String(q || '').split('\n').slice(0, 4).map((l) => `> ${l}`).join('\n');
|
|
44
|
+
const footer = (via) => `<sub>via lake-gate${via ? ` · ${via}` : ''}</sub>`;
|
|
45
|
+
|
|
46
|
+
// ---- Bodies that the UI, the MCP server and the CLI post to the PR ----
|
|
47
|
+
export function commentBody({ planId, version, anchor, text, thread = newId(), via }) {
|
|
48
|
+
const where = anchor?.heading ? ` · ${anchor.heading}` : anchor ? ` · line ${anchor.start}${anchor.end > anchor.start ? `–${anchor.end}` : ''}` : '';
|
|
49
|
+
return [`**Comment on \`${planId}\` v${shortOf(version)}${where}**`, anchor?.quote ? quoteBlock(anchor.quote) : null, '', String(text).trim(), '', footer(via),
|
|
50
|
+
encodeMarker('c', { p: planId, v: shortOf(version), t: thread, ...(anchor ? { a: { s: anchor.start, e: anchor.end || anchor.start, q: String(anchor.quote || '').slice(0, 300), h: anchor.heading || undefined } } : {}) })]
|
|
51
|
+
.filter((x) => x !== null).join('\n');
|
|
52
|
+
}
|
|
53
|
+
// A structured suggestion (model change, cheaper steps, cap, drop a step). The author applies it in one click,
|
|
54
|
+
// which commits a new plan version; the thread then shows as accepted.
|
|
55
|
+
export function suggestionBody({ planId, version, title, patch, saving, text, thread = newId(), via, anchor }) {
|
|
56
|
+
const save = saving && saving[1] > 0.005 ? ` · saves up to $${saving[1] < 10 ? saving[1].toFixed(2) : Math.round(saving[1])}` : '';
|
|
57
|
+
return [`**Suggestion on \`${planId}\` v${shortOf(version)}: ${String(title).replace(/\*/g, '')}**${save}`, '', text ? String(text).trim() : null, text ? '' : null, footer(via),
|
|
58
|
+
encodeMarker('c', { p: planId, v: shortOf(version), t: thread, s: { title: String(title).slice(0, 140), patch, save: saving || null }, ...(anchor ? { a: { s: anchor.start, e: anchor.end || anchor.start, q: String(anchor.quote || '').slice(0, 300) } } : {}) })]
|
|
59
|
+
.filter((x) => x !== null).join('\n');
|
|
60
|
+
}
|
|
61
|
+
export function acceptBody({ planId, thread, title, newVersion, via }) {
|
|
62
|
+
return [`**Accepted suggestion on \`${planId}\`: ${String(title || '').replace(/\*/g, '')}** → v${shortOf(newVersion)}`, '', 'This is a new plan version, so earlier approvals no longer apply.', '', footer(via),
|
|
63
|
+
encodeMarker('resolve', { p: planId, t: thread, r: true, acc: 1, nv: shortOf(newVersion) })].join('\n');
|
|
64
|
+
}
|
|
65
|
+
export function replyBody({ planId, thread, text, via }) {
|
|
66
|
+
return [`**Reply on \`${planId}\`**`, '', String(text).trim(), '', footer(via), encodeMarker('c', { p: planId, t: thread, re: 1 })].join('\n');
|
|
67
|
+
}
|
|
68
|
+
export function resolveBody({ planId, thread, resolved = true, text, via }) {
|
|
69
|
+
return [`**${resolved ? 'Resolved' : 'Reopened'} a thread on \`${planId}\`**`, text ? `\n${String(text).trim()}` : null, '', footer(via), encodeMarker('resolve', { p: planId, t: thread, r: resolved })]
|
|
70
|
+
.filter((x) => x !== null).join('\n');
|
|
71
|
+
}
|
|
72
|
+
// approve | reject. The /lake line is what lake-gate's policy counts; the rest is the reviewer's note.
|
|
73
|
+
export function verdictBody({ action, planId, version, text, via, resolves = [] }) {
|
|
74
|
+
const cmd = action === 'approve' ? 'approve' : 'reject';
|
|
75
|
+
return [`/lake ${cmd} ${planId}@${shortOf(version)}`, text && String(text).trim() ? `\n${String(text).trim()}` : null, '', footer(via),
|
|
76
|
+
via ? encodeMarker('v', { via }) : null, ...resolves.map((t) => encodeMarker('resolve', { p: planId, t, r: true }))].filter((x) => x !== null).join('\n');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ---- Normalizing GitHub REST objects ----
|
|
80
|
+
export function normalizeIssueComment(c) {
|
|
81
|
+
return { id: `c${c.id}`, ghId: c.id, source: 'comment', login: c.user.login, type: c.user.type, association: c.author_association, body: c.body || '', createdAt: c.created_at, url: c.html_url };
|
|
82
|
+
}
|
|
83
|
+
export function normalizeReview(r) {
|
|
84
|
+
return { id: `r${r.id}`, ghId: r.id, source: 'review', login: r.user.login, type: r.user.type, association: r.author_association, body: r.body || '', createdAt: r.submitted_at, state: r.state, commitId: r.commit_id, url: r.html_url };
|
|
85
|
+
}
|
|
86
|
+
export function normalizeLineComment(c) {
|
|
87
|
+
return { id: `l${c.id}`, ghId: c.id, source: 'line', login: c.user.login, type: c.user.type, association: c.author_association, body: c.body || '', createdAt: c.created_at,
|
|
88
|
+
path: c.path, line: c.line ?? c.original_line, startLine: c.start_line ?? c.original_start_line ?? null, commitId: c.original_commit_id || c.commit_id, inReplyTo: c.in_reply_to_id ? `l${c.in_reply_to_id}` : null, url: c.html_url };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// One plan file at one commit.
|
|
92
|
+
export function versionFromText(text, { sha = null, at = null, author = null, fallbackId } = {}) {
|
|
93
|
+
const p = readPlanText(text, fallbackId);
|
|
94
|
+
const fm = String(text).replace(/\r\n?/g, '\n').match(/^---\n[\s\S]*?\n---\n?/);
|
|
95
|
+
return { id: p.id, title: p.title, digest: p.digest, short: p.short, body: p.body, meta: p.meta, offset: fm ? fm[0].split('\n').length - 1 : 0, sha, at, author };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Chronological unique versions from a list of {text, sha, at, author} snapshots.
|
|
99
|
+
export function versionsFromSnapshots(snaps, fallbackId) {
|
|
100
|
+
const out = [];
|
|
101
|
+
for (const s of snaps) {
|
|
102
|
+
if (s.text == null) continue;
|
|
103
|
+
const v = versionFromText(s.text, { ...s, fallbackId });
|
|
104
|
+
if (!out.length || out[out.length - 1].digest !== v.digest) {
|
|
105
|
+
if (!out.some((o) => o.digest === v.digest)) out.push(v);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const NATIVE = { APPROVED: 'approve', CHANGES_REQUESTED: 'reject' };
|
|
112
|
+
|
|
113
|
+
// Makes the event list policy-ready for ONE plan:
|
|
114
|
+
// - a native GitHub review (Approve / Request changes) without a /lake line counts for the plan version at the reviewed commit;
|
|
115
|
+
// - a check-button click relayed by the Action (bot comment with a proxy marker) counts as the clicking user.
|
|
116
|
+
export function expandEvents(events, { planId, digestAt = {}, config = {} }) {
|
|
117
|
+
const out = [];
|
|
118
|
+
for (const ev of events) {
|
|
119
|
+
if (ev.source === 'line') continue;
|
|
120
|
+
let e = ev;
|
|
121
|
+
const proxy = parseMarkers(ev.body).find((m) => m.kind === 'proxy');
|
|
122
|
+
if (proxy && ev.login === PROXY_LOGIN && ev.type === 'Bot' && proxy.data.by) {
|
|
123
|
+
e = { ...ev, login: proxy.data.by, type: 'User', association: proxy.data.assoc || 'NONE', via: 'GitHub check button' };
|
|
124
|
+
}
|
|
125
|
+
if (config.nativeReviews !== false && ev.source === 'review' && NATIVE[ev.state] && !parseCommands(ev.body).length) {
|
|
126
|
+
const d = ev.commitId && digestAt[ev.commitId];
|
|
127
|
+
if (d) e = { ...e, body: `/lake ${NATIVE[ev.state]} ${planId}@${d}\n${ev.body || ''}`, via: 'GitHub review', native: true };
|
|
128
|
+
}
|
|
129
|
+
out.push(e);
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ---- Diff ----
|
|
135
|
+
export function lineDiff(a, b) {
|
|
136
|
+
const A = clean(a).split('\n'); const B = clean(b).split('\n');
|
|
137
|
+
const n = A.length; const m = B.length;
|
|
138
|
+
const L = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
|
|
139
|
+
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = A[i] === B[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
|
|
140
|
+
const out = []; let i = 0; let j = 0;
|
|
141
|
+
while (i < n && j < m) {
|
|
142
|
+
if (A[i] === B[j]) { out.push({ op: 'same', text: A[i], a: i + 1, b: j + 1 }); i++; j++; }
|
|
143
|
+
else if (L[i + 1][j] >= L[i][j + 1]) { out.push({ op: 'del', text: A[i], a: i + 1 }); i++; }
|
|
144
|
+
else { out.push({ op: 'add', text: B[j], b: j + 1 }); j++; }
|
|
145
|
+
}
|
|
146
|
+
while (i < n) { out.push({ op: 'del', text: A[i], a: i + 1 }); i++; }
|
|
147
|
+
while (j < m) { out.push({ op: 'add', text: B[j], b: j + 1 }); j++; }
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
function clean(body) { return stripEstimate(String(body)).replace(/\s+$/, ''); }
|
|
151
|
+
|
|
152
|
+
// Word-level spans for a changed line pair: [{op:'same'|'add'|'del', text}]
|
|
153
|
+
export function wordDiff(a, b) {
|
|
154
|
+
const A = a.split(/(\s+)/); const B = b.split(/(\s+)/);
|
|
155
|
+
const n = A.length; const m = B.length;
|
|
156
|
+
if (n * m > 40000) return [{ op: 'del', text: a }, { op: 'add', text: b }];
|
|
157
|
+
const L = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
|
|
158
|
+
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = A[i] === B[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
|
|
159
|
+
const out = []; let i = 0; let j = 0;
|
|
160
|
+
const push = (op, text) => { const last = out[out.length - 1]; if (last && last.op === op) last.text += text; else out.push({ op, text }); };
|
|
161
|
+
while (i < n && j < m) {
|
|
162
|
+
if (A[i] === B[j]) { push('same', A[i]); i++; j++; } else if (L[i + 1][j] >= L[i][j + 1]) { push('del', A[i]); i++; } else { push('add', B[j]); j++; }
|
|
163
|
+
}
|
|
164
|
+
while (i < n) push('del', A[i++]);
|
|
165
|
+
while (j < m) push('add', B[j++]);
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function diffStats(diff) {
|
|
170
|
+
return { added: diff.filter((d) => d.op === 'add').length, removed: diff.filter((d) => d.op === 'del').length };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Where does an anchor (from an older version) land in another version's body? null = outdated.
|
|
174
|
+
export function relocateAnchor(anchor, body) {
|
|
175
|
+
if (!anchor) return null;
|
|
176
|
+
const lines = String(body).split('\n');
|
|
177
|
+
const q = String(anchor.quote || '').trim();
|
|
178
|
+
if (!q) return anchor.start <= lines.length ? { start: anchor.start, end: anchor.end } : null;
|
|
179
|
+
const first = q.split('\n')[0].trim().replace(/^([-*+]|\d+[.)])\s+/, '');
|
|
180
|
+
const hits = [];
|
|
181
|
+
lines.forEach((l, i) => { if (l.includes(first)) hits.push(i + 1); });
|
|
182
|
+
if (!hits.length) return null;
|
|
183
|
+
const best = hits.reduce((a, h) => (Math.abs(h - anchor.start) < Math.abs(a - anchor.start) ? h : a), hits[0]);
|
|
184
|
+
return { start: best, end: best + (anchor.end - anchor.start) };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function headingFor(body, line) {
|
|
188
|
+
const lines = String(body).split('\n');
|
|
189
|
+
for (let i = Math.min(line, lines.length) - 1; i >= 0; i--) { const m = lines[i].match(/^#{1,4}\s+(.+)$/); if (m) return m[1].trim(); }
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ---- The model ----
|
|
194
|
+
// plan: current plan ({id, title, body, digest, short, meta}); versions: chronological [{digest, body, at, sha, author, offset}]
|
|
195
|
+
// events: normalized events (comments, reviews, line comments); digestAt: {commitSha: digest} for this plan's file
|
|
196
|
+
export function buildPlanReview({ plan, versions = [], events = [], prAuthor = null, config, digestAt = {}, pr = null, requestedReviewers = [], budgetApprovers }) {
|
|
197
|
+
const vs = versions.length ? [...versions] : [];
|
|
198
|
+
if (!vs.some((v) => v.digest === plan.digest)) vs.push({ ...plan, offset: plan.offset || 0, at: plan.at || null, author: plan.author || null });
|
|
199
|
+
const byPrefix = (p) => (p ? vs.find((v) => v.digest.startsWith(String(p).toLowerCase())) : null);
|
|
200
|
+
const vIndex = (d) => vs.findIndex((v) => v.digest === d);
|
|
201
|
+
const current = vs[vIndex(plan.digest)];
|
|
202
|
+
const estimate = estimatePlan(plan.body, config);
|
|
203
|
+
const expanded = expandEvents(events, { planId: plan.id, digestAt, config });
|
|
204
|
+
const policy = evaluatePlan({ plan, estimate, events: expanded, prAuthor, config, budgetApprovers });
|
|
205
|
+
const sorted = [...events].sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
|
|
206
|
+
const expandedById = new Map(expanded.map((e) => [e.id, e]));
|
|
207
|
+
|
|
208
|
+
const verdicts = []; const threads = new Map(); const timeline = []; const resolves = [];
|
|
209
|
+
const planPath = `.lake/plans/${plan.id}.md`;
|
|
210
|
+
|
|
211
|
+
for (const raw of sorted) {
|
|
212
|
+
const ev = expandedById.get(raw.id) || raw;
|
|
213
|
+
const markers = parseMarkers(raw.body);
|
|
214
|
+
const viaMarker = markers.find((m) => m.kind === 'v');
|
|
215
|
+
// verdicts
|
|
216
|
+
for (const c of parseCommands(ev.body)) {
|
|
217
|
+
if (c.id !== plan.id) continue;
|
|
218
|
+
const v = byPrefix(c.digest);
|
|
219
|
+
const item = { login: ev.login, action: c.action, version: v ? v.digest : null, short: v ? v.short : shortOf(c.digest), n: v ? vIndex(v.digest) + 1 : null,
|
|
220
|
+
text: messageOf(raw.body), at: ev.createdAt, via: ev.via || viaMarker?.data.via || (raw.source === 'review' ? 'GitHub review' : 'PR comment'),
|
|
221
|
+
self: !!(prAuthor && ev.login.toLowerCase() === prAuthor.toLowerCase()), bot: ev.type === 'Bot', url: raw.url, eventId: raw.id };
|
|
222
|
+
verdicts.push(item);
|
|
223
|
+
timeline.push({ kind: c.action, login: item.login, at: item.at, short: item.short, n: item.n, text: item.text, via: item.via, self: item.self });
|
|
224
|
+
}
|
|
225
|
+
// Lake marker threads
|
|
226
|
+
for (const m of markers) {
|
|
227
|
+
if (m.data.p !== plan.id) continue;
|
|
228
|
+
if (m.kind === 'c' && !m.data.re && m.data.t) {
|
|
229
|
+
const v = byPrefix(m.data.v) || current;
|
|
230
|
+
const a = m.data.a ? { start: m.data.a.s, end: m.data.a.e ?? m.data.a.s, quote: m.data.a.q || '', heading: m.data.a.h || headingFor(v.body, m.data.a.s) } : null;
|
|
231
|
+
threads.set(m.data.t, { id: m.data.t, version: v.digest, short: v.short, n: vIndex(v.digest) + 1, anchor: a, comments: [], resolved: false, resolvedBy: null, source: 'lake',
|
|
232
|
+
suggestion: m.data.s ? { title: String(m.data.s.title || ''), patch: m.data.s.patch, saving: m.data.s.save || null, by: raw.login, accepted: false } : null });
|
|
233
|
+
threads.get(m.data.t).comments.push({ login: raw.login, text: messageOf(raw.body), at: raw.createdAt, id: raw.id, url: raw.url });
|
|
234
|
+
timeline.push({ kind: 'comment', login: raw.login, at: raw.createdAt, short: v.short, n: vIndex(v.digest) + 1, text: messageOf(raw.body), thread: m.data.t, where: a?.heading || null });
|
|
235
|
+
} else if (m.kind === 'c' && m.data.re && threads.has(m.data.t)) {
|
|
236
|
+
threads.get(m.data.t).comments.push({ login: raw.login, text: messageOf(raw.body), at: raw.createdAt, id: raw.id, url: raw.url });
|
|
237
|
+
timeline.push({ kind: 'reply', login: raw.login, at: raw.createdAt, text: messageOf(raw.body), thread: m.data.t });
|
|
238
|
+
} else if (m.kind === 'resolve') {
|
|
239
|
+
resolves.push({ t: m.data.t, r: m.data.r !== false, login: raw.login, at: raw.createdAt, acc: !!m.data.acc, nv: m.data.nv || null });
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
// Native GitHub line comments on the plan file
|
|
243
|
+
if (raw.source === 'line' && raw.path === planPath) {
|
|
244
|
+
if (!raw.inReplyTo) {
|
|
245
|
+
const v = (raw.commitId && byPrefix(digestAt[raw.commitId])) || current;
|
|
246
|
+
const start = Math.max(1, (raw.startLine || raw.line) - (v.offset || 0)); const end = Math.max(start, raw.line - (v.offset || 0));
|
|
247
|
+
const quote = String(v.body).split('\n').slice(start - 1, end).join('\n');
|
|
248
|
+
threads.set(raw.id, { id: raw.id, version: v.digest, short: v.short, n: vIndex(v.digest) + 1, anchor: { start, end, quote, heading: headingFor(v.body, start) }, comments: [], resolved: false, resolvedBy: null, source: 'github' });
|
|
249
|
+
timeline.push({ kind: 'comment', login: raw.login, at: raw.createdAt, short: v.short, n: vIndex(v.digest) + 1, text: raw.body, thread: raw.id, where: headingFor(v.body, start) });
|
|
250
|
+
} else if (threads.has(raw.inReplyTo)) timeline.push({ kind: 'reply', login: raw.login, at: raw.createdAt, text: raw.body, thread: raw.inReplyTo });
|
|
251
|
+
const t = threads.get(raw.inReplyTo || raw.id);
|
|
252
|
+
if (t) t.comments.push({ login: raw.login, text: raw.body, at: raw.createdAt, id: raw.id, url: raw.url });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
for (const r of resolves) {
|
|
256
|
+
const t = threads.get(r.t); if (!t) continue;
|
|
257
|
+
t.resolved = r.r; t.resolvedBy = r.r ? r.login : null; t.resolvedAt = r.r ? r.at : null;
|
|
258
|
+
if (t.suggestion && r.acc) { t.suggestion = { ...t.suggestion, accepted: true, acceptedBy: r.login, newVersion: r.nv }; timeline.push({ kind: 'accept', login: r.login, at: r.at, thread: r.t, text: t.suggestion.title, short: r.nv }); continue; }
|
|
259
|
+
timeline.push({ kind: r.r ? 'resolve' : 'reopen', login: r.login, at: r.at, thread: r.t });
|
|
260
|
+
}
|
|
261
|
+
// Where each thread sits on the current version
|
|
262
|
+
const allThreads = [...threads.values()].map((t) => {
|
|
263
|
+
if (t.version === plan.digest) return { ...t, outdated: false, current: t.anchor ? { start: t.anchor.start, end: t.anchor.end } : null };
|
|
264
|
+
const loc = relocateAnchor(t.anchor, plan.body);
|
|
265
|
+
return { ...t, outdated: !loc && !!t.anchor, current: loc };
|
|
266
|
+
});
|
|
267
|
+
for (const v of vs) timeline.push({ kind: 'version', login: v.author || null, at: v.at, short: v.short, n: vIndex(v.digest) + 1 });
|
|
268
|
+
timeline.sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')));
|
|
269
|
+
|
|
270
|
+
// Reviewers: latest verdict per person; people asked to review but silent are "waiting"
|
|
271
|
+
const reviewers = new Map();
|
|
272
|
+
for (const r of requestedReviewers) reviewers.set(r, { login: r, verdict: 'waiting', at: null, current: false });
|
|
273
|
+
for (const v of verdicts) {
|
|
274
|
+
if (v.self || v.bot) continue;
|
|
275
|
+
if (v.action === 'revoke') { reviewers.set(v.login, { login: v.login, verdict: 'revoked', at: v.at, current: false }); continue; }
|
|
276
|
+
reviewers.set(v.login, { login: v.login, verdict: v.action === 'approve' ? 'approved' : 'changes-requested', at: v.at, short: v.short, n: v.n, current: v.version === plan.digest, text: v.text, via: v.via });
|
|
277
|
+
}
|
|
278
|
+
if (policy.budget?.required) {
|
|
279
|
+
for (const b of policy.budget.approvers) {
|
|
280
|
+
if (prAuthor && b.toLowerCase() === prAuthor.toLowerCase()) continue;
|
|
281
|
+
const r = reviewers.get(b);
|
|
282
|
+
reviewers.set(b, { ...(r || { login: b, verdict: 'waiting', at: null, current: false }), budget: true });
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
for (const t of allThreads) for (const c of t.comments) {
|
|
286
|
+
if (c.login === prAuthor) continue;
|
|
287
|
+
const r = reviewers.get(c.login);
|
|
288
|
+
if (!r) reviewers.set(c.login, { login: c.login, verdict: 'commented', at: c.at, current: false });
|
|
289
|
+
else if (r.verdict === 'waiting') reviewers.set(c.login, { ...r, verdict: 'commented', at: c.at });
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const rounds = vs.map((v, i) => {
|
|
293
|
+
const vv = verdicts.filter((x) => x.version === v.digest);
|
|
294
|
+
const isCur = v.digest === plan.digest;
|
|
295
|
+
let outcome = isCur ? policy.state : vv.some((x) => x.action === 'reject') ? 'changes-requested' : vv.some((x) => x.action === 'approve') ? 'approved-then-edited' : 'superseded';
|
|
296
|
+
if (isCur && outcome === 'pending' && pr?.draft) outcome = 'draft';
|
|
297
|
+
const prev = vs[i - 1];
|
|
298
|
+
return { n: i + 1, digest: v.digest, short: v.short, at: v.at, author: v.author, sha: v.sha, current: isCur, verdicts: vv,
|
|
299
|
+
threads: allThreads.filter((t) => t.version === v.digest), estimate: estimatePlan(v.body, config), outcome, body: v.body,
|
|
300
|
+
stats: prev ? diffStats(lineDiff(prev.body, v.body)) : null };
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
const passing = policy.state === 'approved' || policy.state === 'auto-approved';
|
|
304
|
+
const status = passing ? policy.state : policy.state === 'changes-requested' ? 'changes-requested' : (!pr || pr.draft) ? 'draft' : policy.state === 'needs-budget' ? 'needs-budget' : 'in-review';
|
|
305
|
+
const last = timeline.filter((t) => t.at).slice(-1)[0];
|
|
306
|
+
return {
|
|
307
|
+
id: plan.id, title: plan.title, path: planPath, digest: plan.digest, short: plan.short, body: plan.body, meta: plan.meta || {},
|
|
308
|
+
author: prAuthor || plan.meta?.author || null, pr: pr ? { number: pr.number, title: pr.title, url: pr.html_url, draft: !!pr.draft, state: pr.merged_at ? 'merged' : pr.state, branch: pr.head?.ref } : null,
|
|
309
|
+
status, policy, estimate, rounds, round: rounds.length, threads: allThreads, verdicts, timeline, reviewers: [...reviewers.values()],
|
|
310
|
+
openThreads: allThreads.filter((t) => !t.resolved && !t.outdated).length, lastActivity: last ? last.at : null,
|
|
311
|
+
approveLine: `/lake approve ${plan.id}@${plan.short}`,
|
|
312
|
+
suggestions: costSuggestions(estimate, config).filter((x) => !allThreads.some((t) => t.suggestion && !t.resolved && t.version === plan.digest && JSON.stringify(t.suggestion.patch) === JSON.stringify(x.patch))),
|
|
313
|
+
modelOptions: modelOptions(estimate, config),
|
|
314
|
+
budget: policy.budget,
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export function sectionText(body) { return stripEstimate(String(body)); }
|
|
319
|
+
export { splitFrontmatter };
|
package/src/sha256.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Small synchronous SHA-256 (UTF-8 string in, hex out). Pure JS so the same plan digest code runs
|
|
2
|
+
// in Node, in the browser review UI and in the GitHub Action, with identical results.
|
|
3
|
+
const K = new Uint32Array([
|
|
4
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
|
5
|
+
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
6
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
|
7
|
+
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
8
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
|
9
|
+
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]);
|
|
10
|
+
|
|
11
|
+
export function sha256Hex(str) {
|
|
12
|
+
const bytes = new TextEncoder().encode(String(str));
|
|
13
|
+
const len = bytes.length;
|
|
14
|
+
const total = ((len + 9 + 63) >> 6) << 6;
|
|
15
|
+
const buf = new Uint8Array(total);
|
|
16
|
+
buf.set(bytes); buf[len] = 0x80;
|
|
17
|
+
const dv = new DataView(buf.buffer);
|
|
18
|
+
dv.setUint32(total - 8, Math.floor(len / 0x20000000)); dv.setUint32(total - 4, (len << 3) >>> 0);
|
|
19
|
+
const H = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
|
|
20
|
+
const W = new Uint32Array(64);
|
|
21
|
+
const rot = (x, n) => (x >>> n) | (x << (32 - n));
|
|
22
|
+
for (let off = 0; off < total; off += 64) {
|
|
23
|
+
for (let i = 0; i < 16; i++) W[i] = dv.getUint32(off + i * 4);
|
|
24
|
+
for (let i = 16; i < 64; i++) {
|
|
25
|
+
const a = W[i - 15], b = W[i - 2];
|
|
26
|
+
W[i] = (W[i - 16] + (rot(a, 7) ^ rot(a, 18) ^ (a >>> 3)) + W[i - 7] + (rot(b, 17) ^ rot(b, 19) ^ (b >>> 10))) >>> 0;
|
|
27
|
+
}
|
|
28
|
+
let [a, b, c, d, e, f, g, h] = H;
|
|
29
|
+
for (let i = 0; i < 64; i++) {
|
|
30
|
+
const t1 = (h + (rot(e, 6) ^ rot(e, 11) ^ rot(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + W[i]) >>> 0;
|
|
31
|
+
const t2 = ((rot(a, 2) ^ rot(a, 13) ^ rot(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
|
|
32
|
+
h = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;
|
|
33
|
+
}
|
|
34
|
+
H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h;
|
|
35
|
+
}
|
|
36
|
+
return [...H].map((x) => x.toString(16).padStart(8, '0')).join('');
|
|
37
|
+
}
|
package/src/store.js
CHANGED
|
@@ -78,7 +78,7 @@ export function exportPlan(root, markdown, { id, source, sessionId, author } = {
|
|
|
78
78
|
export function localStatus(root, plan, config = loadConfig(root)) {
|
|
79
79
|
const est = estimatePlan(plan.body, config);
|
|
80
80
|
const rec = getApprovals(root)[plan.id];
|
|
81
|
-
if (rec && rec.digest === plan.digest && (rec.state === 'approved' || rec.state === 'auto-approved')) return { state: rec.state, approvers: rec.approvers || [], estimate: est, synced: rec };
|
|
81
|
+
if (rec && rec.digest === plan.digest && (rec.state === 'approved' || rec.state === 'auto-approved')) return { state: rec.state, approvers: rec.approvers || [], estimate: est, synced: rec, trial: !!rec.trial };
|
|
82
82
|
if (rec && rec.digest === plan.digest && rec.state === 'changes-requested') return { state: 'changes-requested', approvers: [], blockers: rec.blockers, estimate: est, synced: rec };
|
|
83
83
|
const a = config.autoApprove || {};
|
|
84
84
|
if (a.mode === 'on') {
|