lake-gate 0.2.0 → 0.2.2

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 CHANGED
@@ -11,7 +11,7 @@ lake-gate is a small, free, open-source plan gate for teams using Claude Code an
11
11
  - **Review app.** Rendered plans, comments on exact lines, review rounds per plan version with a diff between them, verdicts and an activity timeline. Approve or request changes in one click. Run it locally with `npx lake-gate ui`, or use the hosted static app (it talks to the GitHub API straight from your browser). [Live demo with a made-up team](https://getlake.github.io/lake-gate/app/#/demo).
12
12
  - **Approve from where you already are.** The Lake review app, GitHub's own **Approve** button, or your agent chat (MCP server for Claude Code and Cursor). They all write to the same place, the PR, so there is one source of truth.
13
13
  - **Model and cost per step.** Every plan shows which model runs each step and what that costs, with the same estimator and price table as [lake-meter](https://getlake.github.io/lake-meter/). Declare the model in the plan (`Model: Opus 5.5`, or `(model: haiku)` on a step). Reviewers suggest a cheaper model, a dropped step or a cap, and the author accepts it in one click, which saves a new plan version.
14
- - **Budget approval (optional).** Above `budget.approverAbove` dollars, one of `budget.approvers` must also approve that exact version. It shows in the app, the PR check and the MCP tools.
14
+ - **Budget approval (optional).** Above `budget.approverAbove` dollars, one of `budget.approvers` (GitHub logins) must also approve that exact version. It shows in the app, the PR check and the MCP tools.
15
15
  - **Small plans pass on their own.** Tiny, low-complexity plans are auto-approved by default, and quick fixes without a plan aren't gated at all. Set `autoApprove.mode` to `shadow` or `off` to be stricter.
16
16
 
17
17
  ## Install (about 10 minutes)
@@ -95,6 +95,7 @@ It's a rough heuristic, the same one lake-meter uses: complexity from keywords,
95
95
  ```
96
96
  lake-gate init [--try] [--force] set up the repo (--try: local-only trial, self-approval allowed)
97
97
  lake-gate approve [id] approve your own plan (trial mode only)
98
+ lake-gate uninstall remove the hook, MCP entries and workflow (keeps .lake/)
98
99
  lake-gate plan <file.md|-> [--id name] save a plan with an estimate and make it active
99
100
  lake-gate estimate <file.md|-> print the estimate only
100
101
  lake-gate status plans, versions, approval state
@@ -119,7 +120,7 @@ lake-gate hook claude the Claude Code PreToolUse hook (stdin
119
120
  | `localGate` | `"block"` | Hook behaviour: `block` (deny), `ask` (Claude Code prompts you), `off` |
120
121
  | `readOnlyBash` | git status/log/diff, ls, cat, rg... | Bash commands allowed before approval (regexes; chained commands are not) |
121
122
  | `autoApprove` | `{mode:"on", maxUsd:1.5, maxSteps:3, maxComplexity:"low"}` | Tiny plans pass without a human. `off`, `shadow` (only report), or `on` |
122
- | `budget` | `{approverAbove:null, approvers:[]}` | Above this many dollars (upper estimate of the planned model), one of `approvers` (logins or `@org/team`) must also approve |
123
+ | `budget` | `{approverAbove:null, approvers:[]}` | Above this many dollars (upper estimate of the planned model), one of `approvers` must also approve. Use GitHub **logins**, e.g. `["alice","bob"]`. `@org/team` needs a token with `read:org`, which the default Action token doesn't have. When a team can't be read, the summary says so and repo admins can approve instead |
123
124
  | `gateWithoutPlan` | `false` | `true` blocks edits even when there's no plan |
124
125
  | `provider`, `catalog` | `anthropic`, lake-meter prices | Same shape as lake-meter's price catalog |
125
126
  | `nativeReviews` | `true` | GitHub's own Approve / Request changes count for the plan version at the reviewed commit |
package/action.yml CHANGED
@@ -6,7 +6,7 @@ branding:
6
6
  color: green
7
7
  inputs:
8
8
  token:
9
- description: GitHub token with statuses:write and issues:write (the default GITHUB_TOKEN works).
9
+ description: GitHub token with statuses:write and pull-requests:write (the default GITHUB_TOKEN works).
10
10
  required: false
11
11
  default: ${{ github.token }}
12
12
  comment:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lake-gate",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Version-bound team plan approval for AI coding agents: review UI, Claude Code hook, MCP server, GitHub Action. No backend, no telemetry.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import fs from 'node:fs';
2
2
  import { repoRoot, exportPlan, loadPlan, listPlans, getState, setState, localStatus, getApprovals, setApprovals } from './store.js';
3
3
  import { loadConfig } from './config.js';
4
- import { estimatePlan, renderEstimate, range } from './estimate.js';
4
+ import { estimatePlan, renderEstimate, range, costLabel } from './estimate.js';
5
5
  import { handleClaudePreToolUse } from './hook.js';
6
6
  import { syncFromGitHub, applyEvents } from './sync.js';
7
- import { init, ACTION_REF } from './init.js';
7
+ import { init, uninstall, ACTION_REF } from './init.js';
8
8
  import { startUi } from './ui-server.js';
9
9
  import { serve as serveMcp } from './mcp.js';
10
10
 
@@ -14,6 +14,7 @@ Usage:
14
14
  lake-gate init [--try] [--force] Set up .lake/, the Claude Code hook, MCP and the GitHub workflow
15
15
  --try: solo trial, approve your own plans locally
16
16
  lake-gate approve [id] Trial mode only: approve the active plan locally (never counts on the PR)
17
+ lake-gate uninstall Remove the hook, MCP entries and workflow (keeps .lake/ plans)
17
18
  lake-gate plan <file.md|-> [--id name] Save a plan (any agent) to .lake/plans/ with an estimate; make it active
18
19
  lake-gate estimate <file.md|-> Print complexity, model per step and cost range
19
20
  lake-gate status Active plan, version and approval state
@@ -31,9 +32,9 @@ const readInput = (f) => (f === '-' || !f ? fs.readFileSync(0, 'utf8') : fs.read
31
32
 
32
33
  function describe(root, plan) {
33
34
  const st = localStatus(root, plan);
34
- const extra = st.state === 'pending' ? (st.stale ? ' (approval is for an older version)' : '') + `\n approve on the PR: /lake approve ${plan.id}@${plan.short}` : st.approvers?.length ? ` by ${st.approvers.map((a) => '@' + a).join(', ')}` : '';
35
+ const extra = st.state === 'pending' ? (st.stale ? ' (approval is for an older version)' : '') + (loadConfig(root).try ? '\n approve locally: npx lake-gate approve' : `\n approve on the PR: /lake approve ${plan.id}@${plan.short}`) : st.approvers?.length ? ` by ${st.approvers.map((a) => '@' + a).join(', ')}` : '';
35
36
  const e = st.estimate;
36
- return `${plan.id} v${plan.short} ${e.complexity} est. ${range(e.declared ? e.plannedUsd : e.usd)}${e.model ? ` on ${e.model.name}` : ''} ${st.state}${st.trial ? ' (trial, local only)' : ''}${extra}`;
37
+ return `${plan.id} v${plan.short} ${e.complexity} est. ${costLabel(e)} ${st.state}${st.trial ? ' (trial, local only)' : ''}${extra}`;
37
38
  }
38
39
 
39
40
  export async function main(argv = process.argv.slice(2), io = { out: (s) => process.stdout.write(s + '\n'), err: (s) => process.stderr.write(s + '\n') }) {
@@ -47,10 +48,19 @@ export async function main(argv = process.argv.slice(2), io = { out: (s) => proc
47
48
  io.out(`${trial ? '' : '\nNext:\n'} git add .lake .claude .github .mcp.json .cursor && git commit -m "Add lake-gate" && git push\n Then review plans with: npx lake-gate ui (or in GitHub with Review changes → Approve)\n Optional: require the "lake/plan-approval" status check in branch protection.`);
48
49
  return 0;
49
50
  }
51
+ case 'uninstall': {
52
+ for (const l of uninstall(root)) io.out(l);
53
+ io.out('Kept .lake/ (your plans and config). Delete it yourself if you want it gone, then commit. Remove "lake/plan-approval" from required checks if you set it.');
54
+ return 0;
55
+ }
50
56
  case 'plan': {
51
- const { plan, estimate } = exportPlan(root, readInput(args.find((a) => !a.startsWith('--') && a !== flag(args, '--id'))), { id: flag(args, '--id'), source: 'cli' });
52
- io.out(`Saved .lake/plans/${plan.id}.md version ${plan.short} ${estimate.complexity} est. ${range(estimate.usd)}`);
53
- io.out(`Approve on the PR with: /lake approve ${plan.id}@${plan.short}`);
57
+ const { plan, estimate, config, previous, unchanged } = exportPlan(root, readInput(args.find((a) => !a.startsWith('--') && a !== flag(args, '--id'))), { id: flag(args, '--id'), source: 'cli', fresh: args.includes('--new') });
58
+ io.out(previous ? `Updated ${plan.id} → v${plan.short} (was v${previous.short}; approval reset) ${estimate.complexity} est. ${costLabel(estimate)}`
59
+ : `${unchanged ? 'Unchanged' : 'Saved'} .lake/plans/${plan.id}.md version ${plan.short} ${estimate.complexity} est. ${costLabel(estimate)}`);
60
+ const st = localStatus(root, plan, config);
61
+ if (st.state === 'approved' || st.state === 'auto-approved') io.out(st.state === 'auto-approved' ? 'Auto-approved (small plan). The agent can build.' : 'Approved. The agent can build.');
62
+ else if (config.try) io.out('Approve locally: npx lake-gate approve');
63
+ else io.out(`Approve on the PR with: /lake approve ${plan.id}@${plan.short}`);
54
64
  return 0;
55
65
  }
56
66
  case 'estimate': {
@@ -18,7 +18,8 @@ export const DEFAULT_CONFIG = {
18
18
  checkButtons: false, // experimental: Approve / Request changes buttons on a GitHub check run (needs checks: write)
19
19
  autoApprove: { mode: 'on', maxUsd: 1.5, maxSteps: 3, maxComplexity: 'low' }, // tiny plans pass without a human. mode: "off" | "shadow" | "on"
20
20
  // Budget approval: above approverAbove (USD, upper estimate or the plan's "Budget cap") one of approvers
21
- // (GitHub logins or "@org/team") must approve the exact version too. Off until you set both.
21
+ // must approve the exact version too. List GitHub logins, e.g. ["alice", "bob"]. "@org/team" needs a token with
22
+ // read:org, which the default Action token doesn't have (lake-gate then warns and lets repo admins approve).
22
23
  budget: { approverAbove: null, approvers: [], suggestAbove: 0, suggestCapAbove: 10 },
23
24
  catalog: {}, // extra models in lake-meter's prices.json shape, e.g. { "my-model": { "label": "My model", "tier": "standard", "input": 1, "cacheRead": 0.1, "output": 5 } }
24
25
  provider: 'anthropic', // model family for Lake's picks: "anthropic" | "openai". Prices: lake-meter's table (meter-core.js)
package/src/estimate.js CHANGED
@@ -35,8 +35,12 @@ export function estimatePlan(body, config) {
35
35
  }, body, config);
36
36
  }
37
37
 
38
- export const money = (n) => (n < 0.1 ? `$${n.toFixed(3)}` : n < 10 ? `$${n.toFixed(2)}` : `$${Math.round(n)}`);
39
- export const range = ([a, b]) => `${money(a)}–${money(b)}`;
38
+ export const money = (n) => (n < 0.01 ? '<$0.01' : n < 0.1 ? `$${n.toFixed(3)}` : n < 10 ? `$${n.toFixed(2)}` : `$${Math.round(n)}`);
39
+ export const range = ([a, b]) => (b < 0.01 ? '<$0.01' : `${money(a)}–${money(b)}`);
40
+ // Which model the cost is for: one plan model, or per-step picks on top of a default.
41
+ export const mixedModels = (est) => !!est.declared && est.steps.some((s) => s.planned && s.planned.name !== est.model?.name);
42
+ export const modelLabel = (est) => (mixedModels(est) ? (est.model ? ` · planned per step (default ${est.model.name})` : ' · planned per step') : est.model ? ` on ${est.model.name}` : '');
43
+ export const costLabel = (est) => `${range(est.declared ? est.plannedUsd : est.usd)}${modelLabel(est)}`;
40
44
 
41
45
  export function autoApproveVerdict(est, config) {
42
46
  const a = config.autoApprove || {};
@@ -59,7 +63,7 @@ export function renderEstimate(est, config) {
59
63
  return [
60
64
  '## Lake estimate',
61
65
  '',
62
- `Overall complexity: **${est.complexity}** · ${est.declared ? `Planned model${est.model ? ` **${est.model.name}**` : 's per step'}: **${range(est.plannedUsd)}** · Lake mix (cheapest model that fits each step): ${range(est.usd)}` : `Estimated cost with the recommended model per step: **${range(est.usd)}** (all steps on ${est.baseline}: ${range(est.frontierUsd)})`}${est.cap != null ? ` · Budget cap **${money(est.cap)}**` : ''}`,
66
+ `Overall complexity: **${est.complexity}** · ${est.declared ? `${mixedModels(est) ? `Planned per step${est.model ? ` (default **${est.model.name}**)` : ''}` : `Planned model${est.model ? ` **${est.model.name}**` : 's per step'}`}: **${range(est.plannedUsd)}** · Lake mix (cheapest model that fits each step): ${range(est.usd)}` : `Estimated cost with the recommended model per step: **${range(est.usd)}** (all steps on ${est.baseline}: ${range(est.frontierUsd)})`}${est.cap != null ? ` · Budget cap **${money(est.cap)}**` : ''}`,
63
67
  '',
64
68
  est.declared ? '| # | Step | Complexity | Planned model | Recommended model | Est. cost |' : '| # | Step | Complexity | Recommended model | Est. cost |',
65
69
  est.declared ? '|---|---|---|---|---|---|' : '|---|---|---|---|---|',
package/src/github.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { parseConfig } from './config-core.js';
2
2
  import { readPlanText } from './plan.js';
3
- import { estimatePlan, range, money } from './estimate.js';
3
+ import { estimatePlan, range, money, costLabel } from './estimate.js';
4
4
  import { evaluatePlan, isPassing, parseCommands } from './policy.js';
5
5
  import { expandEvents } from './review.js';
6
6
  import { costSuggestions } from './models.js';
@@ -65,15 +65,22 @@ export async function nativeDigests(gh, events, path, { headSha, headText, confi
65
65
  return out;
66
66
  }
67
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).
68
+ // Budget approvers: logins as listed (recommended). "@org/team" is expanded through the API when the token may
69
+ // read the team. An Actions GITHUB_TOKEN usually may not: then we say so in the summary and fall back to any listed
70
+ // login or a repo admin (or the repo owner), so a plan never gets stuck on a team nobody can see.
70
71
  export async function resolveBudgetApprovers(gh, config) {
71
72
  const b = config.budget || {};
72
73
  if (b.approverAbove == null || !(b.approvers || []).length) return undefined;
73
74
  const out = b.approvers.filter((x) => !String(x).includes('/')).map((x) => String(x).replace(/^@/, ''));
75
+ const unreadable = [];
74
76
  for (const t of b.approvers.filter((x) => String(x).includes('/'))) {
75
77
  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 */ }
78
+ try { out.push(...(await gh.all(`~/orgs/${org}/teams/${slug}/members`)).map((u) => u.login)); } catch { unreadable.push(`@${org}/${slug}`); }
79
+ }
80
+ out.unreadable = unreadable;
81
+ if (unreadable.length) {
82
+ try { out.push(...(await gh.all('/collaborators?permission=admin')).filter((u) => u.permissions?.admin !== false).map((u) => u.login)); out.fallback = 'admins'; }
83
+ catch { out.fallback = 'owner'; } // can't list admins either: the repo owner (OWNER association) counts
77
84
  }
78
85
  return out;
79
86
  }
@@ -127,11 +134,14 @@ export function renderSummary(ev) {
127
134
  r.state === 'changes-requested' ? `changes requested by ${r.blockers.map((a) => '@' + a).join(', ')}` :
128
135
  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
136
  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)})` : ''}`;
137
+ const cost = `${costLabel(est)}${est.cap != null ? ` (cap ${money(est.cap)})` : ''}`;
131
138
  lines.push(`| [${r.title.replace(/\|/g, '/')}](${r.path}) | \`${r.short}\` | ${status} | ${est.complexity} | ${cost} |`);
