lake-gate 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lake
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,111 @@
1
- # Temporary Holding Version
1
+ # lake-gate
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Your agent writes the plan. A teammate approves that exact version. Then the agent builds.**
4
+
5
+ lake-gate is a small, free, open-source plan gate for teams using Claude Code, Cursor or Codex. It runs in your repo and on GitHub. There is no Lake server, no account and no telemetry.
6
+
7
+ - **Plan export.** When Claude Code leaves plan mode, the plan is saved to `.lake/plans/<id>.md` with a complexity rating, a recommended model per step and a cost range.
8
+ - **Version-bound approval.** A teammate approves on the PR with `/lake approve <id>@<version>`. Edit one word of the plan and the approval no longer applies.
9
+ - **Local gate.** A Claude Code `PreToolUse` hook denies file edits and non-read-only shell commands until the active plan's current version is approved. Reading and exploring stay free.
10
+ - **PR check.** A GitHub Action sets the `lake/plan-approval` status. Make it required and unapproved plans can't merge.
11
+ - **Auto-approve for small plans (optional).** Small, cheap, low-complexity plans can skip review. It ships in shadow mode: the PR shows "would auto-approve" and a human still decides.
12
+
13
+ ## Install (about 10 minutes)
14
+
15
+ ```bash
16
+ cd your-repo
17
+ npx lake-gate init # writes .lake/, .claude/settings.json hook, .github/workflows/lake-gate.yml
18
+ npm i -D lake-gate # optional for JS repos: faster hook than npx
19
+ git add .lake .claude .github && git commit -m "Add lake-gate" && git push
20
+ ```
21
+
22
+ If the npm package is not available yet, install from GitHub first:
23
+
24
+ ```bash
25
+ npm i -g github:getlake/lake-gate
26
+ # then in your repo:
27
+ lake-gate init
28
+ ```
29
+
30
+ Then in GitHub: **Settings → Branches → branch protection → Require status checks → `lake/plan-approval`** (the check appears after the first PR runs).
31
+
32
+ Requirements: Node 18.17+, git, a GitHub repo. macOS/Linux shells for the hook (Windows: use WSL for now).
33
+
34
+ ## The flow
35
+
36
+ 1. **Plan.** In Claude Code, use plan mode as usual. When the plan is accepted, the hook saves it to `.lake/plans/add-webhook-retries.md` and tells you its version and estimate. Using Cursor or Codex? Save the plan as markdown and run `npx lake-gate plan plan.md`.
37
+ 2. **Open a PR with the plan first** (a draft PR is fine). The Action posts one summary comment with the exact approve line.
38
+ 3. **A teammate approves** with a PR comment or review: `/lake approve add-webhook-retries@86eab4d0`. The PR author and bots can't approve. Read-only users can't approve.
39
+ 4. **Sync and build.** `npx lake-gate sync` pulls approvals into your local checkout (uses `GITHUB_TOKEN` or `gh auth token`). The agent can now edit. The code lands in the same PR and the check is green.
40
+ 5. **Plan changes?** Edit the plan file. The version changes, the gate closes again and the PR check turns red until someone approves the new version.
41
+
42
+ Commands on the PR, one per line:
43
+
44
+ | Comment | Effect |
45
+ |---|---|
46
+ | `/lake approve <id>@<version>` | Approve this exact version |
47
+ | `/lake reject <id>@<version>` | Request changes. Blocks until the same person approves |
48
+ | `/lake revoke <id>` | Withdraw your approval |
49
+
50
+ ## What the estimate looks like
51
+
52
+ ```
53
+ | # | Step | Complexity | Recommended model | Est. cost |
54
+ | 1 | Add a bounded retry queue with backoff | medium | Claude Sonnet 5.5 | $0.42–$1.25 |
55
+ | 2 | Database migration: retry_count column | high | Claude Opus 5.5 | $2.04–$7.09 |
56
+ | 3 | Fix typo in README | low | Claude Haiku 5.5 | $0.032–$0.11|
57
+ ```
58
+
59
+ It's a rough heuristic: keywords plus token bands per complexity, multiplied by public API list prices (as of 2026-11-12, cache hits assumed). It isn't a quote or a spending cap. On a subscription plan you spend quota, not these dollars. Prices, models and bands are all in `.lake/config.json`.
60
+
61
+ ## CLI
62
+
63
+ ```
64
+ lake-gate init [--action-ref owner/repo@ref] [--force]
65
+ lake-gate plan <file.md|-> [--id name] save a plan with an estimate and make it active
66
+ lake-gate estimate <file.md|-> print the estimate only
67
+ lake-gate status plans, versions, approval state
68
+ lake-gate sync [--pr N] pull approvals from the PR
69
+ lake-gate check [--plan id] exit 0 only if the active plan's current version is approved
70
+ lake-gate use <id> switch the active plan (the hook blocks agents from doing this)
71
+ lake-gate hook claude the Claude Code PreToolUse hook (stdin JSON)
72
+ ```
73
+
74
+ `check` is the pre-run gate for anything that isn't Claude Code, e.g. `npx lake-gate check && codex exec "implement .lake/plans/x.md"`.
75
+
76
+ ## Configuration: `.lake/config.json`
77
+
78
+ | Key | Default | Meaning |
79
+ |---|---|---|
80
+ | `requiredApprovals` | `1` | Distinct non-author approvals needed |
81
+ | `allowedAssociations` | `OWNER, MEMBER, COLLABORATOR` | Who may approve |
82
+ | `ignoreLogins` | `[]` | Logins that never count (e.g. a shared agent account) |
83
+ | `requirePlan` | `"warn"` | PR changes code without a plan: `off`, `warn`, `fail` |
84
+ | `localGate` | `"block"` | Hook behaviour: `block` (deny), `ask` (Claude Code prompts you), `off` |
85
+ | `readOnlyBash` | git status/log/diff, ls, cat, rg... | Bash commands allowed before approval (regexes; chained commands are not) |
86
+ | `autoApprove` | `{mode:"shadow", maxUsd:1.5, maxSteps:3, maxComplexity:"low"}` | `off`, `shadow`, or `on` |
87
+ | `models`, `cacheHitShare` | Haiku / Sonnet / Opus 5.5 list prices | Edit to match your stack |
88
+
89
+ The PR check reads the config from the **base branch**, so a PR can't loosen its own policy.
90
+
91
+ ## What it does not do (read this)
92
+
93
+ - **It is a guardrail, not a security boundary.** The local hook stops an agent from drifting into implementation. A human can turn it off (`LAKE_GATE=off`, editing settings). The real enforcement point is the required GitHub status.
94
+ - **A malicious insider can bypass the PR check** by editing the workflow in a `pull_request` run. Protect `.github/` and `.lake/config.json` with CODEOWNERS if that matters to you. Comment events always run the workflow from the default branch.
95
+ - **Approval doesn't stop a run that goes wrong after it starts.** lake-gate gates the start of implementation. It does not watch direction or spend during a run (yet).
96
+ - Fork PRs get a read-only token, so the status can't be posted. It's meant for internal team repos.
97
+ - Cost numbers are forecasts from a heuristic, not measurements.
98
+ - Claude Code is gated by the hook. Cursor and Codex use `lake-gate check` as a pre-run step.
99
+
100
+ ## Privacy
101
+
102
+ There's no telemetry, no analytics and no network calls except `lake-gate sync`, which reads your PR from the GitHub API, and the Action, which runs inside your GitHub. Plans stay in your repo.
103
+
104
+ ## Development
105
+
106
+ ```bash
107
+ npm test # unit + end-to-end tests (temp git repos, simulated hook payloads, mocked GitHub API)
108
+ ./scripts/demo.sh # packs the npm tarball, installs it in a throwaway repo, runs the whole flow
109
+ ```
110
+
111
+ MIT © Lake
package/action.yml ADDED
@@ -0,0 +1,21 @@
1
+ name: Lake plan gate
2
+ description: Version-bound team approval for AI coding agent plans. Sets the lake/plan-approval commit status.
3
+ author: Lake
4
+ branding:
5
+ icon: check-circle
6
+ color: green
7
+ inputs:
8
+ token:
9
+ description: GitHub token with statuses:write and issues:write (the default GITHUB_TOKEN works).
10
+ required: false
11
+ default: ${{ github.token }}
12
+ comment:
13
+ description: Post and update one summary comment on the PR.
14
+ required: false
15
+ default: 'true'
16
+ outputs:
17
+ state:
18
+ description: success or failure
19
+ runs:
20
+ using: node24
21
+ main: src/action.js
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+ main().then((code) => { process.exitCode = code; }, (e) => { process.stderr.write(`lake-gate: ${e.message}\n`); process.exitCode = 2; });
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "lake-gate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Version-bound team plan approval for AI coding agents. Claude Code hook + GitHub Action. No backend, no telemetry.",
5
+ "type": "module",
6
+ "bin": { "lake-gate": "bin/lake-gate.js" },
7
+ "main": "src/index.js",
8
+ "exports": { ".": "./src/index.js" },
9
+ "files": ["bin", "src", "templates", "action.yml", "README.md", "LICENSE"],
10
+ "engines": { "node": ">=18.17" },
11
+ "scripts": { "test": "node --test test/*.test.js" },
12
+ "keywords": ["claude-code", "hooks", "ai-agents", "plan-review", "github-action", "approval", "cursor", "codex", "cost"],
13
+ "license": "MIT",
14
+ "author": "Lake research team",
15
+ "repository": { "type": "git", "url": "git+https://github.com/getlake/lake-gate.git" },
16
+ "homepage": "https://github.com/getlake/lake-gate#readme",
17
+ "bugs": { "url": "https://github.com/getlake/lake-gate/issues" }
18
+ }
package/src/action.js ADDED
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ // GitHub Action entry point. Uses only the REST API with the workflow's GITHUB_TOKEN; no checkout needed.
3
+ import fs from 'node:fs';
4
+ import { client, evaluatePr, publish, renderSummary } from './github.js';
5
+
6
+ export function prNumberFromEvent(name, payload) {
7
+ if (payload.pull_request) return payload.pull_request.number;
8
+ if (name === 'issue_comment' && payload.issue && payload.issue.pull_request) return payload.issue.number;
9
+ return null;
10
+ }
11
+
12
+ export async function runAction(env = process.env, fetchImpl) {
13
+ const payload = JSON.parse(fs.readFileSync(env.GITHUB_EVENT_PATH, 'utf8'));
14
+ const number = prNumberFromEvent(env.GITHUB_EVENT_NAME, payload);
15
+ if (!number) { console.log('lake-gate: not a pull request event, nothing to do.'); return null; }
16
+ const token = env.INPUT_TOKEN || env.GITHUB_TOKEN;
17
+ const gh = client({ token, repo: env.GITHUB_REPOSITORY, api: env.GITHUB_API_URL || 'https://api.github.com', fetchImpl });
18
+ const ev = await evaluatePr(gh, number);
19
+ await publish(gh, ev, { comment: (env.INPUT_COMMENT || 'true') !== 'false' });
20
+ const md = renderSummary(ev);
21
+ if (env.GITHUB_STEP_SUMMARY) fs.appendFileSync(env.GITHUB_STEP_SUMMARY, md + '\n');
22
+ if (env.GITHUB_OUTPUT) fs.appendFileSync(env.GITHUB_OUTPUT, `state=${ev.state}\n`);
23
+ console.log(`lake-gate: ${ev.state}: ${ev.description}`);
24
+ return ev;
25
+ }
26
+
27
+ if (import.meta.url === `file://${process.argv[1]}`) {
28
+ runAction().catch((e) => { console.error(`::error::lake-gate: ${e.message}`); process.exit(1); });
29
+ }
package/src/cli.js ADDED
@@ -0,0 +1,96 @@
1
+ import fs from 'node:fs';
2
+ import { repoRoot, exportPlan, loadPlan, listPlans, getState, setState, localStatus } from './store.js';
3
+ import { loadConfig } from './config.js';
4
+ import { estimatePlan, renderEstimate, range } from './estimate.js';
5
+ import { handleClaudePreToolUse } from './hook.js';
6
+ import { syncFromGitHub, applyEvents } from './sync.js';
7
+ import { init, ACTION_REF } from './init.js';
8
+
9
+ const HELP = `lake-gate: version-bound team approval for AI coding agent plans
10
+
11
+ Usage:
12
+ lake-gate init [--action-ref owner/repo@ref] [--force] Set up .lake/, the Claude Code hook and the GitHub workflow
13
+ lake-gate plan <file.md|-> [--id name] Save a plan (any agent) to .lake/plans/ with an estimate; make it active
14
+ lake-gate estimate <file.md|-> Print complexity, model per step and cost range
15
+ lake-gate status Active plan, version and approval state
16
+ lake-gate sync [--pr N] Pull approvals from the PR on GitHub (uses GITHUB_TOKEN or gh)
17
+ lake-gate check [--plan id] Exit 0 if the active plan's current version is approved (pre-run check)
18
+ lake-gate use <id> Set the active plan (human only; the hook blocks agents)
19
+ lake-gate hook claude Claude Code PreToolUse hook (reads JSON on stdin)
20
+
21
+ No telemetry. No backend. Docs: https://github.com/getlake/lake-gate`;
22
+
23
+ const flag = (args, name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; };
24
+ const readInput = (f) => (f === '-' || !f ? fs.readFileSync(0, 'utf8') : fs.readFileSync(f, 'utf8'));
25
+
26
+ function describe(root, plan) {
27
+ const st = localStatus(root, plan);
28
+ 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(', ')}` : '';
29
+ return `${plan.id} v${plan.short} ${st.estimate.complexity} est. ${range(st.estimate.usd)} ${st.state}${extra}`;
30
+ }
31
+
32
+ export async function main(argv = process.argv.slice(2), io = { out: (s) => process.stdout.write(s + '\n'), err: (s) => process.stderr.write(s + '\n') }) {
33
+ const [cmd, ...args] = argv;
34
+ const root = repoRoot();
35
+ switch (cmd) {
36
+ case 'init': {
37
+ for (const l of init(root, { actionRef: flag(args, '--action-ref') || ACTION_REF, force: args.includes('--force') })) io.out(l);
38
+ io.out('\nNext:\n 1. git add .lake .claude .github && git commit -m "Add lake-gate"\n 2. In GitHub branch protection, require the status check "lake/plan-approval".\n 3. Optional: npm i -D lake-gate (faster hook than npx).');
39
+ return 0;
40
+ }
41
+ case 'plan': {
42
+ const { plan, estimate } = exportPlan(root, readInput(args.find((a) => !a.startsWith('--') && a !== flag(args, '--id'))), { id: flag(args, '--id'), source: 'cli' });
43
+ io.out(`Saved .lake/plans/${plan.id}.md version ${plan.short} ${estimate.complexity} est. ${range(estimate.usd)}`);
44
+ io.out(`Approve on the PR with: /lake approve ${plan.id}@${plan.short}`);
45
+ return 0;
46
+ }
47
+ case 'estimate': {
48
+ const cfg = loadConfig(root);
49
+ io.out(renderEstimate(estimatePlan(readInput(args[0]), cfg), cfg));
50
+ return 0;
51
+ }
52
+ case 'status': {
53
+ const st = getState(root);
54
+ const plans = listPlans(root);
55
+ if (!plans.length) { io.out('No plans yet. Use plan mode in Claude Code, or: lake-gate plan <file.md>'); return 0; }
56
+ for (const p of plans) io.out(`${p.id === st.active ? '*' : ' '} ${describe(root, p)}`);
57
+ return 0;
58
+ }
59
+ case 'sync': {
60
+ if (flag(args, '--from-json')) { // offline/testing: {prAuthor, events}
61
+ const j = JSON.parse(fs.readFileSync(flag(args, '--from-json'), 'utf8'));
62
+ applyEvents(root, j);
63
+ } else {
64
+ const r = await syncFromGitHub(root, { pr: flag(args, '--pr') && Number(flag(args, '--pr')) });
65
+ io.out(`Synced approvals from PR #${r.pr}.`);
66
+ }
67
+ for (const p of listPlans(root)) io.out(' ' + describe(root, p));
68
+ return 0;
69
+ }
70
+ case 'check': {
71
+ const id = flag(args, '--plan') || getState(root).active;
72
+ const plan = id && loadPlan(root, id);
73
+ if (!plan) { io.err('lake-gate: no active plan.'); return 1; }
74
+ const st = localStatus(root, plan);
75
+ const ok = st.state === 'approved' || st.state === 'auto-approved';
76
+ (ok ? io.out : io.err)(describe(root, plan));
77
+ return ok ? 0 : 1;
78
+ }
79
+ case 'use': {
80
+ if (!args[0] || !loadPlan(root, args[0])) { io.err(`No plan named ${args[0]}`); return 1; }
81
+ const st = getState(root); st.active = args[0]; setState(root, st);
82
+ io.out(`Active plan: ${args[0]}`);
83
+ return 0;
84
+ }
85
+ case 'hook': {
86
+ if (args[0] !== 'claude') { io.err('Supported: lake-gate hook claude'); return 1; }
87
+ const input = JSON.parse(fs.readFileSync(0, 'utf8') || '{}');
88
+ const res = handleClaudePreToolUse(input);
89
+ if (res) io.out(JSON.stringify(res));
90
+ return 0;
91
+ }
92
+ case undefined: case 'help': case '--help': case '-h': io.out(HELP); return 0;
93
+ case '--version': case '-v': io.out(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url))).version); return 0;
94
+ default: io.err(`Unknown command: ${cmd}\n\n${HELP}`); return 1;
95
+ }
96
+ }
package/src/config.js ADDED
@@ -0,0 +1,52 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ // Prices are public list prices per million tokens, copied from
5
+ // https://docs.anthropic.com/en/docs/about-claude/pricing on 2026-11-12.
6
+ // They are assumptions for a forecast, not a quote. Edit .lake/config.json to change them.
7
+ export const DEFAULT_CONFIG = {
8
+ requiredApprovals: 1,
9
+ allowedAssociations: ['OWNER', 'MEMBER', 'COLLABORATOR'],
10
+ ignoreLogins: [],
11
+ requirePlan: 'warn', // PR check when code changes without a plan: "off" | "warn" | "fail"
12
+ localGate: 'block', // Claude Code hook: "block" | "ask" | "off"
13
+ gatedTools: ['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'Bash'],
14
+ readOnlyBash: [
15
+ '^\\s*(ls|pwd|cat|head|tail|wc|rg|grep|find|tree|file|stat|which|echo|env|date|du|df)(\\s|$)',
16
+ '^\\s*git\\s+(status|log|diff|show|branch|remote|rev-parse|ls-files|blame|fetch)(\\s|$)',
17
+ '^\\s*(npx\\s+(-y\\s+)?)?lake-gate(@\\S+)?\\s+(status|estimate|check|sync|plan|help)(\\s|$)',
18
+ ],
19
+ autoApprove: { mode: 'shadow', maxUsd: 1.5, maxSteps: 3, maxComplexity: 'low' }, // mode: "off" | "shadow" | "on"
20
+ cacheHitShare: 0.7,
21
+ pricesAsOf: '2026-11-12',
22
+ models: {
23
+ fast: { name: 'Claude Haiku 5.5', inputPerMTok: 0.5, cacheReadPerMTok: 0.05, outputPerMTok: 2.5 },
24
+ balanced: { name: 'Claude Sonnet 5.5', inputPerMTok: 2, cacheReadPerMTok: 0.1, outputPerMTok: 10 },
25
+ frontier: { name: 'Claude Opus 5.5', inputPerMTok: 4, cacheReadPerMTok: 0.2, outputPerMTok: 20 },
26
+ },
27
+ tierFor: { low: 'fast', medium: 'balanced', high: 'frontier' },
28
+ // Rough agentic token bands per step (input includes re-read context; output is generated code/text).
29
+ tokens: {
30
+ low: { in: [120000, 400000], out: [4000, 15000] },
31
+ medium: { in: [400000, 1200000], out: [15000, 45000] },
32
+ high: { in: [1000000, 3500000], out: [35000, 120000] },
33
+ },
34
+ };
35
+
36
+ function isObj(v) { return v && typeof v === 'object' && !Array.isArray(v); }
37
+ export function merge(base, over) {
38
+ if (!isObj(over)) return base;
39
+ const out = { ...base };
40
+ for (const [k, v] of Object.entries(over)) out[k] = isObj(v) && isObj(base[k]) ? merge(base[k], v) : v;
41
+ return out;
42
+ }
43
+
44
+ export function parseConfig(text) {
45
+ if (!text) return DEFAULT_CONFIG;
46
+ return merge(DEFAULT_CONFIG, JSON.parse(text));
47
+ }
48
+
49
+ export function loadConfig(root) {
50
+ const p = path.join(root, '.lake', 'config.json');
51
+ return parseConfig(fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null);
52
+ }
@@ -0,0 +1,82 @@
1
+ import { extractSteps } from './plan.js';
2
+
3
+ const RANK = { low: 0, medium: 1, high: 2 };
4
+ export const complexityRank = (c) => RANK[c] ?? 1;
5
+
6
+ const HIGH = /\b(migrat\w*|schema|database|auth\w*|security|secret|payment|billing|concurren\w*|race|lock(ing)?|distributed|encrypt\w*|permission\w*|architect\w*|rewrite|re-?architect|multi-?tenant|infra\w*|deploy\w*|kubernetes|cache invalidation|backfill|data model|breaking change)\b/i;
7
+ const LOW = /\b(typo|rename|copy|wording|docs?|readme|comment|bump|version bump|lint|format\w*|style|log message|changelog|config value|constant|label|tooltip|text)\b/i;
8
+ const MANY_FILES = /\b(across|all|every|each)\s+(the\s+)?(files|modules|services|packages|endpoints|components|call ?sites)\b/i;
9
+ const TESTS = /\b(test|tests|spec|e2e|integration)\b/i;
10
+
11
+ export function classifyStep(text) {
12
+ const reasons = [];
13
+ let score = 1;
14
+ const h = text.match(HIGH); const l = text.match(LOW);
15
+ if (h) { score += 1; reasons.push(`mentions "${h[0]}"`); }
16
+ if (MANY_FILES.test(text)) { score += 1; reasons.push('touches many files'); }
17
+ if (l && !h) { score -= 1; reasons.push(`looks small ("${l[0]}")`); }
18
+ const words = text.split(/\s+/).length;
19
+ if (words > 80) { score += 1; reasons.push('long step'); }
20
+ if (TESTS.test(text) && score < 2 && !l) reasons.push('includes tests');
21
+ const complexity = score <= 0 ? 'low' : score === 1 ? 'medium' : 'high';
22
+ if (!reasons.length) reasons.push('default');
23
+ return { complexity, reasons };
24
+ }
25
+
26
+ const usd = (tokIn, tokOut, m, hit) => (tokIn * (1 - hit) * m.inputPerMTok + tokIn * hit * m.cacheReadPerMTok + tokOut * m.outputPerMTok) / 1e6;
27
+
28
+ export function estimatePlan(body, config) {
29
+ const steps = extractSteps(body).map((s, i) => {
30
+ const { complexity, reasons } = classifyStep(s.text);
31
+ const tier = config.tierFor[complexity];
32
+ const model = config.models[tier];
33
+ const band = config.tokens[complexity];
34
+ const hit = config.cacheHitShare;
35
+ const lo = usd(band.in[0], band.out[0], model, hit);
36
+ const hi = usd(band.in[1], band.out[1], model, hit);
37
+ const top = config.models.frontier;
38
+ return { n: i + 1, title: s.title.slice(0, 90), complexity, reasons, tier, model: model.name, tokens: band,
39
+ usd: [lo, hi], frontierUsd: [usd(band.in[0], band.out[0], top, hit), usd(band.in[1], band.out[1], top, hit)] };
40
+ });
41
+ const sum = (k, i) => steps.reduce((a, s) => a + s[k][i], 0);
42
+ const maxC = steps.reduce((a, s) => (complexityRank(s.complexity) > complexityRank(a) ? s.complexity : a), 'low');
43
+ return {
44
+ steps,
45
+ complexity: maxC,
46
+ usd: [sum('usd', 0), sum('usd', 1)],
47
+ frontierUsd: [sum('frontierUsd', 0), sum('frontierUsd', 1)],
48
+ pricesAsOf: config.pricesAsOf,
49
+ };
50
+ }
51
+
52
+ export const money = (n) => (n < 0.1 ? `$${n.toFixed(3)}` : n < 10 ? `$${n.toFixed(2)}` : `$${Math.round(n)}`);
53
+ export const range = ([a, b]) => `${money(a)}–${money(b)}`;
54
+
55
+ export function autoApproveVerdict(est, config) {
56
+ const a = config.autoApprove || {};
57
+ if (!a.mode || a.mode === 'off') return { eligible: false, mode: 'off', reasons: [] };
58
+ const reasons = [];
59
+ if (est.usd[1] > a.maxUsd) reasons.push(`upper estimate ${money(est.usd[1])} > ${money(a.maxUsd)}`);
60
+ if (est.steps.length > a.maxSteps) reasons.push(`${est.steps.length} steps > ${a.maxSteps}`);
61
+ if (complexityRank(est.complexity) > complexityRank(a.maxComplexity)) reasons.push(`complexity ${est.complexity} > ${a.maxComplexity}`);
62
+ return { eligible: reasons.length === 0, mode: a.mode, reasons };
63
+ }
64
+
65
+ export function renderEstimate(est, config) {
66
+ const rows = est.steps.map((s) => `| ${s.n} | ${s.title.replace(/\|/g, '/')} | ${s.complexity} | ${s.model} | ${range(s.usd)} |`);
67
+ const auto = autoApproveVerdict(est, config);
68
+ const autoLine = auto.mode === 'off' ? '' : auto.eligible
69
+ ? `\nAuto-approve policy (${auto.mode}): ${auto.mode === 'on' ? 'this plan is auto-approved' : 'this plan would be auto-approved'} (small, low cost).`
70
+ : `\nAuto-approve policy (${auto.mode}): needs a human (${auto.reasons.join('; ')}).`;
71
+ return [
72
+ '## Lake estimate',
73
+ '',
74
+ `Overall complexity: **${est.complexity}** · Estimated cost with the recommended model per step: **${range(est.usd)}** (all steps on ${config.models.frontier.name}: ${range(est.frontierUsd)})`,
75
+ '',
76
+ '| # | Step | Complexity | Recommended model | Est. cost |',
77
+ '|---|---|---|---|---|',
78
+ ...rows,
79
+ '',
80
+ `Rough forecast from keyword heuristics and API list prices as of ${est.pricesAsOf}, assuming ${Math.round(config.cacheHitShare * 100)}% cache hits. Not a quote, not a cap. Subscription plans spend quota, not these dollars.` + autoLine,
81
+ ].join('\n');
82
+ }
package/src/github.js ADDED
@@ -0,0 +1,110 @@
1
+ import { parseConfig } from './config.js';
2
+ import { readPlanText } from './plan.js';
3
+ import { estimatePlan, range } from './estimate.js';
4
+ import { evaluatePlan, isPassing } from './policy.js';
5
+
6
+ export const STATUS_CONTEXT = 'lake/plan-approval';
7
+ export const MARKER = '<!-- lake-gate:summary -->';
8
+
9
+ export function client({ token, repo, api = 'https://api.github.com', fetchImpl = globalThis.fetch }) {
10
+ const [owner, name] = repo.split('/');
11
+ async function req(method, url, body) {
12
+ const res = await fetchImpl(url.startsWith('http') ? url : `${api}/repos/${owner}/${name}${url}`, {
13
+ method,
14
+ headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'lake-gate', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(body ? { 'Content-Type': 'application/json' } : {}) },
15
+ body: body ? JSON.stringify(body) : undefined,
16
+ });
17
+ if (res.status === 404 && method === 'GET') return null;
18
+ if (!res.ok) throw new Error(`GitHub ${method} ${url} -> ${res.status} ${await res.text()}`);
19
+ return res.status === 204 ? null : res.json();
20
+ }
21
+ async function all(url) {
22
+ const out = [];
23
+ for (let page = 1; page < 50; page++) {
24
+ const chunk = await req('GET', `${url}${url.includes('?') ? '&' : '?'}per_page=100&page=${page}`);
25
+ if (!chunk || !chunk.length) break;
26
+ out.push(...chunk);
27
+ if (chunk.length < 100) break;
28
+ }
29
+ return out;
30
+ }
31
+ async function file(p, ref) {
32
+ const r = await req('GET', `/contents/${p.split('/').map(encodeURIComponent).join('/')}?ref=${encodeURIComponent(ref)}`);
33
+ return r && r.content ? Buffer.from(r.content, 'base64').toString('utf8') : null;
34
+ }
35
+ return { req, all, file, owner, name };
36
+ }
37
+
38
+ export async function collectEvents(gh, number) {
39
+ const [comments, reviews] = await Promise.all([gh.all(`/issues/${number}/comments`), gh.all(`/pulls/${number}/reviews`)]);
40
+ return [
41
+ ...comments.map((c) => ({ login: c.user.login, type: c.user.type, association: c.author_association, body: c.body, createdAt: c.created_at, source: 'comment', id: c.id })),
42
+ ...reviews.filter((r) => r.state !== 'DISMISSED').map((r) => ({ login: r.user.login, type: r.user.type, association: r.author_association, body: r.body, createdAt: r.submitted_at, source: 'review', id: r.id })),
43
+ ];
44
+ }
45
+
46
+ const isPlanPath = (f) => /^\.lake\/plans\/[^/]+\.md$/.test(f) && !f.endsWith('/README.md');
47
+ const isCodePath = (f) => !f.startsWith('.lake/') && !/\.(md|txt)$/i.test(f) && !f.startsWith('docs/');
48
+
49
+ // Evaluates every plan file touched by the PR. Config is read from the BASE branch so a PR cannot loosen its own policy.
50
+ export async function evaluatePr(gh, number) {
51
+ const pr = await gh.req('GET', `/pulls/${number}`);
52
+ const config = parseConfig(await gh.file('.lake/config.json', pr.base.sha));
53
+ const files = await gh.all(`/pulls/${number}/files`);
54
+ const planFiles = files.filter((f) => isPlanPath(f.filename) && f.status !== 'removed').map((f) => f.filename);
55
+ const codeChanged = files.some((f) => isCodePath(f.filename));
56
+ const events = await collectEvents(gh, number);
57
+ const results = [];
58
+ for (const p of planFiles) {
59
+ const text = await gh.file(p, pr.head.sha);
60
+ if (text == null) continue;
61
+ const plan = readPlanText(text, p.split('/').pop().slice(0, -3));
62
+ const estimate = estimatePlan(plan.body, config);
63
+ results.push({ ...evaluatePlan({ plan, estimate, events, prAuthor: pr.user.login, config }), title: plan.title, path: p, estimate });
64
+ }
65
+ return { pr, config, results, codeChanged, ...summarize(results, codeChanged, config) };
66
+ }
67
+
68
+ export function summarize(results, codeChanged, config) {
69
+ if (!results.length) {
70
+ if (!codeChanged || config.requirePlan === 'off') return { state: 'success', description: 'No plan in this PR' };
71
+ return config.requirePlan === 'fail'
72
+ ? { state: 'failure', description: 'Code changed without a plan in .lake/plans/' }
73
+ : { state: 'success', description: 'Warning: code changed without a plan in .lake/plans/' };
74
+ }
75
+ const bad = results.filter((r) => !isPassing(r));
76
+ if (!bad.length) return { state: 'success', description: `${results.length} plan(s) approved for their current version` };
77
+ const r = bad[0];
78
+ return { state: 'failure', description: r.state === 'changes-requested' ? `Changes requested on ${r.id}` : `Waiting for approval: /lake approve ${r.id}@${r.short}`.slice(0, 140) };
79
+ }
80
+
81
+ export function renderSummary(ev) {
82
+ const lines = [MARKER, '### Lake plan gate', ''];
83
+ if (!ev.results.length) { lines.push(ev.description + '.'); return lines.join('\n'); }
84
+ lines.push('| Plan | Version | Status | Complexity | Est. cost |', '|---|---|---|---|---|');
85
+ for (const r of ev.results) {
86
+ const status = r.state === 'approved' ? `approved by ${r.approvers.map((a) => '@' + a).join(', ')}` :
87
+ r.state === 'auto-approved' ? 'auto-approved by policy' :
88
+ r.state === 'changes-requested' ? `changes requested by ${r.blockers.map((a) => '@' + a).join(', ')}` : `needs ${r.needed} approval(s)`;
89
+ lines.push(`| [${r.title.replace(/\|/g, '/')}](${r.path}) | \`${r.short}\` | ${status} | ${r.estimate.complexity} | ${range(r.estimate.usd)} |`);
90
+ }
91
+ const pending = ev.results.filter((r) => !isPassing(r));
92
+ if (pending.length) {
93
+ lines.push('', 'To approve, a teammate other than the PR author comments (one line per plan):', '```', ...pending.map((r) => `/lake approve ${r.id}@${r.short}`), '```',
94
+ 'Approval is bound to this exact version. Editing the plan file needs a fresh approval.');
95
+ }
96
+ const shadow = ev.results.filter((r) => r.auto.mode === 'shadow' && r.auto.eligible && !isPassing(r));
97
+ if (shadow.length) lines.push('', `Shadow auto-approve: ${shadow.map((r) => r.id).join(', ')} would pass the auto-approve policy. It is in shadow mode, so a human still decides.`);
98
+ const notes = ev.results.flatMap((r) => r.notes);
99
+ if (notes.length) lines.push('', '<details><summary>Ignored commands</summary>', '', ...notes.map((n) => `- ${n}`), '', '</details>');
100
+ return lines.join('\n');
101
+ }
102
+
103
+ export async function publish(gh, ev, { comment = true } = {}) {
104
+ await gh.req('POST', `/statuses/${ev.pr.head.sha}`, { state: ev.state, context: STATUS_CONTEXT, description: ev.description.slice(0, 140) });
105
+ if (!comment || (!ev.results.length && ev.state === 'success' && !/Warning/.test(ev.description))) return;
106
+ const body = renderSummary(ev);
107
+ const existing = (await gh.all(`/issues/${ev.pr.number}/comments`)).find((c) => c.user.type === 'Bot' && String(c.body).startsWith(MARKER));
108
+ if (existing) { if (existing.body !== body) await gh.req('PATCH', `/issues/comments/${existing.id}`, { body }); }
109
+ else await gh.req('POST', `/issues/${ev.pr.number}/comments`, { body });
110
+ }
package/src/hook.js ADDED
@@ -0,0 +1,65 @@
1
+ import path from 'node:path';
2
+ import { loadConfig } from './config.js';
3
+ import { repoRoot, stateDir, getState, loadPlan, exportPlan, localStatus } from './store.js';
4
+ import { range } from './estimate.js';
5
+
6
+ const FILE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
7
+ const inside = (p, dir) => { const r = path.relative(dir, p); return r === '' || (!r.startsWith('..') && !path.isAbsolute(r)); };
8
+
9
+ function out(decision, reason, extra = {}) {
10
+ if (!decision) return extra.systemMessage ? { systemMessage: extra.systemMessage } : null;
11
+ return { ...(extra.systemMessage ? { systemMessage: extra.systemMessage } : {}),
12
+ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: decision, permissionDecisionReason: reason } };
13
+ }
14
+
15
+ function approveHint(plan) {
16
+ return `Commit .lake/plans/${plan.id}.md, push and open a PR. A teammate (not you) comments:\n /lake approve ${plan.id}@${plan.short}\nThen run: npx lake-gate sync`;
17
+ }
18
+
19
+ // Pure decision for one Claude Code PreToolUse payload. Returns the JSON object to print (or null for "no opinion").
20
+ export function handleClaudePreToolUse(input, env = process.env) {
21
+ if (env.LAKE_GATE === 'off') return null;
22
+ const root = repoRoot(input.cwd || env.CLAUDE_PROJECT_DIR || process.cwd());
23
+ const config = loadConfig(root);
24
+ const tool = input.tool_name;
25
+ const ti = input.tool_input || {};
26
+
27
+ if (tool === 'ExitPlanMode') {
28
+ if (!ti.plan || !String(ti.plan).trim()) return null;
29
+ const { plan, estimate } = exportPlan(root, ti.plan, { source: 'claude-code', sessionId: input.session_id });
30
+ const st = localStatus(root, plan, config);
31
+ const gateNote = st.state === 'approved' || st.state === 'auto-approved' ? `Already ${st.state}` : 'Implementation is gated until a teammate approves this version';
32
+ 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
+ }
34
+
35
+ if (config.localGate === 'off' || !config.gatedTools.includes(tool)) return null;
36
+ if (input.permission_mode === 'plan') return null; // plan mode is read-only already
37
+
38
+ const sdir = stateDir(root);
39
+ if (FILE_TOOLS.has(tool)) {
40
+ const fp = path.resolve(root, ti.file_path || ti.notebook_path || '');
41
+ if (inside(fp, sdir)) return out('deny', 'Lake: local approval state cannot be edited by the agent.');
42
+ if (inside(fp, path.join(root, '.lake', 'plans'))) return null; // editing a plan is allowed; it creates a new version
43
+ if (!inside(fp, root)) return null; // outside the repo is out of scope
44
+ }
45
+ if (tool === 'Bash') {
46
+ const cmd = String(ti.command || '');
47
+ if (/\.git\/lake|lake[\\/]+(state|approvals)\.json/.test(cmd)) return out('deny', 'Lake: local approval state cannot be edited by the agent.');
48
+ if (/lake-gate(@\S+)?\s+use\b/.test(cmd)) return out('deny', 'Lake: switching the active plan is a human action. Ask the user to run `npx lake-gate use <id>`.');
49
+ const ro = config.readOnlyBash.some((r) => new RegExp(r).test(cmd)) && !/[;&|`$()<>]/.test(cmd.replace(/2>&1|\|\s*(head|tail|wc|rg|grep|sort|uniq)\b[^|;&]*/g, ''));
50
+ if (ro) return null;
51
+ }
52
+
53
+ const decision = config.localGate === 'ask' ? 'ask' : 'deny';
54
+ const state = getState(root);
55
+ const activeId = (input.session_id && state.sessions[input.session_id]) || state.active;
56
+ const plan = activeId && loadPlan(root, activeId);
57
+ if (!plan) {
58
+ return out(decision, 'Lake: no plan for this work yet. Write a short plan first (Claude Code plan mode, then exit plan mode) or export one with `npx lake-gate plan <file.md>`. Implementation is gated until the plan is approved by a teammate.');
59
+ }
60
+ const st = localStatus(root, plan, config);
61
+ if (st.state === 'approved' || st.state === 'auto-approved') return null;
62
+ const why = st.state === 'changes-requested' ? `changes were requested by ${(st.blockers || []).map((b) => '@' + b).join(', ')}` :
63
+ st.stale ? 'the plan was edited after it was approved, so the approval no longer applies' : 'it is not approved yet';
64
+ return out(decision, `Lake: plan "${plan.id}" version ${plan.short} blocks implementation because ${why}. Do not work around this gate; stop and tell the user.\n${approveHint(plan)}`);
65
+ }
package/src/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export * from './config.js';
2
+ export * from './plan.js';
3
+ export * from './estimate.js';
4
+ export * from './policy.js';
5
+ export * from './store.js';
6
+ export * from './hook.js';
7
+ export * from './github.js';
8
+ export * from './sync.js';
9
+ export * from './init.js';
package/src/init.js ADDED
@@ -0,0 +1,42 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { DEFAULT_CONFIG } from './config.js';
5
+
6
+ export const ACTION_REF = 'getlake/lake-gate@v0';
7
+ const TEMPLATES = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'templates');
8
+
9
+ export const HOOK_COMMAND = 'if [ -x "$CLAUDE_PROJECT_DIR/node_modules/.bin/lake-gate" ]; then exec "$CLAUDE_PROJECT_DIR/node_modules/.bin/lake-gate" hook claude; elif command -v lake-gate >/dev/null 2>&1; then exec lake-gate hook claude; else exec npx -y lake-gate@0 hook claude; fi';
10
+ const MATCHER = 'ExitPlanMode|Edit|Write|MultiEdit|NotebookEdit|Bash';
11
+
12
+ export function mergeClaudeSettings(settings) {
13
+ const s = settings && typeof settings === 'object' ? structuredClone(settings) : {};
14
+ s.hooks = s.hooks || {};
15
+ const list = (s.hooks.PreToolUse = s.hooks.PreToolUse || []);
16
+ const already = list.some((g) => (g.hooks || []).some((h) => String(h.command || '').includes('lake-gate')));
17
+ if (!already) list.push({ matcher: MATCHER, hooks: [{ type: 'command', command: HOOK_COMMAND, timeout: 30, onFailure: 'block' }] });
18
+ return { settings: s, changed: !already };
19
+ }
20
+
21
+ export function init(root, { actionRef = ACTION_REF, force = false } = {}) {
22
+ const done = [];
23
+ const write = (rel, content, overwrite = force) => {
24
+ const p = path.join(root, rel);
25
+ if (fs.existsSync(p) && !overwrite) { done.push(`kept ${rel} (exists)`); return; }
26
+ fs.mkdirSync(path.dirname(p), { recursive: true });
27
+ fs.writeFileSync(p, content);
28
+ done.push(`wrote ${rel}`);
29
+ };
30
+ const { models, tokens, tierFor, ...short } = DEFAULT_CONFIG;
31
+ write('.lake/config.json', JSON.stringify({ ...short, models }, null, 2) + '\n');
32
+ write('.lake/plans/README.md', fs.readFileSync(path.join(TEMPLATES, 'plans-README.md'), 'utf8'));
33
+ write('.github/workflows/lake-gate.yml', fs.readFileSync(path.join(TEMPLATES, 'lake-gate.yml'), 'utf8').replace('__ACTION_REF__', actionRef));
34
+
35
+ const sp = path.join(root, '.claude', 'settings.json');
36
+ let current = {};
37
+ if (fs.existsSync(sp)) { try { current = JSON.parse(fs.readFileSync(sp, 'utf8')); } catch { throw new Error('.claude/settings.json is not valid JSON; fix it and run init again.'); } }
38
+ const { settings, changed } = mergeClaudeSettings(current);
39
+ if (changed) { fs.mkdirSync(path.dirname(sp), { recursive: true }); fs.writeFileSync(sp, JSON.stringify(settings, null, 2) + '\n'); done.push('merged .claude/settings.json (PreToolUse hook)'); }
40
+ else done.push('kept .claude/settings.json (hook already present)');
41
+ return done;
42
+ }
package/src/plan.js ADDED
@@ -0,0 +1,90 @@
1
+ import crypto from 'node:crypto';
2
+
3
+ export const EST_START = '<!-- lake:estimate:start (generated, not part of the approved digest) -->';
4
+ export const EST_END = '<!-- lake:estimate:end -->';
5
+
6
+ export function slugify(s) {
7
+ return String(s || 'plan').toLowerCase().normalize('NFKD').replace(/[^\w\s-]/g, '')
8
+ .trim().replace(/[\s_]+/g, '-').replace(/-+/g, '-').slice(0, 48).replace(/-$/, '') || 'plan';
9
+ }
10
+
11
+ export function splitFrontmatter(text) {
12
+ const t = String(text).replace(/\r\n?/g, '\n');
13
+ const m = t.match(/^---\n([\s\S]*?)\n---\n?/);
14
+ if (!m) return { meta: {}, body: t };
15
+ const meta = {};
16
+ for (const line of m[1].split('\n')) {
17
+ const kv = line.match(/^([\w-]+):\s*(.*)$/);
18
+ if (kv) meta[kv[1]] = kv[2].replace(/^"(.*)"$/, '$1');
19
+ }
20
+ return { meta, body: t.slice(m[0].length) };
21
+ }
22
+
23
+ export function stripEstimate(body) {
24
+ const s = body.indexOf(EST_START);
25
+ if (s === -1) return body;
26
+ const e = body.indexOf(EST_END, s);
27
+ return e === -1 ? body.slice(0, s) : body.slice(0, s) + body.slice(e + EST_END.length);
28
+ }
29
+
30
+ // The digest covers only the human/agent-authored plan text: no frontmatter, no generated estimate,
31
+ // normalized line endings and trailing whitespace. Any other edit produces a new version.
32
+ export function normalizeBody(body) {
33
+ return stripEstimate(body).replace(/\r\n?/g, '\n').split('\n').map((l) => l.replace(/\s+$/, '')).join('\n').trim() + '\n';
34
+ }
35
+
36
+ export function digestOf(body) {
37
+ return crypto.createHash('sha256').update(normalizeBody(body)).digest('hex');
38
+ }
39
+
40
+ export function titleOf(body) {
41
+ const h = body.match(/^#\s+(.+)$/m);
42
+ if (h) return h[1].trim();
43
+ const first = body.split('\n').find((l) => l.trim());
44
+ return (first || 'Untitled plan').replace(/^[#>*\-\s]+/, '').slice(0, 80);
45
+ }
46
+
47
+ const SKIP_HEADINGS = /^(context|summary|overview|background|goal|goals|notes?|risks?|open questions|verification|testing plan|out of scope)\b/i;
48
+
49
+ export function extractSteps(body) {
50
+ const lines = normalizeBody(body).split('\n');
51
+ // 1) top-level numbered list items, with indented continuation lines
52
+ const steps = [];
53
+ let cur = null;
54
+ for (const l of lines) {
55
+ const m = l.match(/^\s{0,3}(\d+)[.)]\s+(.+)$/);
56
+ if (m) { cur = { title: m[2].trim(), text: m[2] }; steps.push(cur); continue; }
57
+ if (cur && /^\s{2,}\S/.test(l)) { cur.text += '\n' + l.trim(); continue; }
58
+ if (cur && /^\s*$/.test(l)) continue;
59
+ cur = null;
60
+ }
61
+ if (steps.length) return steps;
62
+ // 2) ## / ### headings that are not context sections
63
+ let sec = null;
64
+ for (const l of lines) {
65
+ const m = l.match(/^#{2,4}\s+(.+)$/);
66
+ if (m) { sec = SKIP_HEADINGS.test(m[1].replace(/^(step\s*)?\d+[.:)]?\s*/i, '')) ? null : { title: m[1].trim(), text: m[1] }; if (sec) steps.push(sec); continue; }
67
+ if (sec) sec.text += '\n' + l;
68
+ }
69
+ if (steps.length) return steps;
70
+ // 3) top-level bullets
71
+ for (const l of lines) { const m = l.match(/^[-*]\s+(.+)$/); if (m) steps.push({ title: m[1].trim(), text: m[1] }); }
72
+ if (steps.length) return steps;
73
+ return [{ title: titleOf(body), text: body }];
74
+ }
75
+
76
+ export function renderPlanFile({ id, title, author, source, created, body, estimateMd }) {
77
+ const fm = ['---', `id: ${id}`, `title: "${String(title).replace(/"/g, "'")}"`];
78
+ if (author) fm.push(`author: ${author}`);
79
+ if (source) fm.push(`source: ${source}`);
80
+ if (created) fm.push(`created: ${created}`);
81
+ fm.push('---', '');
82
+ const clean = stripEstimate(body).replace(/\s+$/, '');
83
+ return fm.join('\n') + clean + '\n\n' + EST_START + '\n' + estimateMd.trim() + '\n' + EST_END + '\n';
84
+ }
85
+
86
+ export function readPlanText(text, fallbackId) {
87
+ const { meta, body } = splitFrontmatter(text);
88
+ const digest = digestOf(body);
89
+ return { id: meta.id || fallbackId, title: meta.title || titleOf(body), meta, body, digest, short: digest.slice(0, 8) };
90
+ }
package/src/policy.js ADDED
@@ -0,0 +1,49 @@
1
+ import { autoApproveVerdict } from './estimate.js';
2
+
3
+ // Commands, one per line, in a PR comment or review body:
4
+ // /lake approve <plan-id>@<digest-prefix>
5
+ // /lake reject <plan-id>@<digest-prefix> (request changes; blocks until the same person approves)
6
+ // /lake revoke <plan-id> (withdraw your approval of any version)
7
+ const CMD = /^\s*\/lake\s+(approve|reject|revoke)\b[ \t]*([^\s@]+)?(?:@([0-9a-f]{7,64}))?/gim;
8
+
9
+ export function parseCommands(body) {
10
+ const out = [];
11
+ for (const m of String(body || '').matchAll(CMD)) out.push({ action: m[1].toLowerCase(), id: m[2] || null, digest: m[3] ? m[3].toLowerCase() : null });
12
+ return out;
13
+ }
14
+
15
+ // events: [{ login, type: 'User'|'Bot', association, body, createdAt, source: 'comment'|'review' }]
16
+ export function evaluatePlan({ plan, estimate, events, prAuthor, config }) {
17
+ const approvals = new Map();
18
+ const blockers = new Map();
19
+ const notes = [];
20
+ const sorted = [...events].sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
21
+ for (const ev of sorted) {
22
+ for (const c of parseCommands(ev.body)) {
23
+ if (c.id && c.id !== plan.id) continue;
24
+ if (!c.id) { notes.push(`@${ev.login}: "/lake ${c.action}" needs a plan id, e.g. /lake ${c.action} ${plan.id}@${plan.short}`); continue; }
25
+ const who = ev.login;
26
+ const ineligible =
27
+ ev.type === 'Bot' ? 'bots and agents cannot approve' :
28
+ prAuthor && who.toLowerCase() === prAuthor.toLowerCase() ? 'the plan author cannot approve their own plan' :
29
+ (config.ignoreLogins || []).some((x) => x.toLowerCase() === who.toLowerCase()) ? 'listed in ignoreLogins' :
30
+ !config.allowedAssociations.includes(ev.association) ? `association ${ev.association} lacks write access` : null;
31
+ if (c.action === 'revoke') { approvals.delete(who); continue; }
32
+ if (ineligible) { notes.push(`ignored ${c.action} from @${who}: ${ineligible}`); continue; }
33
+ const matches = c.digest && plan.digest.startsWith(c.digest);
34
+ 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; }
35
+ if (c.action === 'approve') { approvals.set(who, ev.createdAt); blockers.delete(who); }
36
+ else { blockers.set(who, ev.createdAt); approvals.delete(who); }
37
+ }
38
+ }
39
+ const auto = estimate ? autoApproveVerdict(estimate, config) : { eligible: false, mode: 'off', reasons: [] };
40
+ let state;
41
+ if (blockers.size) state = 'changes-requested';
42
+ else if (approvals.size >= config.requiredApprovals) state = 'approved';
43
+ else if (auto.mode === 'on' && auto.eligible) state = 'auto-approved';
44
+ else state = 'pending';
45
+ return { id: plan.id, digest: plan.digest, short: plan.short, state, approvers: [...approvals.keys()], blockers: [...blockers.keys()], auto, notes,
46
+ needed: Math.max(0, config.requiredApprovals - approvals.size) };
47
+ }
48
+
49
+ export const isPassing = (r) => r.state === 'approved' || r.state === 'auto-approved';
package/src/store.js ADDED
@@ -0,0 +1,90 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { loadConfig } from './config.js';
5
+ import { readPlanText, renderPlanFile, slugify, titleOf, splitFrontmatter } from './plan.js';
6
+ import { estimatePlan, renderEstimate, autoApproveVerdict } from './estimate.js';
7
+
8
+ function git(cwd, args) {
9
+ try { return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return null; }
10
+ }
11
+
12
+ export function repoRoot(cwd = process.cwd()) {
13
+ return git(cwd, ['rev-parse', '--show-toplevel']) || path.resolve(cwd);
14
+ }
15
+
16
+ // Local state lives inside .git so it is never committed and never part of a PR.
17
+ export function stateDir(root) {
18
+ const gd = git(root, ['rev-parse', '--absolute-git-dir']);
19
+ const dir = gd ? path.join(gd, 'lake') : path.join(root, '.lake', '.local');
20
+ fs.mkdirSync(dir, { recursive: true });
21
+ return dir;
22
+ }
23
+
24
+ const readJson = (p, d) => { try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return d; } };
25
+ const writeJson = (p, v) => fs.writeFileSync(p, JSON.stringify(v, null, 2) + '\n');
26
+
27
+ export const plansDir = (root) => path.join(root, '.lake', 'plans');
28
+ export const planPath = (root, id) => path.join(plansDir(root), `${id}.md`);
29
+
30
+ export function getState(root) { return readJson(path.join(stateDir(root), 'state.json'), { active: null, sessions: {} }); }
31
+ export function setState(root, s) { writeJson(path.join(stateDir(root), 'state.json'), s); }
32
+ export function getApprovals(root) { return readJson(path.join(stateDir(root), 'approvals.json'), {}); }
33
+ export function setApprovals(root, a) { writeJson(path.join(stateDir(root), 'approvals.json'), a); }
34
+
35
+ export function listPlans(root) {
36
+ const d = plansDir(root);
37
+ if (!fs.existsSync(d)) return [];
38
+ return fs.readdirSync(d).filter((f) => f.endsWith('.md') && f !== 'README.md').map((f) => loadPlan(root, f.slice(0, -3)));
39
+ }
40
+
41
+ export function loadPlan(root, id) {
42
+ const p = planPath(root, id);
43
+ if (!fs.existsSync(p)) return null;
44
+ return { ...readPlanText(fs.readFileSync(p, 'utf8'), id), path: p };
45
+ }
46
+
47
+ function uniqueId(root, base) {
48
+ let id = base; let n = 2;
49
+ while (fs.existsSync(planPath(root, id))) id = `${base}-${n++}`;
50
+ return id;
51
+ }
52
+
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 } = {}) {
55
+ const config = loadConfig(root);
56
+ const state = getState(root);
57
+ const incoming = splitFrontmatter(markdown).body;
58
+ let planId = id || (sessionId && state.sessions[sessionId]) || null;
59
+ let created = new Date().toISOString();
60
+ if (planId && fs.existsSync(planPath(root, planId))) {
61
+ const prev = splitFrontmatter(fs.readFileSync(planPath(root, planId), 'utf8')).meta;
62
+ created = prev.created || created;
63
+ author = author || prev.author;
64
+ } else {
65
+ planId = uniqueId(root, planId || slugify(titleOf(incoming)));
66
+ }
67
+ author = author || git(root, ['config', 'user.email']) || undefined;
68
+ const est = estimatePlan(incoming, config);
69
+ fs.mkdirSync(plansDir(root), { recursive: true });
70
+ fs.writeFileSync(planPath(root, planId), renderPlanFile({ id: planId, title: titleOf(incoming), author, source, created, body: incoming, estimateMd: renderEstimate(est, config) }));
71
+ state.active = planId;
72
+ if (sessionId) state.sessions[sessionId] = planId;
73
+ setState(root, state);
74
+ return { plan: loadPlan(root, planId), estimate: est, config };
75
+ }
76
+
77
+ // Local approval status of a plan, based on the last `lake-gate sync` from GitHub and the local auto-approve policy.
78
+ export function localStatus(root, plan, config = loadConfig(root)) {
79
+ const est = estimatePlan(plan.body, config);
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 };
82
+ if (rec && rec.digest === plan.digest && rec.state === 'changes-requested') return { state: 'changes-requested', approvers: [], blockers: rec.blockers, estimate: est, synced: rec };
83
+ const a = config.autoApprove || {};
84
+ if (a.mode === 'on') {
85
+ const v = autoApproveVerdict(est, config);
86
+ if (v.eligible) return { state: 'auto-approved', approvers: [], estimate: est };
87
+ }
88
+ const stale = rec && rec.digest !== plan.digest && (rec.state === 'approved' || rec.state === 'auto-approved');
89
+ return { state: 'pending', stale, approvers: [], estimate: est };
90
+ }
package/src/sync.js ADDED
@@ -0,0 +1,46 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { loadConfig } from './config.js';
3
+ import { listPlans, getApprovals, setApprovals } from './store.js';
4
+ import { estimatePlan } from './estimate.js';
5
+ import { evaluatePlan } from './policy.js';
6
+ import { client, collectEvents } from './github.js';
7
+
8
+ const sh = (cmd, args, cwd) => { try { return execFileSync(cmd, args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return null; } };
9
+
10
+ export function parseRemote(url) {
11
+ const m = String(url || '').match(/github\.com[:/]([^/]+)\/([^/]+?)(\.git)?$/);
12
+ return m ? `${m[1]}/${m[2]}` : null;
13
+ }
14
+
15
+ // Applies GitHub approvals to the LOCAL plan files. An approval only counts if its digest matches the local file,
16
+ // so a plan edited locally after approval is pending again.
17
+ export function applyEvents(root, { events, prAuthor, prNumber }) {
18
+ const config = loadConfig(root);
19
+ const store = getApprovals(root);
20
+ const results = [];
21
+ for (const plan of listPlans(root)) {
22
+ const r = evaluatePlan({ plan, estimate: estimatePlan(plan.body, config), events, prAuthor, config });
23
+ store[plan.id] = { digest: plan.digest, state: r.state, approvers: r.approvers, blockers: r.blockers, pr: prNumber ?? null, syncedAt: new Date().toISOString() };
24
+ results.push(r);
25
+ }
26
+ setApprovals(root, store);
27
+ return results;
28
+ }
29
+
30
+ export async function syncFromGitHub(root, { pr, token, fetchImpl } = {}) {
31
+ const repo = parseRemote(sh('git', ['remote', 'get-url', 'origin'], root));
32
+ if (!repo) throw new Error('No GitHub remote named origin.');
33
+ token = token || process.env.GITHUB_TOKEN || process.env.GH_TOKEN || sh('gh', ['auth', 'token'], root);
34
+ if (!token) throw new Error('Need GitHub read access: set GITHUB_TOKEN or run `gh auth login`.');
35
+ const gh = client({ token, repo, fetchImpl });
36
+ let number = pr;
37
+ if (!number) {
38
+ const branch = sh('git', ['rev-parse', '--abbrev-ref', 'HEAD'], root);
39
+ const prs = await gh.req('GET', `/pulls?state=open&head=${encodeURIComponent(`${gh.owner}:${branch}`)}`);
40
+ if (!prs || !prs.length) throw new Error(`No open PR for branch ${branch}. Push and open one, then run sync again.`);
41
+ number = prs[0].number;
42
+ }
43
+ const prObj = await gh.req('GET', `/pulls/${number}`);
44
+ const events = await collectEvents(gh, number);
45
+ return { pr: number, results: applyEvents(root, { events, prAuthor: prObj.user.login, prNumber: number }) };
46
+ }
@@ -0,0 +1,28 @@
1
+ # Lake plan gate: checks that every plan in .lake/plans/ touched by a PR is approved,
2
+ # for its current version, by someone other than the PR author.
3
+ # Make "lake/plan-approval" a required status check in branch protection to enforce it.
4
+ name: Lake plan gate
5
+ on:
6
+ pull_request:
7
+ types: [opened, synchronize, reopened, ready_for_review]
8
+ pull_request_review:
9
+ types: [submitted, edited, dismissed]
10
+ issue_comment:
11
+ types: [created, edited, deleted]
12
+ permissions:
13
+ contents: read
14
+ pull-requests: read
15
+ issues: write
16
+ statuses: write
17
+ concurrency:
18
+ group: lake-gate-${{ github.event.pull_request.number || github.event.issue.number }}
19
+ cancel-in-progress: false
20
+ jobs:
21
+ plan-gate:
22
+ if: github.event_name != 'issue_comment' || (github.event.issue.pull_request && contains(github.event.comment.body, '/lake'))
23
+ runs-on: ubuntu-latest
24
+ timeout-minutes: 5
25
+ steps:
26
+ - uses: __ACTION_REF__
27
+ with:
28
+ token: ${{ secrets.GITHUB_TOKEN }}
@@ -0,0 +1,10 @@
1
+ # Plans
2
+
3
+ Each file here is an implementation plan an AI coding agent will follow, with a generated cost estimate.
4
+
5
+ - Approve a plan on its PR with a comment: `/lake approve <plan-id>@<version>` (the PR bot comment shows the exact line).
6
+ - Request changes: `/lake reject <plan-id>@<version>`. Withdraw: `/lake revoke <plan-id>`.
7
+ - The PR author cannot approve their own plan. Bots cannot approve.
8
+ - Editing a plan changes its version and needs a fresh approval. The generated "Lake estimate" block is not part of the version.
9
+
10
+ Made with lake-gate. No telemetry: nothing leaves your repo except what GitHub already runs.