lean-agents 0.0.0-stage → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.es.md +454 -0
- package/README.md +453 -2
- package/core/AGENTS.es.md +60 -0
- package/core/AGENTS.md +60 -0
- package/core/README.md +8 -0
- package/core/agents/debug.md +14 -0
- package/core/agents/explore.md +13 -0
- package/core/agents/planner.md +14 -0
- package/core/agents/research.md +13 -0
- package/core/agents/review.md +13 -0
- package/core/copilot-usage-tui.js +186 -0
- package/core/mcp.json +38 -0
- package/core/pins.json +30 -0
- package/core/tiers.json +4 -0
- package/node_modules/@clack/core/LICENSE +9 -0
- package/node_modules/@clack/core/README.md +22 -0
- package/node_modules/@clack/core/dist/index.d.mts +503 -0
- package/node_modules/@clack/core/dist/index.mjs +1003 -0
- package/node_modules/@clack/core/package.json +63 -0
- package/node_modules/@clack/prompts/LICENSE +9 -0
- package/node_modules/@clack/prompts/README.md +396 -0
- package/node_modules/@clack/prompts/dist/index.d.mts +949 -0
- package/node_modules/@clack/prompts/dist/index.mjs +1423 -0
- package/node_modules/@clack/prompts/package.json +67 -0
- package/node_modules/fast-string-truncated-width/dist/index.d.ts +4 -0
- package/node_modules/fast-string-truncated-width/dist/index.js +111 -0
- package/node_modules/fast-string-truncated-width/dist/types.d.ts +19 -0
- package/node_modules/fast-string-truncated-width/dist/types.js +2 -0
- package/node_modules/fast-string-truncated-width/dist/utils.d.ts +4 -0
- package/node_modules/fast-string-truncated-width/dist/utils.js +20 -0
- package/node_modules/fast-string-truncated-width/license +21 -0
- package/node_modules/fast-string-truncated-width/package.json +35 -0
- package/node_modules/fast-string-truncated-width/readme.md +59 -0
- package/node_modules/fast-string-width/dist/index.d.ts +4 -0
- package/node_modules/fast-string-width/dist/index.js +14 -0
- package/node_modules/fast-string-width/license +21 -0
- package/node_modules/fast-string-width/package.json +34 -0
- package/node_modules/fast-string-width/readme.md +42 -0
- package/node_modules/fast-wrap-ansi/LICENSE +23 -0
- package/node_modules/fast-wrap-ansi/README.md +26 -0
- package/node_modules/fast-wrap-ansi/lib/main.d.ts +6 -0
- package/node_modules/fast-wrap-ansi/lib/main.js +218 -0
- package/node_modules/fast-wrap-ansi/package.json +51 -0
- package/node_modules/jsonc-parser/CHANGELOG.md +76 -0
- package/node_modules/jsonc-parser/LICENSE.md +21 -0
- package/node_modules/jsonc-parser/README.md +364 -0
- package/node_modules/jsonc-parser/SECURITY.md +41 -0
- package/node_modules/jsonc-parser/lib/esm/impl/edit.js +185 -0
- package/node_modules/jsonc-parser/lib/esm/impl/format.js +261 -0
- package/node_modules/jsonc-parser/lib/esm/impl/parser.js +659 -0
- package/node_modules/jsonc-parser/lib/esm/impl/scanner.js +443 -0
- package/node_modules/jsonc-parser/lib/esm/impl/string-intern.js +29 -0
- package/node_modules/jsonc-parser/lib/esm/main.d.ts +351 -0
- package/node_modules/jsonc-parser/lib/esm/main.js +178 -0
- package/node_modules/jsonc-parser/lib/umd/impl/edit.js +201 -0
- package/node_modules/jsonc-parser/lib/umd/impl/format.js +275 -0
- package/node_modules/jsonc-parser/lib/umd/impl/parser.js +682 -0
- package/node_modules/jsonc-parser/lib/umd/impl/scanner.js +456 -0
- package/node_modules/jsonc-parser/lib/umd/impl/string-intern.js +42 -0
- package/node_modules/jsonc-parser/lib/umd/main.d.ts +351 -0
- package/node_modules/jsonc-parser/lib/umd/main.js +194 -0
- package/node_modules/jsonc-parser/package.json +37 -0
- package/node_modules/sisteransi/license +21 -0
- package/node_modules/sisteransi/package.json +34 -0
- package/node_modules/sisteransi/readme.md +113 -0
- package/node_modules/sisteransi/src/index.js +58 -0
- package/node_modules/sisteransi/src/sisteransi.d.ts +35 -0
- package/package.json +29 -4
- package/profiles/README.md +10 -0
- package/profiles/anthropic-api/gsd-defaults.json +26 -0
- package/profiles/anthropic-api.json +18 -0
- package/profiles/antigravity.json +12 -0
- package/profiles/claude-subscription/gsd-defaults.json +26 -0
- package/profiles/claude-subscription.json +17 -0
- package/profiles/github-copilot/gsd-defaults.json +26 -0
- package/profiles/github-copilot.json +17 -0
- package/profiles/openai-api/gsd-defaults.json +26 -0
- package/profiles/openai-api.json +17 -0
- package/profiles/opencode-go/gsd-defaults.json +26 -0
- package/profiles/opencode-go.json +17 -0
- package/profiles/vertex-gemini/gsd-defaults.json +26 -0
- package/profiles/vertex-gemini.json +18 -0
- package/scripts/adhd-skill.mjs +12 -0
- package/scripts/bump-pins.mjs +104 -0
- package/scripts/check-private.sh +52 -0
- package/scripts/check-readme.mjs +131 -0
- package/scripts/ci-download.sh +20 -0
- package/scripts/ci-install-opencode-v2.sh +6 -0
- package/scripts/ci-latest-report.mjs +38 -0
- package/scripts/copilot-context-mode.mjs +33 -0
- package/scripts/labels.sh +55 -0
- package/scripts/lean.mjs +700 -0
- package/scripts/lib/adapters/antigravity.mjs +72 -0
- package/scripts/lib/adapters/claude.mjs +122 -0
- package/scripts/lib/adapters/copilot-cli.mjs +81 -0
- package/scripts/lib/adapters/cursor.mjs +60 -0
- package/scripts/lib/adapters/opencode-v1.mjs +86 -0
- package/scripts/lib/adapters/opencode-v2.mjs +168 -0
- package/scripts/lib/adapters/vscode-copilot.mjs +56 -0
- package/scripts/lib/adhd.mjs +28 -0
- package/scripts/lib/adopt.mjs +474 -0
- package/scripts/lib/agent-lifecycle.mjs +163 -0
- package/scripts/lib/copilot-usage.mjs +49 -0
- package/scripts/lib/doctor.mjs +207 -0
- package/scripts/lib/feedback.mjs +30 -0
- package/scripts/lib/fsops.mjs +291 -0
- package/scripts/lib/gsd.mjs +42 -0
- package/scripts/lib/inventory.mjs +195 -0
- package/scripts/lib/lean-update.mjs +30 -0
- package/scripts/lib/migrate.mjs +407 -0
- package/scripts/lib/network.mjs +79 -0
- package/scripts/lib/node-runtime.mjs +85 -0
- package/scripts/lib/parallel.mjs +265 -0
- package/scripts/lib/pins.mjs +47 -0
- package/scripts/lib/project.mjs +38 -0
- package/scripts/lib/redact.mjs +30 -0
- package/scripts/lib/render.mjs +101 -0
- package/scripts/lib/system.mjs +178 -0
- package/scripts/lib/terminals.mjs +218 -0
- package/scripts/lib/ui.mjs +34 -0
- package/scripts/lib/unverified.mjs +49 -0
- package/scripts/lib/upgrade.mjs +130 -0
- package/scripts/lib/verify-commit.mjs +16 -0
- package/scripts/lib/verify-sha256.mjs +20 -0
- package/scripts/lint-workflows.mjs +25 -0
- package/scripts/models-refresh.mjs +58 -0
- package/scripts/parallel.mjs +59 -0
- package/scripts/pins-latest.mjs +43 -0
- package/scripts/release.mjs +46 -0
- package/scripts/verify-pins.mjs +36 -0
- package/scripts/version-watch.mjs +118 -0
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// Parallel agent sessions: one git worktree per task, one worker agent in each, merged one at a time.
|
|
2
|
+
// Commands are argv arrays, never shell strings. State lives in <git common dir>/lean-agents/.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
7
|
+
import { loadProfile, modelFor } from './render.mjs';
|
|
8
|
+
import { which } from './system.mjs';
|
|
9
|
+
|
|
10
|
+
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
11
|
+
const LOG_TAIL_BYTES = 2000;
|
|
12
|
+
|
|
13
|
+
// User-facing tier names; profiles call the cheapest one "fast".
|
|
14
|
+
export const TIERS = { cheap: 'fast', balanced: 'balanced', strong: 'strong' };
|
|
15
|
+
const ROLE_TIER = { plan: 'strong', build: 'balanced', explore: 'cheap', research: 'cheap' };
|
|
16
|
+
const DEFAULT_PROFILE = { claude: 'claude-subscription', orca: 'claude-subscription' };
|
|
17
|
+
|
|
18
|
+
export function git(cwd, args) {
|
|
19
|
+
const r = spawnSync('git', args, { cwd, encoding: 'utf8' });
|
|
20
|
+
return { ok: r.status === 0, out: (r.stdout ?? '').trim(), err: (r.stderr ?? '').trim() };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function gitOrThrow(cwd, args) {
|
|
24
|
+
const r = git(cwd, args);
|
|
25
|
+
if (!r.ok) throw new Error(`git ${args.join(' ')}: ${r.err || r.out}`);
|
|
26
|
+
return r.out;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Task file: optional `---` front matter (role, tier, agent, check), then the prompt body.
|
|
30
|
+
export function parseTask(file) {
|
|
31
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
32
|
+
const name = path.basename(file).replace(/\.md$/, '');
|
|
33
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) throw new Error(`task file name "${name}" must be lowercase letters, digits and dashes`);
|
|
34
|
+
const meta = {};
|
|
35
|
+
let body = text;
|
|
36
|
+
const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
|
|
37
|
+
if (m) {
|
|
38
|
+
for (const line of m[1].split(/\r?\n/)) {
|
|
39
|
+
const kv = line.match(/^(\w+):\s*(.*)$/);
|
|
40
|
+
if (kv) meta[kv[1]] = kv[2].trim();
|
|
41
|
+
}
|
|
42
|
+
body = text.slice(m[0].length);
|
|
43
|
+
}
|
|
44
|
+
return { name, role: meta.role ?? 'build', tier: meta.tier, agent: meta.agent, check: meta.check, body };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function tierOf(task, override) {
|
|
48
|
+
const tier = override ?? task.tier ?? ROLE_TIER[task.role];
|
|
49
|
+
if (!tier) throw new Error(`task ${task.name}: unknown role "${task.role}" (use plan, build, explore or research, or set tier)`);
|
|
50
|
+
if (!TIERS[tier]) throw new Error(`task ${task.name}: unknown tier "${tier}" (use cheap, balanced or strong)`);
|
|
51
|
+
return tier;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Model for a tier through a profile; Claude aliases (haiku, sonnet, opus) come from claude-subscription.
|
|
55
|
+
export function tierModel(agent, tier, profileName) {
|
|
56
|
+
const profile = loadProfile(ROOT, profileName ?? DEFAULT_PROFILE[agent]);
|
|
57
|
+
return modelFor(profile, TIERS[tier])?.model ?? null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Only `Read <path> and follow it.` goes on the command line; the task text stays in the file.
|
|
61
|
+
export const instruction = (promptFile) => `Read ${promptFile} and follow it.`;
|
|
62
|
+
|
|
63
|
+
export function buildWorkerCommand({ agent, name, model, promptFile, dir, base }) {
|
|
64
|
+
const instr = instruction(promptFile);
|
|
65
|
+
if (agent === 'claude') {
|
|
66
|
+
return ['claude', '--bg', '-n', name, '--permission-mode', 'plan', ...(model ? ['--model', model] : []), instr];
|
|
67
|
+
}
|
|
68
|
+
if (agent === 'opencode') {
|
|
69
|
+
return ['opencode', 'run', '--title', name, '--agent', 'plan', ...(model ? ['-m', model] : []), '-f', promptFile, instr];
|
|
70
|
+
}
|
|
71
|
+
if (agent === 'orca') {
|
|
72
|
+
return ['orca', 'worktree', 'create', '--name', name, '--agent', 'claude', ...(model ? ['--model', model] : []),
|
|
73
|
+
'--prompt', instr, '--surface', 'terminal', '--base-branch', base, '--json'];
|
|
74
|
+
}
|
|
75
|
+
throw new Error(`no command for agent "${agent}"`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export const orcaAvailable = () => Boolean(which('orca')) && spawnSync('orca', ['agent-context', '--json'], { stdio: 'ignore' }).status === 0;
|
|
79
|
+
|
|
80
|
+
export function pickAgent(requested) {
|
|
81
|
+
if (requested && requested !== 'auto') return requested;
|
|
82
|
+
if (orcaAvailable()) return 'orca';
|
|
83
|
+
if (which('claude')) return 'claude';
|
|
84
|
+
if (which('opencode')) return 'opencode';
|
|
85
|
+
return 'print';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Quoted for display only, so the user can paste it into a terminal.
|
|
89
|
+
export const display = (argv) => argv.map((a) => (/^[\w./:=@%+-]+$/.test(a) ? a : `'${a.replace(/'/g, "'\\''")}'`)).join(' ');
|
|
90
|
+
|
|
91
|
+
export function repoInfo(cwd) {
|
|
92
|
+
const top = gitOrThrow(cwd, ['rev-parse', '--show-toplevel']);
|
|
93
|
+
const common = path.resolve(top, gitOrThrow(top, ['rev-parse', '--git-common-dir']));
|
|
94
|
+
return { top, stateDir: path.join(common, 'lean-agents') };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const workersFile = (stateDir) => path.join(stateDir, 'workers.json');
|
|
98
|
+
|
|
99
|
+
export function loadWorkers(stateDir) {
|
|
100
|
+
try { return JSON.parse(fs.readFileSync(workersFile(stateDir), 'utf8')); } catch { return { base: null, workers: [] }; }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function saveWorkers(stateDir, data) {
|
|
104
|
+
fs.mkdirSync(stateDir, { recursive: true });
|
|
105
|
+
fs.writeFileSync(workersFile(stateDir), `${JSON.stringify(data, null, 2)}\n`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export const statusOf = (stateDir, name) => {
|
|
109
|
+
try { return fs.readFileSync(path.join(stateDir, name, 'status'), 'utf8').trim() || 'running'; } catch { return 'running'; }
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
function logTail(stateDir, name) {
|
|
113
|
+
const file = path.join(stateDir, name, 'log');
|
|
114
|
+
if (!fs.existsSync(file)) return '';
|
|
115
|
+
const buf = fs.readFileSync(file);
|
|
116
|
+
return buf.subarray(Math.max(0, buf.length - LOG_TAIL_BYTES)).toString('utf8').trim().split('\n').slice(-5).join('\n');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function writePrompt(stateDir, task, statusFile) {
|
|
120
|
+
const dir = path.join(stateDir, task.name);
|
|
121
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
122
|
+
const promptFile = path.join(dir, 'task.md');
|
|
123
|
+
fs.writeFileSync(promptFile, [
|
|
124
|
+
task.body.trim(),
|
|
125
|
+
'',
|
|
126
|
+
'## Rules from the coordinator',
|
|
127
|
+
'- Work only in this worktree. Do not push. Commit your work on this branch.',
|
|
128
|
+
`- Report by writing one line to ${statusFile}: \`running\`, \`blocked: <question>\` or \`done\`.`,
|
|
129
|
+
'',
|
|
130
|
+
].join('\n'));
|
|
131
|
+
fs.writeFileSync(statusFile, 'running\n');
|
|
132
|
+
return promptFile;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Orca prefixes the branch with the user's handle; find it by suffix and rename it to lean/<name>.
|
|
136
|
+
function adoptOrcaBranch(top, name, branch) {
|
|
137
|
+
const list = gitOrThrow(top, ['worktree', 'list', '--porcelain']).split('\n\n').map((b) => ({
|
|
138
|
+
dir: (b.match(/^worktree (.*)$/m) ?? [])[1], branch: ((b.match(/^branch refs\/heads\/(.*)$/m) ?? [])[1]),
|
|
139
|
+
}));
|
|
140
|
+
const hit = list.find((w) => w.branch && (w.branch === name || w.branch.endsWith(`/${name}`)));
|
|
141
|
+
if (!hit) throw new Error(`Orca created no worktree for "${name}" (VERIFY the Orca output)`);
|
|
142
|
+
if (hit.branch !== branch) gitOrThrow(hit.dir, ['branch', '-m', hit.branch, branch]);
|
|
143
|
+
return hit.dir;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function start(cwd, files, opts = {}) {
|
|
147
|
+
const { top, stateDir } = repoInfo(cwd);
|
|
148
|
+
const data = loadWorkers(stateDir);
|
|
149
|
+
const base = opts.base ?? data.base ?? gitOrThrow(top, ['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
150
|
+
data.base = base;
|
|
151
|
+
const out = [];
|
|
152
|
+
for (const file of files) {
|
|
153
|
+
const task = parseTask(file);
|
|
154
|
+
if (data.workers.some((w) => w.name === task.name)) throw new Error(`worker "${task.name}" already exists; run clean first`);
|
|
155
|
+
const agent = pickAgent(task.agent ?? opts.agent);
|
|
156
|
+
const tier = tierOf(task, opts.tier);
|
|
157
|
+
const modelAgent = agent === 'print' ? 'claude' : agent;
|
|
158
|
+
const model = opts.model ?? tierModel(modelAgent, tier, opts.profile);
|
|
159
|
+
const branch = `lean/${task.name}`;
|
|
160
|
+
const promptFile = writePrompt(stateDir, task, path.join(stateDir, task.name, 'status'));
|
|
161
|
+
const logFile = path.join(stateDir, task.name, 'log');
|
|
162
|
+
const worker = { name: task.name, branch, base, agent, tier, model, check: task.check ?? null, dir: null };
|
|
163
|
+
let argv;
|
|
164
|
+
if (agent === 'orca') {
|
|
165
|
+
argv = buildWorkerCommand({ agent, name: task.name, model, promptFile, base });
|
|
166
|
+
const r = spawnSync(argv[0], argv.slice(1), { cwd: top, encoding: 'utf8' });
|
|
167
|
+
fs.writeFileSync(logFile, `${r.stdout ?? ''}${r.stderr ?? ''}`);
|
|
168
|
+
if (r.status !== 0) throw new Error(`orca worktree create failed: ${(r.stderr ?? '').trim()}`);
|
|
169
|
+
worker.dir = adoptOrcaBranch(top, task.name, branch);
|
|
170
|
+
} else {
|
|
171
|
+
worker.dir = path.join(`${top}.lean`, task.name);
|
|
172
|
+
if (agent === 'custom' && !opts.cmd) throw new Error('--agent custom needs --cmd <program>');
|
|
173
|
+
gitOrThrow(top, ['worktree', 'add', '-b', branch, worker.dir, base]);
|
|
174
|
+
data.workers.push(worker);
|
|
175
|
+
saveWorkers(stateDir, data);
|
|
176
|
+
if (agent === 'custom') {
|
|
177
|
+
argv = [opts.cmd, promptFile];
|
|
178
|
+
} else if (agent !== 'print') {
|
|
179
|
+
argv = buildWorkerCommand({ agent, name: task.name, model, promptFile, dir: worker.dir });
|
|
180
|
+
}
|
|
181
|
+
if (agent === 'print' || (agent !== 'custom' && !which(argv[0]))) {
|
|
182
|
+
argv = buildWorkerCommand({ agent: 'claude', name: task.name, model, promptFile, dir: worker.dir });
|
|
183
|
+
worker.agent = 'print';
|
|
184
|
+
worker.command = `cd ${display([worker.dir])} && ${display(argv)}`;
|
|
185
|
+
} else {
|
|
186
|
+
const fd = fs.openSync(logFile, 'a');
|
|
187
|
+
// OpenCode has no --dir flag in 2.1.4, so the worker's working directory is the worktree.
|
|
188
|
+
spawn(argv[0], argv.slice(1), { cwd: worker.dir, detached: true, stdio: ['ignore', fd, fd] }).unref();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (!data.workers.includes(worker)) data.workers.push(worker);
|
|
192
|
+
saveWorkers(stateDir, data);
|
|
193
|
+
out.push(worker);
|
|
194
|
+
}
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export function status(cwd) {
|
|
199
|
+
const { stateDir } = repoInfo(cwd);
|
|
200
|
+
return loadWorkers(stateDir).workers.map((w) => ({
|
|
201
|
+
...w,
|
|
202
|
+
status: statusOf(stateDir, w.name),
|
|
203
|
+
tail: logTail(stateDir, w.name),
|
|
204
|
+
}));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Merges one finished worker, in start order, then rebases the others onto the new base.
|
|
208
|
+
export function merge(cwd, name) {
|
|
209
|
+
const { top, stateDir } = repoInfo(cwd);
|
|
210
|
+
const data = loadWorkers(stateDir);
|
|
211
|
+
const w = data.workers.find((x) => x.name === name);
|
|
212
|
+
if (!w) throw new Error(`no worker "${name}"`);
|
|
213
|
+
if (w.merged) throw new Error(`worker "${name}" is already merged`);
|
|
214
|
+
const next = data.workers.find((x) => !x.merged);
|
|
215
|
+
if (next.name !== name) throw new Error(`merge "${next.name}" first (start order)`);
|
|
216
|
+
const st = statusOf(stateDir, name);
|
|
217
|
+
if (st !== 'done') throw new Error(`worker "${name}" is "${st}", not done`);
|
|
218
|
+
if (git(w.dir, ['status', '--porcelain']).out) throw new Error(`worker "${name}" has uncommitted changes in ${w.dir}`);
|
|
219
|
+
if (git(top, ['rev-parse', '--abbrev-ref', 'HEAD']).out !== data.base) throw new Error(`check out ${data.base} in ${top} first`);
|
|
220
|
+
if (git(top, ['status', '--porcelain', '--untracked-files=no']).out) throw new Error(`${top} has uncommitted changes`);
|
|
221
|
+
if (w.check) {
|
|
222
|
+
const [bin, ...args] = w.check.split(/\s+/);
|
|
223
|
+
const r = spawnSync(bin, args, { cwd: w.dir, encoding: 'utf8' });
|
|
224
|
+
if (r.status !== 0) throw new Error(`check "${w.check}" failed:\n${(r.stdout ?? '').slice(-LOG_TAIL_BYTES)}${(r.stderr ?? '').slice(-LOG_TAIL_BYTES)}`);
|
|
225
|
+
}
|
|
226
|
+
const m = git(top, ['merge', '--no-ff', '--no-edit', w.branch]);
|
|
227
|
+
if (!m.ok) { git(top, ['merge', '--abort']); throw new Error(`merge of "${name}" failed: ${m.err || m.out}\nIf it conflicts, rebase it on ${data.base} in ${w.dir} and retry`); }
|
|
228
|
+
w.merged = true;
|
|
229
|
+
saveWorkers(stateDir, data);
|
|
230
|
+
const rebased = [];
|
|
231
|
+
const skipped = [];
|
|
232
|
+
for (const o of data.workers) {
|
|
233
|
+
if (o.merged) continue;
|
|
234
|
+
// A running worker has a dirty tree and would be disturbed; it rebases itself or at its own merge.
|
|
235
|
+
if (statusOf(stateDir, o.name) !== 'done' || git(o.dir, ['status', '--porcelain']).out) { skipped.push(o.name); continue; }
|
|
236
|
+
if (git(o.dir, ['rebase', data.base]).ok) rebased.push(o.name);
|
|
237
|
+
else { git(o.dir, ['rebase', '--abort']); skipped.push(o.name); }
|
|
238
|
+
}
|
|
239
|
+
if (skipped.length) console.error(`not rebased (running, dirty or conflicting): ${skipped.join(', ')}; rebase them in their worktree before their merge`);
|
|
240
|
+
return rebased;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Removes only workers this helper created, only when merged; never --force.
|
|
244
|
+
export function clean(cwd) {
|
|
245
|
+
const { top, stateDir } = repoInfo(cwd);
|
|
246
|
+
const data = loadWorkers(stateDir);
|
|
247
|
+
const kept = [];
|
|
248
|
+
const removed = [];
|
|
249
|
+
for (const w of data.workers) {
|
|
250
|
+
if (!w.merged) { kept.push(w); continue; }
|
|
251
|
+
if (fs.existsSync(w.dir)) gitOrThrow(top, ['worktree', 'remove', w.dir]);
|
|
252
|
+
if (git(top, ['rev-parse', '--verify', '-q', w.branch]).ok) gitOrThrow(top, ['branch', '-d', w.branch]);
|
|
253
|
+
fs.rmSync(path.join(stateDir, w.name), { recursive: true, force: true });
|
|
254
|
+
removed.push(w.name);
|
|
255
|
+
}
|
|
256
|
+
if (kept.length) saveWorkers(stateDir, { ...data, workers: kept });
|
|
257
|
+
else fs.rmSync(workersFile(stateDir), { force: true });
|
|
258
|
+
try { fs.rmdirSync(`${top}.lean`); } catch { /* not empty or absent */ }
|
|
259
|
+
return { removed, kept: kept.map((w) => w.name) };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// For --doctor: workers left in the repo at `cwd`, if it is one.
|
|
263
|
+
export function leftovers(cwd) {
|
|
264
|
+
try { return loadWorkers(repoInfo(cwd).stateDir).workers.map((w) => w.name); } catch { return []; }
|
|
265
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Known-good versions of everything fetched at run time (core/pins.json).
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'core', 'pins.json');
|
|
7
|
+
export const PINS = JSON.parse(fs.readFileSync(FILE, 'utf8')).pins;
|
|
8
|
+
|
|
9
|
+
function pin(key) {
|
|
10
|
+
const p = PINS[key];
|
|
11
|
+
if (!p) throw new Error(`no pin for ${key} in core/pins.json`);
|
|
12
|
+
return p;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const npmSpec = (key) => `${pin(key).source}@${pin(key).version}`;
|
|
16
|
+
// owner/repo#ref: `skills add` ignores a trailing @tag (installs HEAD) but honors #tag and #<commit sha> (verified skills 1.5.18 and 1.7.4).
|
|
17
|
+
// A pin without `sha` (lean-update until its tag exists) falls back to the tag.
|
|
18
|
+
export const skillSource = (key) => `${pin(key).source}#${pin(key).sha ?? pin(key).version}`;
|
|
19
|
+
// `claude plugin marketplace add owner/repo#<sha>` fails (checked 2026-11-10), so marketplaces pin by tag only.
|
|
20
|
+
export const marketplaceSource = (key) => `${pin(key).source}#${pin(key).version}`;
|
|
21
|
+
// What `uvx --from` takes: the commit SHA, so a moved tag cannot change what runs.
|
|
22
|
+
export const gitSpec = (key) => `git+https://github.com/${pin(key).source}@${pin(key).sha}`;
|
|
23
|
+
// npm or git spec for a {pin:key} placeholder in core/mcp.json.
|
|
24
|
+
export const pinSpec = (key) => (pin(key).kind === 'git' ? gitSpec(key) : npmSpec(key));
|
|
25
|
+
// The `engines.node` range the pinned npm version declares (">=24.15.0"), or undefined when it declares none.
|
|
26
|
+
export const nodeRange = (key) => pin(key).node;
|
|
27
|
+
export const bunPin = () => pin('bun');
|
|
28
|
+
export const skillsCli = () => npmSpec('skills-cli');
|
|
29
|
+
// `download` pins (Bun) are verified by SHA256 at install time and not tracked in state.json.
|
|
30
|
+
const tracked = (p) => !p.ciOnly && p.kind !== 'download';
|
|
31
|
+
export const pinVersions = () => Object.fromEntries(Object.entries(PINS).filter(([, p]) => tracked(p)).map(([k, p]) => [k, p.version]));
|
|
32
|
+
|
|
33
|
+
// Pin keys that differ from the tool name lean-agents saves in state.json options.tools.
|
|
34
|
+
const PIN_TOOL = { 'playwright-mcp': 'playwright', 'gsd-core': 'gsd', 'opencode-dcp': 'dcp', 'ponytail-plugin': 'ponytail', 'context-mode-plugin': 'context-mode' };
|
|
35
|
+
export const pinTool = (key) => PIN_TOOL[key] ?? key;
|
|
36
|
+
// True when the saved options use this pin; the Skills CLI and the lean-update skill ride along with every install.
|
|
37
|
+
export const pinInUse = (key, options) => key === 'skills-cli' || key === 'lean-update'
|
|
38
|
+
|| (key === 'orca-cli' ? (options.terminals ?? []).includes('orca')
|
|
39
|
+
: key === 'warp-opencode' ? (options.terminals ?? []).includes('warp')
|
|
40
|
+
: (options.tools ?? []).includes(PIN_TOOL[key] ?? key));
|
|
41
|
+
|
|
42
|
+
// [{ tool, installed, pinned }] for pins in use whose saved version differs from core/pins.json now.
|
|
43
|
+
export function behindPins(saved) {
|
|
44
|
+
return Object.entries(saved.pins ?? {})
|
|
45
|
+
.filter(([k, v]) => PINS[k] && tracked(PINS[k]) && PINS[k].version !== v && pinInUse(k, saved.options))
|
|
46
|
+
.map(([tool, installed]) => ({ tool, installed, pinned: PINS[tool].version }));
|
|
47
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// --project mode: the shared setup inside one repository, so a team gets it through git.
|
|
2
|
+
// Rules live once in AGENTS.md; the Copilot and Cursor files only point to it.
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { OWNED_MARK, sha } from './fsops.mjs';
|
|
5
|
+
import { loadCore, renderRules, loadProfile } from './render.mjs';
|
|
6
|
+
import { renderCopilotAgent } from './adapters/copilot-cli.mjs';
|
|
7
|
+
import { vscodeServers } from './adapters/vscode-copilot.mjs';
|
|
8
|
+
import { cursorServers, renderCursorAgent } from './adapters/cursor.mjs';
|
|
9
|
+
|
|
10
|
+
const POINTER = 'Follow the shared rules in `AGENTS.md` at the repository root.';
|
|
11
|
+
|
|
12
|
+
// State holds absolute paths, so it stays in the user's home, never in the repository.
|
|
13
|
+
export function projectStateDir(home, dir) {
|
|
14
|
+
return path.join(home, '.config', 'lean-agents', 'projects', sha(dir).slice(0, 12));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function projectPlan(root, dir, o) {
|
|
18
|
+
const core = loadCore(root);
|
|
19
|
+
const profile = loadProfile(root, 'github-copilot');
|
|
20
|
+
const actions = [
|
|
21
|
+
{ kind: 'block', path: path.join(dir, 'AGENTS.md'), body: renderRules(root, o) },
|
|
22
|
+
{ kind: 'block', path: path.join(dir, '.github', 'copilot-instructions.md'), body: `${POINTER}\n` },
|
|
23
|
+
{
|
|
24
|
+
kind: 'file',
|
|
25
|
+
path: path.join(dir, '.cursor', 'rules', 'lean-agents.mdc'),
|
|
26
|
+
content: ['---', 'description: Shared team rules from lean-agents', 'alwaysApply: true', '---', `<!-- ${OWNED_MARK} -->`, POINTER, ''].join('\n'),
|
|
27
|
+
},
|
|
28
|
+
];
|
|
29
|
+
for (const agent of core.agents) {
|
|
30
|
+
actions.push({ kind: 'file', path: path.join(dir, '.github', 'agents', `${agent.name}.agent.md`), content: renderCopilotAgent(agent, profile, o.network.outbound !== 'off') });
|
|
31
|
+
actions.push({ kind: 'file', path: path.join(dir, '.cursor', 'agents', `${agent.name}.md`), content: renderCursorAgent(agent) });
|
|
32
|
+
}
|
|
33
|
+
const vscode = vscodeServers(core, o.tools);
|
|
34
|
+
if (vscode.length) actions.push({ kind: 'json', path: path.join(dir, '.vscode', 'mcp.json'), edits: vscode });
|
|
35
|
+
const cursor = cursorServers(core, o.tools);
|
|
36
|
+
if (cursor.length) actions.push({ kind: 'json', path: path.join(dir, '.cursor', 'mcp.json'), edits: cursor });
|
|
37
|
+
return { actions, commands: [] };
|
|
38
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Redaction of free text that may reach a public issue or a log.
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import { PROXY_VARS, CA_VARS, SECRET_NAME } from './network.mjs';
|
|
4
|
+
|
|
5
|
+
const esc = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
6
|
+
|
|
7
|
+
// Home paths, the user and host names, proxy and CA values, secret env values, emails and tokens never get through.
|
|
8
|
+
export function redactText(text, { home, env = process.env, user = env.USER || env.USERNAME, host = os.hostname() } = {}) {
|
|
9
|
+
let out = String(text);
|
|
10
|
+
const named = [...PROXY_VARS, ...CA_VARS].flatMap((n) => [env[n], env[n.toLowerCase()]]).filter((v) => v && v.length > 3);
|
|
11
|
+
const secrets = Object.entries(env).filter(([k, v]) => SECRET_NAME.test(k) && v && v.length >= 8).map(([, v]) => v);
|
|
12
|
+
for (const v of new Set([...named, ...secrets])) out = out.replace(new RegExp(esc(v), 'g'), '<redacted>');
|
|
13
|
+
out = out.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s/@]*@[^\s]*/gi, '<redacted-url>');
|
|
14
|
+
for (const h of [home].flat().filter(Boolean)) out = out.replace(new RegExp(`${esc(h).replace(/\\\\|\//g, '[\\\\/]')}(?=[\\\\/]|$|[^\\w.-])`, 'gi'), '~');
|
|
15
|
+
out = out
|
|
16
|
+
.replace(/(\/Users\/|\/home\/|[A-Za-z]:[\\/]Users[\\/])[^\/\\\s]+/gi, '$1<user>')
|
|
17
|
+
.replace(/(^|[\s"'=:(])\/root(?=[\/\s"')]|$)/g, '$1/<user>')
|
|
18
|
+
.replace(/(\/private)?\/var\/folders\/[^\/\s]+\/[^\/\s]+/g, '/var/folders/<tmp>')
|
|
19
|
+
.replace(/\/private\/var\/[^\/\s]+/g, '/private/var/<tmp>');
|
|
20
|
+
if (user && user.length > 1) out = out.replace(new RegExp(`\\b${esc(user)}\\b`, 'g'), '<user>');
|
|
21
|
+
if (host && host.length > 2) out = out.replace(new RegExp(`\\b${esc(host)}\\b`, 'gi'), '<host>');
|
|
22
|
+
return out
|
|
23
|
+
.replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g, '<email>')
|
|
24
|
+
.replace(/\bAuthorization(["']?\s*[:=]\s*["']?)(Basic|Bearer|Token)\s+[^\s"',;]+/gi, 'Authorization$1$2 <token>')
|
|
25
|
+
.replace(/\beyJ[\w-]+\.eyJ[\w-]+\.[\w-]+/g, '<token>')
|
|
26
|
+
.replace(/\b(gh[pousr]_|github_pat_|sk-|xox[bp]-|glpat-|ya29\.|(?:sk|rk)_(?:live|test)_)[\w-]{8,}|\bnpm_[A-Za-z0-9]{8,}\b|\bhf_[A-Za-z0-9]{8,}\b|\bAKIA[0-9A-Z]{12,}|\bAIza[\w-]{20,}/g, '<token>')
|
|
27
|
+
.replace(/(aws_secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{40}/gi, '$1<token>')
|
|
28
|
+
.replace(/\b(Bearer|token)\s+[\w.~+/=-]{8,}/gi, '$1 <token>')
|
|
29
|
+
.replace(/\b([\w-]*(?:api[_-]?key|password|passwd|secret|token)["']?\s*[:=]\s*["']?)[^\s"',;&]+/gi, '$1<redacted>');
|
|
30
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Renders core/ (rules, neutral subagents) and resolves model tiers from profiles/.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pinSpec } from './pins.mjs';
|
|
5
|
+
|
|
6
|
+
export function loadCore(root) {
|
|
7
|
+
const agentsDir = path.join(root, 'core', 'agents');
|
|
8
|
+
const agents = fs
|
|
9
|
+
.readdirSync(agentsDir)
|
|
10
|
+
.filter((f) => f.endsWith('.md'))
|
|
11
|
+
.sort()
|
|
12
|
+
.map((f) => parseAgent(fs.readFileSync(path.join(agentsDir, f), 'utf8')));
|
|
13
|
+
const mcp = JSON.parse(fs.readFileSync(path.join(root, 'core', 'mcp.json'), 'utf8')).servers;
|
|
14
|
+
// "{pin:key}" in a command stands for source@version from core/pins.json.
|
|
15
|
+
for (const s of Object.values(mcp)) s.command = s.command.map((a) => a.replace(/^\{pin:([\w-]+)\}$/, (_, k) => pinSpec(k)));
|
|
16
|
+
return { agents, mcp };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Registers a tool's absolute `node_command` (the plugin-less form) instead of its npx command; {node} and {modules} come from the toolNode.
|
|
20
|
+
// `nvmDir` (the nvm lean-agents may use, even when no tool needs it now) adds the absolute shapes lean-agents itself writes there to `legacy`,
|
|
21
|
+
// so a rerun flips an entry either way; only those exact shapes (any digits version) are replaced, never one the user wrote.
|
|
22
|
+
export function useToolNode(core, toolNode, nvm) {
|
|
23
|
+
const s = core.mcp['context-mode'];
|
|
24
|
+
if (nvm && s?.node_command) {
|
|
25
|
+
const v = nvm.win ? path.join(nvm.dir, 'v{semver}') : path.join(nvm.dir, 'versions', 'node', 'v{semver}');
|
|
26
|
+
const node = nvm.win ? path.join(v, 'node.exe') : path.join(v, 'bin', 'node');
|
|
27
|
+
const cli = path.join(nvm.win ? path.join(v, 'node_modules') : path.join(v, 'lib', 'node_modules'), 'context-mode', 'cli.mjs');
|
|
28
|
+
s.legacy = [...(s.legacy ?? []), [node, cli, 'server']];
|
|
29
|
+
}
|
|
30
|
+
if (!toolNode || !s?.node_command) return core;
|
|
31
|
+
s.command = s.node_command.map((a) => a.replace('{node}', toolNode.node).replace(/^\{modules\}\/(.*)$/, (_, rest) => path.join(toolNode.modules, rest)));
|
|
32
|
+
return core;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function parseAgent(text) {
|
|
36
|
+
const m = text.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
|
|
37
|
+
if (!m) throw new Error('agent file needs YAML frontmatter');
|
|
38
|
+
const meta = {};
|
|
39
|
+
for (const line of m[1].split('\n')) {
|
|
40
|
+
const kv = line.match(/^(\w+):\s*(.*?)\s*(#.*)?$/);
|
|
41
|
+
if (kv) meta[kv[1]] = kv[2];
|
|
42
|
+
}
|
|
43
|
+
return { ...meta, body: m[2].trim() };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const TEXT = {
|
|
47
|
+
en: {
|
|
48
|
+
lang: 'Always reply in English.',
|
|
49
|
+
serena: ', Serena symbol tools',
|
|
50
|
+
contextMode: '- Output that may pass 20 lines or that you will filter (logs, test runs, CI, API responses): use Context Mode (`ctx_batch_execute`, `ctx_execute`) and print only the answer you derive. RTK compression does not replace this.\n- Web pages: `ctx_fetch_and_index`, then `ctx_search`.\n- Short output you only read, and commands that change state (git, installs): plain shell.\n',
|
|
51
|
+
playwright: '- Real browser actions (clicks, forms, screenshots): Playwright.\n',
|
|
52
|
+
load: '- If one of these tools is deferred or not loaded, load it first (Claude Code: `ToolSearch`). Do not fall back to the shell for that reason.\n',
|
|
53
|
+
},
|
|
54
|
+
es: {
|
|
55
|
+
lang: 'Responde siempre en español.',
|
|
56
|
+
serena: ', símbolos con Serena',
|
|
57
|
+
contextMode: '- Salidas que puedan pasar de 20 líneas o que vayas a filtrar (logs, tests, CI, respuestas de API): usa Context Mode (`ctx_batch_execute`, `ctx_execute`) e imprime solo la respuesta derivada. La compresión de RTK no reemplaza esto.\n- Páginas web: `ctx_fetch_and_index`, luego `ctx_search`.\n- Salidas cortas que solo vas a leer y comandos que cambian estado (git, instalaciones): shell normal.\n',
|
|
58
|
+
playwright: '- Acciones reales en el navegador (clics, formularios, capturas): Playwright.\n',
|
|
59
|
+
load: '- Si una de estas herramientas está diferida o sin cargar, cárgala primero (Claude Code: `ToolSearch`). No vuelvas al shell por esa razón.\n',
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export function renderRules(root, { lang, tools, agents = [] }) {
|
|
64
|
+
const file = lang === 'es' ? 'AGENTS.es.md' : 'AGENTS.md';
|
|
65
|
+
const t = TEXT[lang] ?? TEXT.en;
|
|
66
|
+
// Claude Code has Claude in Chrome, so playwright-extension alone adds nothing for a Claude-only install.
|
|
67
|
+
const effective = agents.length === 1 && agents[0] === 'claude' ? tools.filter((n) => n !== 'playwright-extension') : tools;
|
|
68
|
+
const hasTool = (...names) => names.some((name) => effective.includes(name));
|
|
69
|
+
const toolRules =
|
|
70
|
+
(hasTool('context-mode') ? t.contextMode : '') +
|
|
71
|
+
(hasTool('playwright', 'playwright-extension') ? t.playwright : '') +
|
|
72
|
+
(hasTool('context-mode', 'playwright', 'playwright-extension', 'serena') ? t.load : '');
|
|
73
|
+
const header = `<!-- ${'managed by lean-agents'}: edit core/AGENTS.md upstream or add your own rules in a separate file -->\n`;
|
|
74
|
+
return (
|
|
75
|
+
header +
|
|
76
|
+
fs
|
|
77
|
+
.readFileSync(path.join(root, 'core', file), 'utf8')
|
|
78
|
+
.replace('{{LANG_RULE}}', t.lang)
|
|
79
|
+
.replace('{{SERENA_HINT}}', tools.includes('serena') ? t.serena : '')
|
|
80
|
+
.replace('{{TOOL_RULES}}', toolRules)
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function loadProfile(root, name) {
|
|
85
|
+
if (!name) return null;
|
|
86
|
+
const file = path.join(root, 'profiles', `${name}.json`);
|
|
87
|
+
if (!fs.existsSync(file)) {
|
|
88
|
+
const known = fs.readdirSync(path.join(root, 'profiles')).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5));
|
|
89
|
+
throw new Error(`unknown profile "${name}". Available: ${known.join(', ')}`);
|
|
90
|
+
}
|
|
91
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Tier for an agent name, honoring per-profile overrides (e.g. review on fast for Claude).
|
|
95
|
+
export function tierFor(profile, agentName, defaultTier) {
|
|
96
|
+
return profile?.overrides?.[agentName] ?? defaultTier;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function modelFor(profile, tier) {
|
|
100
|
+
return profile?.tiers?.[tier] ?? null;
|
|
101
|
+
}
|