132
139
  }
140
+ for (const r of ev.results.filter((x) => x.budget?.unreadable?.length).slice(0, 1)) {
141
+ lines.push('', `> **Warning:** couldn't read ${r.budget.unreadable.join(', ')} with this token, so ${r.budget.fallback === 'owner' ? 'the repo owner' : 'repo admins'} and any listed login can give the budget approval. List GitHub logins in \`budget.approvers\` (e.g. \`["alice","bob"]\`) to fix this.`);
142
+ }
133
143
  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.`}`);
144
+ 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), ...(r.budget.fallback === 'owner' ? ['the repo owner'] : [])].join(', ') || r.budget.teams.join(', ')} must approve v${r.short} too.`}`);
135
145
  }
136
146
  for (const r of ev.results) {
137
147
  const sugg = costSuggestions(r.estimate, ev.config || {});
@@ -143,7 +153,7 @@ export function renderSummary(ev) {
143
153
  const base = ev.config?.reviewUrl;
144
154
  if (base && ev.repo && ev.pr?.number) {
145
155
  const img = (n, alt) => `![${alt}](${base}btn/${n}.svg)`;
146
- lines.push('', '**Review in one click** (opens the Lake review page for this PR, sign in with GitHub to post):', '');
156
+ lines.push('', '**Review in one click** (opens the Lake review page; posting needs a GitHub token the first time, or use GitHub\'s own Review changes → Approve):', '');
147
157
  for (const r of pending) {
148
158
  const link = (act) => `${base}#/pr/${ev.repo}/${ev.pr.number}/${encodeURIComponent(r.id)}${act ? `?do=${act}&v=${r.short}` : ''}`;
149
159
  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('')})`, '');
@@ -164,7 +174,12 @@ export async function publish(gh, ev, { comment = true } = {}) {
164
174
  await gh.req('POST', `/statuses/${ev.pr.head.sha}`, { state: ev.state, context: STATUS_CONTEXT, description: ev.description.slice(0, 140) });
165
175
  if (!comment || (!ev.results.length && ev.state === 'success' && !/Warning/.test(ev.description))) return;
166
176
  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 });
177
+ try {
178
+ const existing = (await gh.all(`/issues/${ev.pr.number}/comments`)).find((c) => c.user.type === 'Bot' && String(c.body).startsWith(MARKER));
179
+ if (existing) { if (existing.body !== body) await gh.req('PATCH', `/issues/comments/${existing.id}`, { body }); }
180
+ else await gh.req('POST', `/issues/${ev.pr.number}/comments`, { body });
181
+ } catch (e) {
182
+ // The status check above is what matters. A missing summary comment shouldn't fail the gate.
183
+ console.log(`::warning::lake-gate couldn't post the summary comment (${String(e.message).slice(0, 120)}). Give the workflow "pull-requests: write" (see templates/lake-gate.yml).`);
184
+ }
170
185
  }
