levi-gear 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +135 -2
  3. package/agents/_team-protocol.md +41 -0
  4. package/agents/designer.md +25 -0
  5. package/agents/developer.md +23 -0
  6. package/agents/pm.md +28 -0
  7. package/agents/qa.md +24 -0
  8. package/agents/teamlead.md +26 -0
  9. package/bin/levi.js +2 -0
  10. package/package.json +16 -4
  11. package/src/cli.js +51 -0
  12. package/src/commands/init.js +43 -0
  13. package/src/commands/list.js +19 -0
  14. package/src/commands/status.js +17 -0
  15. package/src/commands/update.js +29 -0
  16. package/src/lib/agents.js +62 -0
  17. package/src/lib/config.js +27 -0
  18. package/src/lib/desired-state.js +93 -0
  19. package/src/lib/frontmatter.js +36 -0
  20. package/src/lib/report.js +21 -0
  21. package/src/lib/role-skills.js +23 -0
  22. package/src/lib/router.js +38 -0
  23. package/src/lib/sync.js +110 -0
  24. package/src/lib/tools.js +98 -0
  25. package/src/lib/usecases.js +109 -0
  26. package/usecases/.gitkeep +0 -0
  27. package/usecases/brainstorming/SKILL.md +84 -0
  28. package/usecases/code-review/SKILL.md +79 -0
  29. package/usecases/code-review/references/performance-and-correctness.md +101 -0
  30. package/usecases/code-review/references/review-guide.md +70 -0
  31. package/usecases/code-review/references/security.md +119 -0
  32. package/usecases/create-feature/SKILL.md +94 -0
  33. package/usecases/create-feature/scripts/lock-tests.mjs +66 -0
  34. package/usecases/create-feature/workflow.js +440 -0
  35. package/usecases/design/SKILL.md +61 -0
  36. package/usecases/design/references/svg-guide.md +14 -0
  37. package/usecases/design/scripts/check-svg.py +77 -0
  38. package/usecases/fix-bug/SKILL.md +96 -0
  39. package/usecases/fix-bug/workflow.js +298 -0
  40. package/usecases/generate-test-scenarios/SKILL.md +97 -0
  41. package/usecases/generate-test-scenarios/references/test-case-guide.md +171 -0
  42. package/usecases/generate-test-scenarios/scripts/render-test-cases-markdown.mjs +76 -0
  43. package/usecases/generate-test-scenarios/scripts/render-test-cases.mjs +68 -0
  44. package/usecases/generate-test-scenarios/scripts/test-case-fields.mjs +63 -0
  45. package/usecases/generate-test-scenarios/scripts/validate-test-cases.mjs +69 -0
  46. package/usecases/generate-test-scenarios/scripts/write-xlsx.mjs +157 -0
  47. package/usecases/spec-writing/SKILL.md +59 -0
  48. package/usecases/spec-writing/references/spec-guide.md +62 -0