package/src/hook.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { loadConfig } from './config.js';
3
3
  import { repoRoot, stateDir, getState, setState, loadPlan, exportPlan, localStatus } from './store.js';
4
- import { range } from './estimate.js';
4
+ import { range, costLabel } from './estimate.js';
5
5
 
6
6
  const FILE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
7
7
  const inside = (p, dir) => { const r = path.relative(dir, p); return r === '' || (!r.startsWith('..') && !path.isAbsolute(r)); };
@@ -30,7 +30,7 @@ export function handleClaudePreToolUse(input, env = process.env) {
30
30
  const { plan, estimate } = exportPlan(root, ti.plan, { source: 'claude-code', sessionId: input.session_id });
31
31
  const st = localStatus(root, plan, config);
32
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}.` });
33
+ return out(null, null, { systemMessage: `Lake: plan saved to .lake/plans/${plan.id}.md (version ${plan.short}, ${estimate.complexity} complexity, est. ${costLabel(estimate)}). ${gateNote}.` });
34
34
  }
35
35
 
36
36
  if (config.localGate === 'off' || !config.gatedTools.includes(tool)) return null;
package/src/init.js CHANGED
@@ -60,3 +60,34 @@ export function init(root, { actionRef = ACTION_REF, force = false, trial = fals
60
60
  }
61
61
  return done;
62
62
  }
63
+
64
+ // Undo init: remove the hook, the MCP entries and the workflow. Plans and config in .lake/ stay (they're your history).
65
+ export function uninstall(root) {
66
+ const done = [];
67
+ const readJson = (p) => { try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return null; } };
68
+ const sp = path.join(root, '.claude', 'settings.json');
69
+ const s = fs.existsSync(sp) && readJson(sp);
70
+ if (s?.hooks?.PreToolUse) {
71
+ const before = JSON.stringify(s.hooks.PreToolUse);
72
+ s.hooks.PreToolUse = s.hooks.PreToolUse.map((g) => ({ ...g, hooks: (g.hooks || []).filter((h) => !String(h.command || '').includes('lake-gate')) })).filter((g) => g.hooks.length);
73
+ if (!s.hooks.PreToolUse.length) delete s.hooks.PreToolUse;
74
+ if (!Object.keys(s.hooks).length) delete s.hooks;
75
+ if (JSON.stringify(s.hooks?.PreToolUse) !== before) {
76
+ if (Object.keys(s).length) fs.writeFileSync(sp, JSON.stringify(s, null, 2) + '\n'); else fs.rmSync(sp);
77
+ done.push('removed the lake-gate hook from .claude/settings.json');
78
+ }
79
+ }
80
+ for (const rel of ['.mcp.json', path.join('.cursor', 'mcp.json')]) {
81
+ const p = path.join(root, rel); const c = fs.existsSync(p) && readJson(p);
82
+ if (!c?.mcpServers?.['lake-gate']) continue;
83
+ delete c.mcpServers['lake-gate'];
84
+ if (!Object.keys(c.mcpServers).length) delete c.mcpServers;
85
+ if (Object.keys(c).length) fs.writeFileSync(p, JSON.stringify(c, null, 2) + '\n'); else fs.rmSync(p);
86
+ done.push(`removed the lake-gate MCP server from ${rel}`);
87
+ }
88
+ const wf = path.join(root, '.github', 'workflows', 'lake-gate.yml');
89
+ if (fs.existsSync(wf)) { fs.rmSync(wf); done.push('removed .github/workflows/lake-gate.yml'); }
90
+ for (const d of ['.cursor', path.join('.github', 'workflows'), '.github', '.claude']) { try { fs.rmdirSync(path.join(root, d)); } catch { /* not empty or missing */ } }
91
+ if (!done.length) done.push('Nothing to remove: lake-gate is not set up here.');
92
+ return done;
93
+ }
package/src/mcp.js CHANGED
@@ -6,14 +6,14 @@
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { execFileSync } from 'node:child_process';
9
- import { repoRoot, loadPlan, getState, exportPlan, listPlans } from './store.js';
9
+ import { repoRoot, loadPlan, getState, exportPlan, listPlans, localStatus } from './store.js';
10
10
  import { client } from './github.js';
11
11
  import { parseRemote, applyEvents } from './sync.js';
12
12
  import { collectEvents, nativeDigests } from './github.js';
13
13
  import { loadPr, actions } from './workspace.js';
14
14
  import { loadConfig } from './config.js';
15
- import { range, money, estimatePlan } from './estimate.js';
16
- import { costSuggestions, modelOptions, applyPatch, resolveModel, describePatch } from './models.js';
15
+ import { range, money, estimatePlan, costLabel, mixedModels } from './estimate.js';
16
+ import { costSuggestions, modelOptions, applyPatch, resolveModel, describePatch, budgetRule } from './models.js';
17
17
  import { stripEstimate } from './plan.js';
18
18
  import { acceptBody } from './review.js';
19
19
 
@@ -35,7 +35,7 @@ export const TOOLS = [
35
35
  inputSchema: S({ plan_markdown: str('Full revised plan in markdown'), plan_id: str('Plan id (defaults to the active plan)'),
36
36
  thread_id: str('Accept this reviewer suggestion thread'), suggestion_id: str('Apply this Lake suggestion, e.g. models-2-4, cap-12, drop-5'), model: str('Run the whole plan on this model, e.g. sonnet'),
37
37
  addressed_threads: { type: 'array', items: { type: 'string' }, description: 'Thread ids this revision addresses (marked resolved)' },
38
- note: str('What changed, for reviewers'), push: { type: 'boolean', description: 'Commit only the plan file and push' } }), annotations: { openWorldHint: true } },
38
+ note: str('What changed, for reviewers'), push: { type: 'boolean', description: 'Commit only the plan file and push (default on when applying a suggestion)' } }), annotations: { openWorldHint: true } },
39
39
  { name: 'lake_review', description: 'As a reviewer, act on a plan PR: approve, request_changes, comment (optionally on lines), reply (in a thread) or suggest (a structured change the author accepts in one click: suggestion_id or model). approve and request_changes post as the human GitHub account on this machine: ONLY use them when the user explicitly said so in this conversation, and pass the exact version they saw.',
40
40
  inputSchema: S({ action: { type: 'string', enum: ['approve', 'request_changes', 'comment', 'reply', 'suggest'] }, plan_id: str('Plan id'), version: str('8-character version (approve / request_changes)'),
41
41
  text: str('Comment, reply, or verdict note (required for request_changes)'), line: { type: 'number', description: 'First plan line to anchor a comment' }, end_line: { type: 'number' },
@@ -54,9 +54,9 @@ const ALIASES = {
54
54
 
55
55
  export function formatCost(est, config, sugg = costSuggestions(est, config), budget) {
56
56
  const L = [];
57
- L.push(`Cost: ${est.declared ? `${range(est.plannedUsd)} with the planned model${est.model ? ` (${est.model.name})` : 's'}` : `${range(est.usd)} with Lake's pick per step (no model declared; add a "Model: <name>" line)`}${est.cap != null ? `, capped at ${money(est.cap)}` : ''}.`);
57
+ L.push(`Cost: ${est.declared ? `${range(est.plannedUsd)} ${mixedModels(est) ? `with the models planned per step${est.model ? ` (default ${est.model.name})` : ''}` : `with the planned model${est.model ? ` (${est.model.name})` : 's'}`}` : `${range(est.usd)} with Lake's pick per step (no model declared; add a "Model: <name>" line)`}${est.cap != null ? `, capped at ${money(est.cap)}` : ''}.`);
58
58
  L.push('Steps:', ...est.steps.map((s) => ` ${s.n}. ${s.title.slice(0, 70)} · ${s.complexity} · ${s.planned ? s.planned.name + (s.fit === 'risky' ? ' (may be too weak)' : s.fit === 'overkill' ? ' (more than needed)' : '') : 'not set'} · Lake pick ${s.model} · ${range(s.planned ? s.planned.usd : s.usd)}`));
59
- L.push('Model options (whole plan):', ...modelOptions(est, config).slice(0, 7).map((o) => ` ${o.key}: ${range(o.usd)} · ${o.fit} · ${o.note}`));
59
+ L.push('Model options (whole plan):', ...modelOptions(est, config).slice(0, 7).map((o) => ` ${o.name}: ${range(o.usd)} · ${o.fit} · ${o.note}`));
60
60
  if (sugg.length) L.push('Suggestions:', ...sugg.map((x) => ` [${x.id}] ${x.title}, saves up to ${money(x.saving[1])}`));
61
61
  if (budget?.required) L.push(`Budget approval: up to ${money(budget.exposure)} > ${money(budget.threshold)}. ${budget.satisfied ? `Approved by @${budget.approvedBy.join(', @')}.` : `Needs one of ${budget.approvers.map((x) => '@' + x).join(', ')} to approve this version.`}`);
62
62
  for (const n of est.modelNotes || []) L.push(`Note: ${n}`);
@@ -119,7 +119,7 @@ async function prModel(ctx, id) {
119
119
  export function formatReview(m, { localDigest, link } = {}) {
120
120
  const L = [];
121
121
  L.push(`Plan ${m.id} · v${m.short} (round ${m.round}) · status: ${m.status}${m.policy.needed && m.status === 'in-review' ? ` · needs ${m.policy.needed} more approval(s)` : ''}`);
122
- L.push(`Estimate: ${m.estimate.complexity} complexity, ${range(m.estimate.declared ? m.estimate.plannedUsd : m.estimate.usd)}${m.estimate.model ? ` on ${m.estimate.model.name}` : ''}`);
122
+ L.push(`Estimate: ${m.estimate.complexity} complexity, ${costLabel(m.estimate)}`);
123
123
  if (m.budget?.required) L.push(`Budget approval: ${m.budget.satisfied ? `done by @${m.budget.approvedBy.join(', @')}` : `needed from one of ${m.budget.approvers.map((x) => '@' + x).join(', ')} (up to ${money(m.budget.exposure)} > ${money(m.budget.threshold)})`}`);
124
124
  if (m.suggestions?.length) L.push(`Lake suggestions: ${m.suggestions.map((x) => `[${x.id}] ${x.title} (saves up to ${money(x.saving[1])})`).join('; ')}`);
125
125
  const sg = m.threads.filter((t) => t.suggestion && !t.resolved);
@@ -179,8 +179,18 @@ export async function callTool(ctx, name, a = {}) {
179
179
  case 'lake_review_status': {
180
180
  const id = resolveId(ctx, a.plan_id);
181
181
  const local = loadPlan(ctx.root, id);
182
- let { number, model, config, events, pr } = await prModel(ctx, id);
183
- const localCost = () => { if (!local) return ''; const cfg = loadConfig(ctx.root); return `\n\n${formatCost(estimatePlan(local.body, cfg), cfg)}`; };
182
+ const localCost = () => {
183
+ if (!local) return '';
184
+ const cfg = loadConfig(ctx.root); const est = estimatePlan(local.body, cfg); const rule = budgetRule(est, cfg);
185
+ const st = localStatus(ctx.root, local, cfg);
186
+ return `\nLocal status: ${st.state}${st.trial ? ' (trial)' : ''}.\n\n${formatCost(est, cfg, undefined, rule.required ? { ...rule, satisfied: false } : null)}`;
187
+ };
188
+ let pm;
189
+ try { pm = await prModel(ctx, id); } catch (e) {
190
+ if (/No GitHub remote/.test(e.message)) return `Plan ${id}${local ? ` v${local.short}` : ''} (local only).${localCost()}\n\nAdd a GitHub remote (origin) and open a PR to share it for review.`;
191
+ throw e;
192
+ }
193
+ let { number, model, config, events, pr } = pm;
184
194
  if (!number) return `No open PR for this branch yet. Push the plan and open a PR so teammates can review it.${local ? ` Local plan ${id} is v${local.short}.` : ''}${localCost()}`;
185
195
  if (!model) return `PR #${number} does not contain .lake/plans/${id}.md yet. Push the plan file.`;
186
196
  const wait = Math.min(240, Math.max(0, Number(a.wait_seconds) || 0));
@@ -227,7 +237,7 @@ export async function callTool(ctx, name, a = {}) {
227
237
  return `Commented on ${id} v${model.short}, line ${s}${e > s ? `–${e}` : ''}.`;
228
238
  }
229
239
  case '_approve': case '_changes': {
230
- const id = a.plan_id;
240
+ const id = resolveId(ctx, a.plan_id);
231
241
  const { number, model } = await prModel(ctx, id);
232
242
  if (!model) throw new Error(`No open PR with plan ${id}.`);
233
243
  const v = String(a.version || '').toLowerCase();
@@ -243,7 +253,7 @@ export async function callTool(ctx, name, a = {}) {
243
253
  return `Plan ${id} v${plan.short}\n` + formatCost(est, cfg, undefined, est.exposure > (cfg.budget?.approverAbove ?? Infinity) ? { required: true, exposure: est.exposure, threshold: cfg.budget.approverAbove, approvers: (cfg.budget.approvers || []).map((x) => String(x).replace(/^@/, '')), satisfied: false } : null);
244
254
  }
245
255
  case '_suggest': {
246
- const { number, model, config } = await prModel(ctx, a.plan_id);
256
+ const { number, model, config } = await prModel(ctx, resolveId(ctx, a.plan_id));
247
257
  if (!model) throw new Error(`No open PR with plan ${a.plan_id}.`);
248
258
  const s = patchFor(a, model.estimate, config);
249
259
  await actions.suggest(ctx.github(), number, { planId: model.id, version: model.digest, title: s.title, patch: s.patch, saving: s.saving, text: a.comment, via });
@@ -262,10 +272,11 @@ export async function callTool(ctx, name, a = {}) {
262
272
  } else s = patchFor(a, estimatePlan(plan.body, cfg), cfg);
263
273
  const next = applyPatch(stripEstimate(plan.body).replace(/\s+$/, '') + '\n', s.patch);
264
274
  const { plan: np, estimate } = exportPlan(ctx.root, next, { id, source: 'mcp' });
275
+ const push = a.push ?? true; // one click: apply, commit only the plan file, push
265
276
  let note = '';
266
- if (a.push) note = '\n' + pushPlan(ctx, id, `Plan ${id}: ${s.title || describePatch(s.patch, cfg)} (v${np.short})`);
277
+ if (push) note = '\n' + pushPlan(ctx, id, `Plan ${id}: ${s.title || describePatch(s.patch, cfg)} (v${np.short})`);
267
278
  if (a.thread_id && number) await ctx.github().req('POST', `/issues/${number}/comments`, { body: acceptBody({ planId: id, thread: a.thread_id, title: s.title, newVersion: np.digest, via }) });
268
- return `Applied "${s.title}" to ${id}: new version v${np.short}, ${range(estimate.declared ? estimate.plannedUsd : estimate.usd)}.${note}${a.push ? '' : ' Push the plan file so reviewers see it.'} Earlier approvals no longer apply.`;
279
+ return `Applied "${s.title}" to ${id}: new version v${np.short}, ${range(estimate.declared ? estimate.plannedUsd : estimate.usd)}.${note}${push ? '' : ' Push the plan file so reviewers see it.'} Earlier approvals no longer apply.`;
269
280
  }
270
281
  default: throw new Error(`Unknown tool ${name}`);
271
282
  }