@@ -0,0 +1,93 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { ROUTER_NAME, skillName } = require('./usecases');
4
+ const { CODEX_SKILL_DIR, CODEX_POLICY, skillDirs, skillDirFor, AGENT_TARGETS } = require('./tools');
5
+ const { withRoleSkills } = require('./role-skills');
6
+ const { setField } = require('./frontmatter');
7
+ const { renderRouter } = require('./router');
8
+
9
+ // Group keys say which part of the kit a file belongs to; they decide where its hash is
10
+ // recorded in .levi.json.
11
+ const usecaseGroup = (id) => `usecase:${id}`;
12
+
13
+ // Relative posix paths of every file under `dir`, leaving out the top-level agents/ folder
14
+ // (those become subagent files elsewhere).
15
+ function walk(dir, skipAgents, base = '') {
16
+ return fs.readdirSync(path.join(dir, base), { withFileTypes: true }).flatMap((entry) => {
17
+ const rel = base ? `${base}/${entry.name}` : entry.name;
18
+ if (entry.isDirectory()) return skipAgents && !base && entry.name === 'agents' ? [] : walk(dir, skipAgents, rel);
19
+ return [rel];
20
+ });
21
+ }
22
+
23
+ function put(out, rel, content, group) {
24
+ out.set(rel, { content: Buffer.from(content), group });
25
+ }
26
+
27
+ // Every levi skill runs only when the user invokes it: Claude Code and Copilot read the
28
+ // frontmatter flag, Codex reads agents/openai.yaml (only written where Codex looks).
29
+ function addSkill(out, usecase, dir) {
30
+ const root = path.posix.join(dir, skillName(usecase.id));
31
+ for (const rel of walk(usecase.dir, true)) {
32
+ let content = fs.readFileSync(path.join(usecase.dir, rel));
33
+ if (rel === 'SKILL.md') content = setField(content.toString('utf8'), 'disable-model-invocation', 'true');
34
+ put(out, path.posix.join(root, rel), content, usecaseGroup(usecase.id));
35
+ }
36
+ if (dir === CODEX_SKILL_DIR) put(out, path.posix.join(root, 'agents/openai.yaml'), CODEX_POLICY, usecaseGroup(usecase.id));
37
+ }
38
+
39
+ // `prepare` adapts an agent to one tool before it is rendered (team agents get their role skills).
40
+ function addAgents(out, agents, tools, group, prepare = (agent) => agent) {
41
+ for (const tool of tools) {
42
+ const target = AGENT_TARGETS[tool];
43
+ for (const agent of agents) put(out, path.posix.join(target.dir, agent.name + target.ext), target.render(prepare(agent, tool)), group);
44
+ }
45
+ }
46
+
47
+ // The `levi` entry point is generated from whatever usecases are installed.
48
+ function addRouter(out, usecases, team, tools) {
49
+ if (!usecases.length) return;
50
+ for (const dir of skillDirs(tools)) {
51
+ const root = path.posix.join(dir, ROUTER_NAME);
52
+ put(out, path.posix.join(root, 'SKILL.md'), renderRouter(dir, usecases, team), 'router');
53
+ if (dir === CODEX_SKILL_DIR) put(out, path.posix.join(root, 'agents/openai.yaml'), CODEX_POLICY, 'router');
54
+ }
55
+ }
56
+
57
+ // `ids` plus every usecase they require, directly or not, each once.
58
+ function withRequired(byId, ids) {
59
+ const all = [];
60
+ const visit = (id) => {
61
+ if (all.includes(id)) return;
62
+ all.push(id);
63
+ if (byId.has(id)) byId.get(id).requires.forEach(visit);
64
+ };
65
+ ids.forEach(visit);
66
+ return all;
67
+ }
68
+
69
+ // The files a clean install of `ids` (and what they require) for `tools` would contain: Map of
70
+ // project-relative path to { content, group }. Nothing is written here. Usecases that are a team
71
+ // role's skill are always installed, since the team always is and its agents rely on them.
72
+ function build(kit, ids, tools) {
73
+ const byId = new Map(kit.usecases.map((u) => [u.id, u]));
74
+ const out = new Map();
75
+ const missing = [];
76
+ const present = [];
77
+ const roleSkills = kit.usecases.filter((u) => u.skill).map((u) => u.id);
78
+ for (const id of withRequired(byId, [...ids, ...roleSkills])) {
79
+ if (!byId.has(id)) {
80
+ missing.push(id);
81
+ continue;
82
+ }
83
+ const usecase = byId.get(id);
84
+ present.push(usecase);
85
+ for (const dir of skillDirs(tools)) addSkill(out, usecase, dir);
86
+ addAgents(out, usecase.agents, tools, usecaseGroup(id));
87
+ }
88
+ addRouter(out, present, kit.team, tools);
89
+ addAgents(out, kit.team, tools, 'team', (agent, tool) => withRoleSkills(agent, present, skillDirFor(tool, tools)));
90
+ return { files: out, missing, ids: present.map((u) => u.id) };
91
+ }
92
+
93
+ module.exports = { build, usecaseGroup };
@@ -0,0 +1,36 @@
1
+ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
2
+ const BLOCK_SCALAR = /^([>|])[+-]?$/;
3
+
4
+ // Flat "key: value" pairs, plus YAML folded (>) and literal (|) multi-line values.
5
+ function parse(text) {
6
+ const match = FRONTMATTER.exec(text);
7
+ if (!match) return { data: {}, body: text };
8
+ const data = {};
9
+ const lines = match[1].split(/\r?\n/);
10
+ for (let i = 0; i < lines.length; i++) {
11
+ const idx = lines[i].indexOf(':');
12
+ if (idx === -1) continue;
13
+ const key = lines[i].slice(0, idx).trim();
14
+ let value = lines[i].slice(idx + 1).trim();
15
+ const block = BLOCK_SCALAR.exec(value);
16
+ if (block) {
17
+ const parts = [];
18
+ while (i + 1 < lines.length && /^\s+\S|^\s*$/.test(lines[i + 1])) parts.push(lines[++i].trim());
19
+ value = parts.join(block[1] === '>' ? ' ' : '\n').trim();
20
+ } else {
21
+ value = value.replace(/^["']|["']$/g, '');
22
+ }
23
+ if (key) data[key] = value;
24
+ }
25
+ return { data, body: match[2] };
26
+ }
27
+
28
+ // Sets a single-line top-level field, replacing any existing line with the same key.
29
+ function setField(text, key, value) {
30
+ const match = FRONTMATTER.exec(text);
31
+ if (!match) return text;
32
+ const lines = match[1].split(/\r?\n/).filter((line) => !line.startsWith(`${key}:`));
33
+ return `---\n${[...lines, `${key}: ${value}`].join('\n')}\n---\n${match[2]}`;
34
+ }
35
+
36
+ module.exports = { parse, setField };
@@ -0,0 +1,21 @@
1
+ const paths = (actions, op) => actions.filter((a) => a.op === op).map((a) => a.path);
2
+
3
+ function section(title, list) {
4
+ if (list.length) console.log(`\n${title}\n${list.map((p) => ` ${p}`).join('\n')}`);
5
+ }
6
+
7
+ // Summarizes what a sync did (or, for dryRun, would do) to the user's files.
8
+ function printReport(actions, { dryRun = false } = {}) {
9
+ const verb = dryRun ? ['Would add', 'update', 'remove'] : ['Added', 'updated', 'removed'];
10
+ const count = (op) => actions.filter((a) => a.op === op).length;
11
+ console.log(`${verb[0]} ${count('add')}, ${verb[1]} ${count('update')}, ${verb[2]} ${count('remove')} file(s).`);
12
+ section('Changed by you (kept as is):', paths(actions, 'customized'));
13
+ section('Already exist and are not managed by levi (kept as is):', paths(actions, 'conflict'));
14
+ section('Deleted by you (not recreated):', paths(actions, 'keep-deleted'));
15
+ section('No longer in the kit, kept because you changed them:', paths(actions, 'orphan'));
16
+ if (actions.some((a) => ['customized', 'conflict', 'keep-deleted'].includes(a.op))) {
17
+ console.log('\nTo take the kit version of a file instead: levi update --force [path...]');
18
+ }
19
+ }
20
+
21
+ module.exports = { printReport };
@@ -0,0 +1,23 @@
1
+ const { PREFIX, joinSections } = require('./agents');
2
+
3
+ // A usecase can be the skill a team role uses for one kind of task (`skill-for` in its SKILL.md).
4
+ // The team agent gets a section that points to the skill's guide, so that it follows the guide
5
+ // whichever usecase calls it, not only when its own usecase runs.
6
+ function withRoleSkills(agent, usecases, skillDir) {
7
+ const role = agent.name.slice(PREFIX.length);
8
+ const mine = usecases.filter((u) => u.skill && u.skill.roles.includes(role));
9
+ if (!mine.length) return agent;
10
+ const rows = mine.map((u) => `| When ${u.skill.when} | \`${skillDir}/${PREFIX}${u.id}/${u.skill.guide}\` |`);
11
+ const section = [
12
+ '## Your skills',
13
+ '',
14
+ 'These levi skills are yours. When a task you are given is one of the kinds below, read the guide before you start and follow it, whichever workflow called you and even when the prompt does not mention it. Paths in a guide are relative to its skill folder. The prompt still decides what to work on, which sources to use and where to write; where it says something the guide also covers, the prompt wins.',
15
+ '',
16
+ '| Task | Guide |',
17
+ '|---|---|',
18
+ ...rows,
19
+ ].join('\n');
20
+ return { ...agent, body: joinSections(agent.ownBody, section, agent.appendix) };
21
+ }
22
+
23
+ module.exports = { withRoleSkills };
@@ -0,0 +1,38 @@
1
+ const { skillName } = require('./usecases');
2
+
3
+ // Builds the SKILL.md of the `levi` entry point for one skill directory. Usecase skills
4
+ // are manual-only, so the router cannot call them through the tool's skill mechanism; it
5
+ // reads their SKILL.md by path instead.
6
+ function renderRouter(skillDir, usecases, team) {
7
+ const teamNames = team.map((a) => `\`${a.name}\``).join(', ');
8
+ const catalog = usecases
9
+ .map((u) => `- **${u.id}**: ${u.description}\n File: \`${skillDir}/${skillName(u.id)}/SKILL.md\``)
10
+ .join('\n');
11
+ return `---
12
+ name: levi
13
+ description: ${JSON.stringify('Entry point of the levi kit. Run only when the user explicitly invokes it with a request; picks the matching levi usecase and runs it.')}
14
+ argument-hint: "<request>"
15
+ disable-model-invocation: true
16
+ ---
17
+
18
+ # levi
19
+
20
+ The request is whatever the user typed after invoking \`levi\`. It may be written in any language; answer in the language the user used.
21
+
22
+ ## Usecases
23
+
24
+ ${catalog}
25
+
26
+ ## Steps
27
+
28
+ 1. If the request is empty, list the usecases above with one line each and ask what the user wants. Stop.
29
+ 2. Pick the usecase whose description best matches the request.
30
+ - No usecase fits: say so, list the available usecases, and stop. Do not improvise a substitute.
31
+ - One or more fit: run the best match. When several fit about equally, take the one whose description names the request's main goal most specifically. Do not ask the user to choose.
32
+ - Say which one you chose in one line, and when another was a close match, name it and add that \`/levi-<usecase>\` runs it directly.
33
+ 3. Read that usecase's file and follow it, treating the request as its input. Resolve relative paths in that file from its own directory. Do not call it through a skill tool: usecases are manual-only.
34
+ 4. Use the usecase's subagents (\`${skillName('<usecase>')}-<role>\`)${teamNames ? ` and the levi team agents (${teamNames})` : ''} only as that usecase instructs.
35
+ `;
36
+ }
37
+
38
+ module.exports = { renderRouter };
@@ -0,0 +1,110 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+ const { loadKit } = require('./usecases');
5
+ const { build } = require('./desired-state');
6
+
7
+ // Git may rewrite line endings (core.autocrlf), which must not count as a user edit, so text
8
+ // is hashed with CRLF folded to LF. Binary files (any NUL byte) are hashed as they are.
9
+ function sha(buf) {
10
+ const text = buf.includes(0) ? buf : Buffer.from(buf.toString('latin1').replace(/\r\n/g, '\n'), 'latin1');
11
+ return crypto.createHash('sha256').update(text).digest('hex');
12
+ }
13
+
14
+ // Path -> hash recorded at install time (null when the config predates hashing).
15
+ function trackedFiles(config) {
16
+ const map = new Map();
17
+ const add = (entry) => Object.entries((entry && entry.files) || {}).forEach(([p, h]) => map.set(p, h));
18
+ Object.values(config.usecases || {}).forEach(add);
19
+ add(config.router);
20
+ add(config.team);
21
+ return map;
22
+ }
23
+
24
+ function readHash(abs) {
25
+ return fs.existsSync(abs) && fs.statSync(abs).isFile() ? sha(fs.readFileSync(abs)) : null;
26
+ }
27
+
28
+ // Decides what to do with one file levi wants to have. The recorded hash tells whether the
29
+ // user changed it since levi wrote it; a changed file is never overwritten without force.
30
+ function planWanted(p, wanted, recorded, diskHash, forced) {
31
+ const newHash = sha(wanted.content);
32
+ const base = { path: p, group: wanted.group, newHash, recorded };
33
+ if (diskHash === null) {
34
+ return recorded !== undefined && !forced ? { ...base, op: 'keep-deleted' } : { ...base, op: 'add' };
35
+ }
36
+ if (diskHash === newHash) return { ...base, op: 'same' };
37
+ if (recorded === undefined) return { ...base, op: forced ? 'update' : 'conflict' };
38
+ if (recorded !== null && diskHash === recorded) return { ...base, op: 'update' };
39
+ if (forced) return { ...base, op: 'update' };
40
+ return { ...base, op: 'customized' };
41
+ }
42
+
43
+ function plan(projectDir, desired, tracked, force) {
44
+ const forced = (p) => force === true || (force instanceof Set && force.has(p));
45
+ const actions = [];
46
+ for (const [p, wanted] of desired.files) {
47
+ const recorded = tracked.has(p) ? tracked.get(p) : undefined;
48
+ actions.push({ ...planWanted(p, wanted, recorded, readHash(path.join(projectDir, p)), forced(p)), content: wanted.content });
49
+ }
50
+ for (const [p, recorded] of tracked) {
51
+ if (desired.files.has(p)) continue;
52
+ const diskHash = readHash(path.join(projectDir, p));
53
+ if (diskHash === null) actions.push({ path: p, op: 'drop' });
54
+ else if (recorded !== null && diskHash === recorded) actions.push({ path: p, op: 'remove' });
55
+ else actions.push({ path: p, op: 'orphan' });
56
+ }
57
+ return actions;
58
+ }
59
+
60
+ // Removes now-empty folders below the tool folders (.claude/skills/..., not .claude/skills).
61
+ function pruneEmptyDirs(projectDir, rel) {
62
+ let dir = path.posix.dirname(rel);
63
+ while (dir.split('/').length >= 3) {
64
+ const abs = path.join(projectDir, dir);
65
+ if (!fs.existsSync(abs) || fs.readdirSync(abs).length) return;
66
+ fs.rmdirSync(abs);
67
+ dir = path.posix.dirname(dir);
68
+ }
69
+ }
70
+
71
+ function writeFile(projectDir, rel, content) {
72
+ const abs = path.join(projectDir, rel);
73
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
74
+ fs.writeFileSync(abs, content);
75
+ }
76
+
77
+ function apply(projectDir, actions) {
78
+ for (const a of actions) {
79
+ if (a.op === 'add' || a.op === 'update') writeFile(projectDir, a.path, a.content);
80
+ else if (a.op === 'remove') {
81
+ fs.rmSync(path.join(projectDir, a.path), { force: true });
82
+ pruneEmptyDirs(projectDir, a.path);
83
+ }
84
+ }
85
+ }
86
+
87
+ // What .levi.json should remember: the hash of each file as levi last wrote it. A file
88
+ // the user changed keeps its old hash so it stays flagged; a path levi never owned is not tracked.
89
+ function recordFiles(actions, ids) {
90
+ const config = { usecases: {}, router: { files: {} }, team: { files: {} } };
91
+ for (const id of ids) config.usecases[id] = { files: {} };
92
+ for (const a of actions) {
93
+ if (!a.group || a.op === 'conflict') continue;
94
+ const hash = ['add', 'update', 'same'].includes(a.op) ? a.newHash : a.recorded;
95
+ const target = a.group.startsWith('usecase:') ? config.usecases[a.group.slice(8)] : config[a.group];
96
+ target.files[a.path] = hash;
97
+ }
98
+ return config;
99
+ }
100
+
101
+ // Brings the project in line with the kit for `ids` and `tools`, touching only files the user
102
+ // has not changed. `previous` is the stored config. With dryRun nothing is written.
103
+ function sync(projectDir, ids, tools, previous, { force = false, dryRun = false } = {}) {
104
+ const desired = build(loadKit(), ids, tools);
105
+ const actions = plan(projectDir, desired, trackedFiles(previous), force);
106
+ if (!dryRun) apply(projectDir, actions);
107
+ return { actions, missing: desired.missing, ...recordFiles(actions, desired.ids) };
108
+ }
109
+
110
+ module.exports = { sync };
@@ -0,0 +1,98 @@
1
+ const TOOLS = ['claude', 'codex', 'copilot'];
2
+
3
+ // `invoke` is the character that starts an explicit skill call in each tool.
4
+ const TOOL_INFO = {
5
+ claude: { label: 'Claude Code', invoke: '/' },
6
+ codex: { label: 'Codex', invoke: '$' },
7
+ copilot: { label: 'Copilot', invoke: '/' },
8
+ };
9
+
10
+ // Claude Code reads only .claude/skills; Codex reads .agents/skills; Copilot reads both
11
+ // of those, so it only needs its own copy when Claude is not selected.
12
+ function skillDirs(tools) {
13
+ const dirs = new Set();
14
+ if (tools.includes('claude')) dirs.add('.claude/skills');
15
+ if (tools.includes('codex')) dirs.add('.agents/skills');
16
+ if (tools.includes('copilot') && !tools.includes('claude')) dirs.add('.agents/skills');
17
+ return [...dirs];
18
+ }
19
+
20
+ // The skill folder an agent of `tool` reads: Copilot uses .claude/skills when Claude is installed.
21
+ function skillDirFor(tool, tools) {
22
+ return tool === 'claude' || (tool === 'copilot' && tools.includes('claude')) ? '.claude/skills' : '.agents/skills';
23
+ }
24
+
25
+ // Codex ignores SKILL.md frontmatter flags and reads its invocation policy from this file.
26
+ const CODEX_SKILL_DIR = '.agents/skills';
27
+ const CODEX_POLICY = 'policy:\n allow_implicit_invocation: false\n';
28
+
29
+ // Subagents are picked from their description, so scope them to levi to keep the agent
30
+ // from reaching for them on requests that did not go through levi.
31
+ function agentDescription(agent) {
32
+ const by = agent.owner ? `the ${agent.owner} workflow` : 'a levi workflow';
33
+ const text = /[.!?]$/.test(agent.description) ? agent.description : `${agent.description}.`;
34
+ return `${text} Used only when ${by} delegates to it; never select it for other requests.`;
35
+ }
36
+
37
+ // Tool-neutral capabilities and model tiers (see agents.js), mapped per tool. Omitting `tools`
38
+ // keeps the tool's defaults, including MCP servers, which an explicit list would cut off.
39
+ const CLAUDE_TOOLS = { read: ['Read', 'Grep', 'Glob'], edit: ['Edit', 'Write'], execute: ['Bash'], web: ['WebFetch', 'WebSearch'] };
40
+ const COPILOT_TOOLS = { read: ['read', 'search'], edit: ['edit'], execute: ['execute'], web: ['web'] };
41
+ const CLAUDE_MODELS = { strong: 'opus', standard: 'sonnet', fast: 'haiku' };
42
+ const CODEX_EFFORT = { strong: 'high', standard: 'medium', fast: 'low' };
43
+
44
+ function mapTools(tools, table) {
45
+ return tools.flatMap((t) => table[t]);
46
+ }
47
+
48
+ function tomlString(text) {
49
+ return '"""\n' + text.replace(/\\/g, '\\\\').replace(/"""/g, '\\"""').trim() + '\n"""';
50
+ }
51
+
52
+ function renderMarkdown(agent, extra) {
53
+ return ['---', `name: ${agent.name}`, `description: ${JSON.stringify(agentDescription(agent))}`, ...extra, '---', '', agent.body.trim(), ''].join(
54
+ '\n'
55
+ );
56
+ }
57
+
58
+ function renderClaude(agent) {
59
+ const extra = [];
60
+ if (agent.tools) extra.push(`tools: ${mapTools(agent.tools, CLAUDE_TOOLS).join(', ')}`);
61
+ if (agent.model) extra.push(`model: ${CLAUDE_MODELS[agent.model]}`);
62
+ return renderMarkdown(agent, extra);
63
+ }
64
+
65
+ // Copilot model names change often, so agents keep the user's selected model.
66
+ function renderCopilot(agent) {
67
+ const extra = agent.tools ? [`tools: ${JSON.stringify(mapTools(agent.tools, COPILOT_TOOLS))}`] : [];
68
+ return renderMarkdown(agent, extra);
69
+ }
70
+
71
+ // Codex has no per-tool list: an agent that can neither edit nor execute runs read-only.
72
+ function renderToml(agent) {
73
+ const lines = [`name = ${JSON.stringify(agent.name)}`, `description = ${JSON.stringify(agentDescription(agent))}`];
74
+ if (agent.model) lines.push(`model_reasoning_effort = "${CODEX_EFFORT[agent.model]}"`);
75
+ if (agent.tools) {
76
+ const writes = agent.tools.includes('edit') || agent.tools.includes('execute');
77
+ lines.push(`sandbox_mode = "${writes ? 'workspace-write' : 'read-only'}"`);
78
+ }
79
+ lines.push(`developer_instructions = ${tomlString(agent.body)}`, '');
80
+ return lines.join('\n');
81
+ }
82
+
83
+ const AGENT_TARGETS = {
84
+ claude: { dir: '.claude/agents', ext: '.md', render: renderClaude },
85
+ codex: { dir: '.codex/agents', ext: '.toml', render: renderToml },
86
+ copilot: { dir: '.github/agents', ext: '.agent.md', render: renderCopilot },
87
+ };
88
+
89
+ function invocationHelp(tools) {
90
+ return tools
91
+ .map((tool) => {
92
+ const { label, invoke } = TOOL_INFO[tool];
93
+ return ` ${label.padEnd(11)} ${invoke}levi <request> ${invoke}levi-<usecase> <request>`;
94
+ })
95
+ .join('\n');
96
+ }
97
+
98
+ module.exports = { TOOLS, CODEX_SKILL_DIR, CODEX_POLICY, skillDirs, skillDirFor, AGENT_TARGETS, invocationHelp };
@@ -0,0 +1,109 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { parse } = require('./frontmatter');
4
+ const { PREFIX, readAgent, loadTeam } = require('./agents');
5
+
6
+ const ROUTER_NAME = 'levi';
7
+ const KIT_DIR = path.join(__dirname, '..', '..', 'usecases');
8
+
9
+ function skillName(id) {
10
+ return PREFIX + id;
11
+ }
12
+
13
+ function kitVersion() {
14
+ return require('../../package.json').version;
15
+ }
16
+
17
+ function loadAgents(id, dir) {
18
+ const agentsDir = path.join(dir, 'agents');
19
+ if (!fs.existsSync(agentsDir)) return [];
20
+ return fs
21
+ .readdirSync(agentsDir)
22
+ .filter((f) => f.endsWith('.md'))
23
+ .map((file) =>
24
+ readAgent(path.join(agentsDir, file), `usecases/${id}/agents/${file}`, `${skillName(id)}-${file.slice(0, -3)}`, skillName(id))
25
+ );
26
+ }
27
+
28
+ function parseList(value) {
29
+ return (value || '').split(',').map((s) => s.trim()).filter(Boolean);
30
+ }
31
+
32
+ // A usecase can be the skill of team roles for one kind of task: `skill-for` (the roles),
33
+ // `skill-when` (the task, completing "When ...") and `skill-guide` (the file the role follows).
34
+ function loadRoleSkill(id, dir, data) {
35
+ const roles = parseList(data['skill-for']);
36
+ if (!roles.length) return null;
37
+ const label = `usecases/${id}/SKILL.md`;
38
+ if (!data['skill-when']) throw new Error(`${label}: skill-for needs skill-when`);
39
+ if (!data['skill-guide']) throw new Error(`${label}: skill-for needs skill-guide`);
40
+ if (!fs.existsSync(path.join(dir, data['skill-guide']))) throw new Error(`${label}: skill-guide "${data['skill-guide']}" not found`);
41
+ return { roles, when: data['skill-when'], guide: data['skill-guide'] };
42
+ }
43
+
44
+ function load(id) {
45
+ const dir = path.join(KIT_DIR, id);
46
+ const skillFile = path.join(dir, 'SKILL.md');
47
+ if (!fs.existsSync(skillFile)) throw new Error(`usecases/${id}: missing SKILL.md`);
48
+ const { data } = parse(fs.readFileSync(skillFile, 'utf8'));
49
+ if (data.name !== skillName(id)) {
50
+ throw new Error(`usecases/${id}/SKILL.md: name must be "${skillName(id)}", got "${data.name}"`);
51
+ }
52
+ if (!data.description) throw new Error(`usecases/${id}/SKILL.md: missing description`);
53
+ const requires = parseList(data.requires);
54
+ return { id, dir, description: data.description, requires, skill: loadRoleSkill(id, dir, data), agents: loadAgents(id, dir) };
55
+ }
56
+
57
+ // A usecase may build on others (`requires:` in its SKILL.md); they must exist in the kit.
58
+ // Role skills must name roles the team has.
59
+ function checkSkillRoles(usecases, team) {
60
+ const roles = new Set(team.map((a) => a.name.slice(PREFIX.length)));
61
+ for (const u of usecases) {
62
+ for (const role of (u.skill && u.skill.roles) || []) {
63
+ if (!roles.has(role)) throw new Error(`usecases/${u.id}/SKILL.md: skill-for names unknown team role "${role}"`);
64
+ }
65
+ }
66
+ }
67
+
68
+ function checkRequires(usecases) {
69
+ const ids = new Set(usecases.map((u) => u.id));
70
+ for (const u of usecases) {
71
+ for (const r of u.requires) {
72
+ if (r === u.id || !ids.has(r)) throw new Error(`usecases/${u.id}/SKILL.md: requires unknown usecase "${r}"`);
73
+ }
74
+ }
75
+ }
76
+
77
+ // Every agent name must be unique across the team and all usecases, and a usecase id must not
78
+ // reuse a team role, or `levi-<id>` would name both a skill and an agent.
79
+ function checkNames(usecases, team) {
80
+ const seen = new Set();
81
+ for (const agent of [...team, ...usecases.flatMap((u) => u.agents)]) {
82
+ if (seen.has(agent.name)) throw new Error(`Agent name "${agent.name}" is defined twice in the kit`);
83
+ seen.add(agent.name);
84
+ }
85
+ for (const u of usecases) {
86
+ if (seen.has(skillName(u.id))) throw new Error(`usecases/${u.id}: id clashes with team agent "${skillName(u.id)}"`);
87
+ }
88
+ }
89
+
90
+ // Loads and validates the whole kit, so a broken file fails before anything is touched.
91
+ function loadKit() {
92
+ const usecases = fs.existsSync(KIT_DIR)
93
+ ? fs
94
+ .readdirSync(KIT_DIR, { withFileTypes: true })
95
+ .filter((e) => e.isDirectory())
96
+ .map((e) => load(e.name))
97
+ : [];
98
+ const team = loadTeam();
99
+ checkNames(usecases, team);
100
+ checkRequires(usecases);
101
+ checkSkillRoles(usecases, team);
102
+ return { usecases, team };
103
+ }
104
+
105
+ function listUsecases() {
106
+ return loadKit().usecases;
107
+ }
108
+
109
+ module.exports = { PREFIX, ROUTER_NAME, kitVersion, skillName, loadKit, listUsecases };
File without changes
@@ -0,0 +1,84 @@
1
+ ---
2
+ name: levi-brainstorming
3
+ description: Brainstorm any problem or idea with the PM and Teamlead and turn it into an execution plan - a list of small tasks, each with the team agent that owns it and an estimate in hours. Uses the project's spec in docs/specs/ as a basis when one exists; never creates or edits specs. Fits requests such as "brainstorm X", "how should we approach X", "break X into tasks and estimate it".
4
+ argument-hint: "<problem or idea to brainstorm>"
5
+ ---
6
+
7
+ # Brainstorming
8
+
9
+ Turn a problem into an execution plan. `levi-pm` frames the problem and owns the plan; `levi-teamlead` explores the approaches and breaks the work into tasks. You run them in turn, relay their questions to the user, and never do their part yourself. A plan with more than 10 tasks is a hard ticket: it gets a second, independent review before it is final.
10
+
11
+ The problem can be anything the team could work on: a feature, a refactor, a migration, a process change.
12
+
13
+ This usecase plans; it does not write specs. Never create or edit anything under `docs/specs/`. An existing spec is read-only input. If the user wants a spec written or changed, they will ask for it separately.
14
+
15
+ ## Files
16
+
17
+ | File | Owner | Purpose |
18
+ |---|---|---|
19
+ | `docs/brainstorming/<slug>.md` | PM | **The deliverable**: the plan |
20
+ | `docs/levi/<slug>/brief.md` | PM | Scratch: the problem framed in a few lines. Written only when there is no spec. Deleted at the end |
21
+ | `docs/levi/<slug>/architecture.md` | Teamlead | Scratch: approaches considered and the one chosen. Deleted at the end |
22
+ | `docs/levi/<slug>/tasks.md` | Teamlead | Scratch: task breakdown with suggested roles and estimates. Deleted at the end |
23
+ | `docs/levi/<slug>/status.md` | PM | Scratch: task assignments. Deleted at the end |
24
+
25
+ `<slug>` is a short kebab-case name for the problem, in English (for example `export-orders-csv`). Create folders as needed. Pass each agent the exact paths it should read and write. When the run finishes, only the plan is left behind (and the spec, untouched, if the project had one).
26
+
27
+ ## Steps
28
+
29
+ 1. **Intake.** The request is the problem. If it is empty, ask what to brainstorm and stop. Derive the slug and a plain-language problem name.
30
+ 2. **Find the spec.** List `docs/specs/` and match files against the problem by name and title.
31
+ - One clear match: use it as the basis. Say which in one line.
32
+ - Two or more equally plausible: ask the user which one (or "none"), then continue.
33
+ - None: there is no spec, and the PM frames the problem itself in step 3.
34
+ 3. **PM frames the problem.** Call `levi-pm` with the problem, the spec path if any, and the mode:
35
+ - *Spec exists:* read it as the basis, without editing it. Return only the gaps and questions that matter for this problem.
36
+ - *No spec:* write `docs/levi/<slug>/brief.md`: goal, users, scope, out of scope, what done looks like as checkable points, and open questions. Mark every assumption as an assumption. Do not write a spec.
37
+
38
+ From here on, "the basis" means the spec when there is one, otherwise `brief.md`.
39
+ 4. **Teamlead explores.** Call `levi-teamlead` with the problem and the basis path. It reads the basis and the project, then writes `architecture.md`: two or three genuinely different approaches with their trade-offs, a recommendation, and the forks only the user can decide. It does not break the work down yet.
40
+ 5. **Ask the user once.** Merge the questions from steps 3 and 4, drop duplicates, and ask them all in a single round (use the tool's structured question feature if it has one). Give each question two to four options with the recommended one first. Add one more question if `docs/brainstorming/<slug>.md` already exists: replace it, or write the new plan under another name. Skip this step when there are no questions. An unanswered question takes its recommended option, recorded as an assumption. After this step the user's part is done; do not ask again unless an agent is BLOCKED.
41
+ 6. **Finalize the inputs.** Run these in parallel when the tool allows, with the user's answers as input:
42
+ - `levi-pm`, only when it wrote `brief.md`: fold the answers into it and clear the open questions that were answered.
43
+ - `levi-teamlead`: update `architecture.md` with the chosen approach, then write `tasks.md`. Every task is small (split anything over about 8 hours) and has: ID, goal, files or areas touched, done criteria, dependencies, the suggested role (`levi-pm`, `levi-teamlead`, `levi-developer`, `levi-designer` or `levi-qa`) and an estimate in hours. Include design, review, QA and acceptance tasks, not only implementation. Name the riskiest task.
44
+ - **Keep tasks independent.** The breakdown exists so that many agents can work at the same time, so cut the work along seams that leave as few dependencies as possible. Each task should be doable and checkable on its own, with its own inputs and done criteria, without waiting for or touching the output of another task. Prefer vertical slices over layers, and tasks that own separate files or areas.
45
+ - **Pull shared work out first.** When several tasks truly need the same thing (a data model, an interface or contract, a shared component, a config), do not let them depend on one another. Make one foundation task that delivers only that shared part, as small as it can be, and let the other tasks depend on it alone. After the foundation task, the remaining tasks must be able to run in parallel.
46
+ - **Dependencies are the exception.** Keep a dependency only when it cannot be removed, such as a task that needs a decision, an interface, or a result that does not exist yet. Prefer a dependency on a foundation task over a chain of tasks. Avoid long chains; a task that waits on a task that waits on another is a sign the cut is wrong.
47
+ 7. **PM writes the plan.** Call `levi-pm` with the basis, `architecture.md` and `tasks.md`. It checks that every goal and done-criterion in the basis is covered by a task, decides the owner of each task (the Teamlead's suggestion unless it has a reason to change it), records the assignments in `status.md`, and writes `docs/brainstorming/<slug>.md` in the format below. The scratch files are deleted later, so the plan's Notes must carry the chosen approach, what was rejected and why, and the riskiest task.
48
+ - If the PM reports uncovered criteria, send them to `levi-teamlead` to add tasks, then call the PM once more. The PM must settle any criterion that is still uncovered by itself: add the missing task and assign it, or rule the criterion out of scope with a one-line note in the plan's Notes. It never edits the spec, and it does not leave a gap open.
49
+ 8. **Review a hard plan.** Count the rows of the task table. With 10 tasks or fewer, skip to step 9. With more than 10, run an independent review, once:
50
+ - Use fresh agent calls that get only the paths of the basis and the plan (plus `review.md` for the PM's call), never the conversation, the other scratch files or your own opinion of the plan. A new call starts with no memory of the earlier steps, which is what makes the review independent.
51
+ - First call `levi-teamlead` to review the plan: task size, independence (remove dependencies that are not needed, move work shared by several tasks into one foundation task), dependencies and order, estimates, missing or redundant tasks, technical risk. The plan belongs to the PM, so the teamlead does not edit it: it writes its decisions to `docs/levi/<slug>/review.md` as a list of concrete changes (task, what changes, why). It decides: it may change tasks, estimates and even the chosen approach, and its calls override the first round.
52
+ - Then call `levi-pm` as a second fresh call, with the basis, the plan and `review.md`. The PM applies the teamlead's changes to `docs/brainstorming/<slug>.md`, then reviews the result against the basis: coverage of every goal and done-criterion, owner of each task, the total and the agent list. It decides on scope, coverage and ownership, and writes the final version over the old one. The teamlead's calls bind on technical matters (task size, estimates, approach, dependencies); the PM's calls override on scope, coverage and ownership. Its reply lists what changed in the review.
53
+ - The reviewers settle every point themselves, with their best judgment; they do not defer a point, hand it back as a question, or park it in Notes. Notes only add information to a decision already made, such as a changed approach and why, or an assumption behind it. Update the Notes to match the final plan. Do not start a second round.
54
+ 9. **Clean up.** Delete `architecture.md`, `tasks.md`, `status.md`, `brief.md` and `review.md` (the last two if they exist) from `docs/levi/<slug>/`, then remove the folder if it is now empty. Remove `docs/levi` too if that is empty. Delete only those files, and only after the plan is final. Keep the plan, and never touch the spec.
55
+ 10. **Check and report.** Open the plan and confirm that the total equals the sum of the task estimates and that the agent list equals the agents in the task table; fix it if not. Tell the user the plan path, the spec used (if any), the total hours, the agents involved, whether the plan was reviewed (and what the review changed), and any assumption taken in place of an unanswered question.
56
+
57
+ ## Plan format
58
+
59
+ `docs/brainstorming/<slug>.md`, written in the language of the request:
60
+
61
+ ```markdown
62
+ # <Problem name>
63
+
64
+ - **Total estimate:** <N> hours
65
+ - **Agents:** levi-pm, levi-teamlead, levi-developer
66
+
67
+ ## Tasks
68
+
69
+ | # | Task | Agent | Estimate (h) | Depends on |
70
+ |---|---|---|---|---|
71
+ | 1 | <small, concrete task> | levi-teamlead | 2 | - |
72
+ | 2 | <small, concrete task> | levi-developer | 4 | 1 |
73
+
74
+ ## Notes
75
+
76
+ <Only when there is something to add: the chosen approach and what was rejected, assumptions,
77
+ risks (the riskiest task), work that needs a human. Notes supplement the plan and never hold an
78
+ undecided point. Omit this whole section otherwise.>
79
+ ```
80
+
81
+ - The total is the sum of the task estimates. It is agent working time, not the calendar duration, so tasks that can run in parallel are still added up.
82
+ - An estimate is the hours the assigned agent needs for that task, including checking its own work, in steps of 0.5 hours. It does not include waiting for the user.
83
+ - The agent list contains each agent that owns at least one task, once.
84
+ - `Depends on` lists only dependencies that cannot be removed. Most tasks should have `-` or point at a foundation task, so that as many tasks as possible can run in parallel.