package/src/models.js CHANGED
@@ -16,7 +16,8 @@ export const NEED = { low: 2, medium: 3, high: 4 };
16
16
  const need = (s) => NEED_LEVEL[s.level] ?? NEED[s.complexity];
17
17
  const TIER_ALIAS = { fast: 'light', light: 'light', balanced: 'standard', standard: 'standard', frontier: 'heavy', heavy: 'heavy', max: 'frontier' };
18
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)))];
19
+ // Models offered in the picker: the configured provider's tiers plus anything the team added to "catalog".
20
+ const CURRENT = (prices, config = {}) => [...new Set([...Object.values(prices.recommend?.[config.provider || 'anthropic'] || {}), ...Object.keys(config.catalog || {})])];
20
21
 
21
22
  export function catalogOf(config) {
22
23
  const prices = pricesFor(config);
@@ -91,7 +92,7 @@ export function applyDeclarations(est, body, config) {
91
92
  export function modelOptions(est, config) {
92
93
  const prices = pricesFor(config); const cat = catalogOf(config);
93
94
  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 keys = [...new Set([...CURRENT(prices, config), ...(est.model ? [est.model.key] : [])])].filter((k) => cat[k]);
95
96
  const opts = keys.map((key) => {
96
97
  const m = cat[key];
97
98
  const usd = [0, 1].map((i) => est.steps.reduce((a, s) => a + stepUsd(s, key, prices)[i], 0));
@@ -189,5 +190,5 @@ export function budgetRule(est, config, resolvedApprovers) {
189
190
  const exposure = est.exposure ?? est.usd[1];
190
191
  const required = exposure > b.approverAbove;
191
192
  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
+ return { required, threshold: b.approverAbove, exposure, approvers: [...new Set(list)], teams: b.approvers.filter((x) => String(x).includes('/')), unreadable: resolvedApprovers?.unreadable || [], fallback: resolvedApprovers?.fallback || null };
193
194
  }
package/src/policy.js CHANGED
@@ -17,6 +17,7 @@ export function parseCommands(body) {
17
17
  export function evaluatePlan({ plan, estimate, events, prAuthor, config, budgetApprovers }) {
18
18
  const approvals = new Map();
19
19
  const blockers = new Map();
20
+ const assoc = new Map();
20
21
  const notes = [];
21
22
  const sorted = [...events].sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
22
23
  for (const ev of sorted) {
@@ -33,7 +34,7 @@ export function evaluatePlan({ plan, estimate, events, prAuthor, config, budgetA
33
34
  if (ineligible) { notes.push(`ignored ${c.action} from @${who}: ${ineligible}`); continue; }
34
35
  const matches = c.digest && plan.digest.startsWith(c.digest);
35
36
  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
+ if (c.action === 'approve') { approvals.set(who, ev.createdAt); assoc.set(who, ev.association); blockers.delete(who); }
37
38
  else { blockers.set(who, ev.createdAt); approvals.delete(who); }
38
39
  }
39
40
  }
@@ -42,7 +43,7 @@ export function evaluatePlan({ plan, estimate, events, prAuthor, config, budgetA
42
43
  // (their approval also counts toward requiredApprovals).
43
44
  const rule = estimate ? budgetRule(estimate, config, budgetApprovers) : { required: false };
44
45
  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 budgetBy = rule.required ? [...approvals.keys()].filter((a) => rule.approvers.some((b) => lc(b) === lc(a)) || (rule.fallback === 'owner' && assoc.get(a) === 'OWNER')) : [];
46
47
  const budget = rule.required ? { ...rule, approvedBy: budgetBy, satisfied: budgetBy.length > 0 } : { required: false, satisfied: true };
47
48
  let state;
48
49
  if (blockers.size) state = 'changes-requested';
package/src/store.js CHANGED
@@ -51,11 +51,14 @@ function uniqueId(root, base) {
51
51
  }
52
52
 
53
53
  // Writes (or re-versions) a plan file with a fresh estimate. Returns the loaded plan + estimate.
54
- export function exportPlan(root, markdown, { id, source, sessionId, author } = {}) {
54
+ export function exportPlan(root, markdown, { id, source, sessionId, author, fresh = false } = {}) {
55
55
  const config = loadConfig(root);
56
56
  const state = getState(root);
57
57
  const incoming = splitFrontmatter(markdown).body;
58
58
  let planId = id || (sessionId && state.sessions[sessionId]) || null;
59
+ // Re-saving a plan with the same title (the CLI / MCP edit loop) is a new version of it, not a "-2" copy.
60
+ if (!planId && !fresh && !sessionId && fs.existsSync(planPath(root, slugify(titleOf(incoming))))) planId = slugify(titleOf(incoming));
61
+ const before = planId && fs.existsSync(planPath(root, planId)) ? loadPlan(root, planId) : null;
59
62
  let created = new Date().toISOString();
60
63
  if (planId && fs.existsSync(planPath(root, planId))) {
61
64
  const prev = splitFrontmatter(fs.readFileSync(planPath(root, planId), 'utf8')).meta;
@@ -71,7 +74,8 @@ export function exportPlan(root, markdown, { id, source, sessionId, author } = {
71
74
  state.active = planId;
72
75
  if (sessionId) state.sessions[sessionId] = planId;
73
76
  setState(root, state);
74
- return { plan: loadPlan(root, planId), estimate: est, config };
77
+ const plan = loadPlan(root, planId);
78
+ return { plan, estimate: est, config, previous: before && before.digest !== plan.digest ? before : null, unchanged: !!before && before.digest === plan.digest };
75
79
  }
76
80
 
77
81
  // Local approval status of a plan, based on the last `lake-gate sync` from GitHub and the local auto-approve policy.
@@ -11,7 +11,7 @@ on:
11
11
  types: [created, edited, deleted]
12
12
  permissions:
13
13
  contents: read
14
- pull-requests: read
14
+ pull-requests: write # to post and update the summary comment
15
15
  issues: write
16
16
  statuses: write
17
17
  concurrency:
package/ui/app.js CHANGED
@@ -29,6 +29,7 @@ function rel(at) {
29
29
  const STATUS = { 'in-review': ['In review', 'clock'], 'changes-requested': ['Changes requested', 'undo'], approved: ['Approved', 'check'], 'needs-budget': ['Needs budget OK', 'coin'], 'auto-approved': ['Auto-approved', 'check'], draft: ['Draft', 'pause'], pending: ['In review', 'clock'], 'approved-then-edited': ['Approved, then edited', 'layers'], superseded: ['Superseded', 'layers'] };
30
30
  const chip = (st) => `<span class="chip st-${st === 'pending' ? 'in-review' : st}">${icon(STATUS[st]?.[1] || 'dot', 'xs')}${STATUS[st]?.[0] || st}</span>`;
31
31
  const costOf = (est) => (est.declared ? est.plannedUsd : est.usd);
32
+ const overridden = (est) => (est.declared ? est.steps.filter((s) => s.planned && s.planned.name !== est.model?.name).length : 0);
32
33
  const short = (n) => String(n || '').replace(/^Claude /, '');
33
34
  const VERDICT_BADGE = { approved: 'ok', 'changes-requested': 'bad', waiting: 'wait', commented: 'com', revoked: 'wait' };
34
35
  const viaIcon = (v) => (String(v).includes('MCP') ? icon('bot', 'xs') : String(v).includes('GitHub') ? icon('gh', 'xs') : '');
@@ -302,7 +303,7 @@ function docView(p, n) {
302
303
  const lv = Math.min(4, b.level || 2);
303
304
  const raw = String(r.body).split('\n').slice(b.start - 1, b.end).join(' ');
304
305
  const decl = b.type !== 'heading' && raw.match(/^\s*(?:\*\*)?(model|budget cap)(?:\*\*)?\s*:(?:\*\*)?\s*(.+)$/i);
305
- const tag = b.type === 'heading' ? `<h${lv}>${b.html}</h${lv}>` : decl ? `<p class="declare">${icon(/model/i.test(decl[1]) ? 'cpu' : 'coin', 's')}<span>${/model/i.test(decl[1]) ? 'Runs on' : 'Budget cap'}</span><b>${esc(/model/i.test(decl[1]) && r.estimate.model ? r.estimate.model.name : decl[2].replace(/\*/g, ''))}</b></p>` : b.html;
306
+ const tag = b.type === 'heading' ? `<h${lv}>${b.html}</h${lv}>` : decl ? `<p class="declare">${icon(/model/i.test(decl[1]) ? 'cpu' : 'coin', 's')}<span>${/model/i.test(decl[1]) ? (overridden(r.estimate) ? 'Default model' : 'Runs on') : 'Budget cap'}</span><b>${esc(/model/i.test(decl[1]) && r.estimate.model ? r.estimate.model.name : decl[2].replace(/\*/g, ''))}</b>${/model/i.test(decl[1]) && overridden(r.estimate) ? `<span>· ${overridden(r.estimate)} step${overridden(r.estimate) > 1 ? 's' : ''} overridden</span>` : ''}</p>` : b.html;
306
307
  const foc = ts.some((t) => t.id === S.focus) || inC(b.start, b.end);
307
308
  out.push(`<div class="blk ${ts.length ? 'has' : ''} ${foc ? 'focus' : ''}" data-s="${b.start}" data-e="${b.end}"><span class="gut"><span class="ln">${b.start}</span>${b.type !== 'hr' ? addBtn(b.start, b.end) : ''}</span><div class="body">${tag}</div></div>`);
308
309
  out.push(thr(ts, b.start, b.end, 34));
@@ -344,7 +345,7 @@ function costCard(p, n) {
344
345
  const curKey = est.model ? est.model.key : est.declared ? null : 'lake-mix';
345
346
  const opts = isCur && p.modelOptions ? `<details class="models"${S.modelsOpen ? ' open' : ''}><summary data-act="models-toggle">${icon('cpu', 's')}Compare models${icon('chevd', 'xs')}</summary>${p.modelOptions.map((o) => `<div class="mo ${o.fit} ${o.key === curKey ? 'cur' : ''}"><div class="grow"><span class="nm">${esc(short(o.name))}${o.recommended ? '<i>Lake pick</i>' : ''}${o.key === curKey ? '<i class="c">in plan</i>' : ''}</span><span class="nt">${esc(o.note)}</span></div><span class="num pr">${range(o.usd)}</span>${o.key !== curKey && o.key !== 'lake-mix' ? act(`data-act="${author ? 'use-model' : 'suggest-model'}" data-m="${esc(o.key)}"`, author ? 'Use' : 'Suggest') : ''}</div>`).join('')}</details>` : '';
346
347
  return `<section class="card cost" aria-label="Model and cost"><h4>${icon('coin', 's')}Model &amp; cost<span class="r">${esc(est.complexity)} complexity</span></h4>
347
- <div class="est-total num">${range(planned)}</div><div class="est-sub">${est.model ? `on <b>${esc(short(est.model.name))}</b>` : est.declared ? 'models set per step' : 'Lake pick per step · no model set in the plan'}${est.cap != null ? ` · capped at ${money(est.cap)}` : ''}</div>
348
+ <div class="est-total num">${range(planned)}</div><div class="est-sub">${overridden(est) ? `planned per step${est.model ? ` (default <b>${esc(short(est.model.name))}</b>)` : ''}` : est.model ? `on <b>${esc(short(est.model.name))}</b>` : est.declared ? 'models set per step' : 'Lake pick per step · no model set in the plan'}${est.cap != null ? ` · capped at ${money(est.cap)}` : ''}</div>
348
349
  ${budget}
349
350
  ${est.steps.map((s) => { const u = s.planned ? s.planned.usd : s.usd; const m = s.planned ? s.planned.name : s.model; return `<div class="step"><span class="sn">${s.n}</span><span class="st" title="${esc(s.title)}">${esc(s.title)}</span><span class="mchip ${s.complexity} ${s.fit}" title="${s.fit === 'risky' ? 'May be too weak for this step' : s.fit === 'overkill' ? `More than this step needs. Lake pick: ${esc(s.model)}` : esc(s.complexity) + ' complexity'}">${s.fit === 'risky' ? '! ' : ''}${esc(short(m))}</span><span class="bar"><i class="${s.complexity}" style="width:${Math.max(6, (u[1] / max) * 100)}%"></i></span></div>`; }).join('')}
350
351
  ${saveHtml}${opts}
@@ -438,7 +439,7 @@ function roundsView(p) {
438
439
  <a class="btn sm" href="${planHref(p)}${r.current ? '' : `?round=${r.n}`}">Read</a>${r.n > 1 ? `<a class="btn sm" href="${planHref(p, `/diff/${r.n - 1}/${r.n}`)}">${icon('diff', 's')}Changes</a>` : ''}</div>
439
440
  <div class="rmeta"><span class="who">${avatar(r.author || p.author, 'sm')}${esc(first(r.author || p.author))} ${r.n === 1 ? 'opened the plan' : 'revised it'}</span><span>${rel(r.at)}</span>
440
441
  ${r.stats ? `<span><span class="plus">+${r.stats.added}</span> <span class="minus">−${r.stats.removed}</span> lines</span>` : ''}
441
- <span class="num">${range(costOf(r.estimate))}${r.estimate.model ? ` · ${esc(short(r.estimate.model.name))}` : ''}${Math.abs(delta) > 0.005 ? ` <span class="${delta > 0 ? 'minus' : 'plus'}">(${delta > 0 ? '+' : '−'}${money(Math.abs(delta))})</span>` : ''}</span>
442
+ <span class="num">${range(costOf(r.estimate))}${r.estimate.model ? ` · ${esc(short(r.estimate.model.name))}${overridden(r.estimate) ? ' + per step' : ''}` : ''}${Math.abs(delta) > 0.005 ? ` <span class="${delta > 0 ? 'minus' : 'plus'}">(${delta > 0 ? '+' : '−'}${money(Math.abs(delta))})</span>` : ''}</span>
442
443
  <span>${th.length} thread${th.length === 1 ? '' : 's'}${th.length ? `, ${resolved} resolved` : ''}</span></div>
443
444
  ${r.verdicts.map(verdictLine).join('')}
444
445
  ${!r.verdicts.length ? `<div class="rmeta" style="margin-top:10px">${r.current ? 'No verdicts on this round yet.' : 'Superseded before anyone gave a verdict.'}</div>` : ''}