levi-gear 0.1.0 → 0.3.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 (47) hide show
  1. package/README.md +13 -8
  2. package/agents/_team-protocol.md +15 -6
  3. package/agents/designer.md +2 -2
  4. package/agents/developer.md +1 -1
  5. package/agents/pm.md +4 -1
  6. package/agents/qa.md +1 -1
  7. package/agents/teamlead.md +1 -1
  8. package/package.json +4 -1
  9. package/src/commands/list.js +2 -1
  10. package/src/lib/agents.js +9 -2
  11. package/src/lib/desired-state.js +38 -11
  12. package/src/lib/role-skills.js +23 -0
  13. package/src/lib/tools.js +6 -1
  14. package/src/lib/usecases.js +44 -2
  15. package/src/runtime/codex-run-state.mjs +156 -0
  16. package/src/runtime/quota-check.mjs +195 -0
  17. package/usecases/_run-rules.md +38 -0
  18. package/usecases/brainstorming/SKILL.md +60 -14
  19. package/usecases/brainstorming/references/codex-runner.md +28 -0
  20. package/usecases/code-review/SKILL.md +86 -0
  21. package/usecases/code-review/references/codex-runner.md +5 -0
  22. package/usecases/code-review/references/large-changes.md +37 -0
  23. package/usecases/code-review/references/performance-and-correctness.md +101 -0
  24. package/usecases/code-review/references/review-guide.md +72 -0
  25. package/usecases/code-review/references/security.md +119 -0
  26. package/usecases/create-feature/SKILL.md +97 -0
  27. package/usecases/create-feature/references/codex-runner.md +57 -0
  28. package/usecases/create-feature/scripts/lock-tests.mjs +66 -0
  29. package/usecases/create-feature/workflow.js +532 -0
  30. package/usecases/design/SKILL.md +66 -0
  31. package/usecases/design/references/codex-runner.md +27 -0
  32. package/usecases/design/references/svg-guide.md +14 -0
  33. package/usecases/design/scripts/check-svg.py +77 -0
  34. package/usecases/fix-bug/SKILL.md +97 -0
  35. package/usecases/fix-bug/references/codex-runner.md +32 -0
  36. package/usecases/fix-bug/workflow.js +392 -0
  37. package/usecases/generate-test-scenarios/SKILL.md +102 -0
  38. package/usecases/generate-test-scenarios/references/codex-runner.md +32 -0
  39. package/usecases/generate-test-scenarios/references/test-case-guide.md +171 -0
  40. package/usecases/generate-test-scenarios/scripts/render-test-cases-markdown.mjs +76 -0
  41. package/usecases/generate-test-scenarios/scripts/render-test-cases.mjs +68 -0
  42. package/usecases/generate-test-scenarios/scripts/test-case-fields.mjs +63 -0
  43. package/usecases/generate-test-scenarios/scripts/validate-test-cases.mjs +69 -0
  44. package/usecases/generate-test-scenarios/scripts/write-xlsx.mjs +157 -0
  45. package/usecases/spec-writing/SKILL.md +63 -0
  46. package/usecases/spec-writing/references/codex-runner.md +25 -0
  47. package/usecases/spec-writing/references/spec-guide.md +62 -0
@@ -0,0 +1,195 @@
1
+ #!/usr/bin/env node
2
+ // Quota guard helper installed with every levi skill. It reads how much of the 5-hour usage
3
+ // window is used, and (on Codex) arms a crontab job that resumes an interrupted run once the
4
+ // quota is back. It never runs a levi workflow itself.
5
+ //
6
+ // check --tool claude|codex [--threshold 95] print the 5-hour usage as JSON
7
+ // record [--passthrough] statusline hook: save Claude Code's usage (JSON on stdin)
8
+ // cron-arm --session <id> --project <dir> [--every 2] [--threshold 95] [-- <codex exec resume flags>]
9
+ // cron-disarm --session <id>
10
+ // cron-fire --session <id> --project <dir> [--threshold 95] [-- <flags>] called by the crontab line
11
+
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { spawnSync } from 'node:child_process';
16
+ import { fileURLToPath } from 'node:url';
17
+
18
+ const THRESHOLD = 95;
19
+ const EVERY_HOURS = 2;
20
+ const FIVE_HOURS = 300;
21
+ const STALE_MS = 30 * 60 * 1000;
22
+ const TAIL_BYTES = 512 * 1024;
23
+ const RESUME_PROMPT = 'I ran out of quota a moment ago and the run was interrupted. Please continue the process or workflow you were running.';
24
+
25
+ const claudeFile = () => path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'levi-quota.json');
26
+ const codexSessions = () => path.join(process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), 'sessions');
27
+
28
+ function result(tool, fields) {
29
+ const threshold = fields.threshold;
30
+ const used = fields.usedPercent;
31
+ const known = typeof used === 'number';
32
+ return { tool, status: known ? 'ok' : 'unknown', ...fields, atThreshold: known && used >= threshold };
33
+ }
34
+
35
+ // A window whose reset time has passed holds no usage any more.
36
+ function window(used, resetsAtSeconds, now = Date.now()) {
37
+ if (typeof used !== 'number') return {};
38
+ const passed = typeof resetsAtSeconds === 'number' && resetsAtSeconds * 1000 <= now;
39
+ return { usedPercent: passed ? 0 : used, resetsAt: resetsAtSeconds ? new Date(resetsAtSeconds * 1000).toISOString() : null };
40
+ }
41
+
42
+ function checkClaude(threshold) {
43
+ const file = claudeFile();
44
+ if (!fs.existsSync(file)) return result('claude', { threshold, source: file, reason: 'the statusline bridge is not set up (no usage file)' });
45
+ const saved = JSON.parse(fs.readFileSync(file, 'utf8'));
46
+ if (Date.now() - saved.recordedAt > STALE_MS) return result('claude', { threshold, source: file, reason: 'the usage file is stale' });
47
+ return result('claude', { threshold, source: file, ...window(saved.usedPercent, saved.resetsAt) });
48
+ }
49
+
50
+ function newestRollout(dir) {
51
+ if (!fs.existsSync(dir)) return null;
52
+ const files = fs.readdirSync(dir, { recursive: true }).filter((f) => /rollout-.*\.jsonl$/.test(f)).sort();
53
+ return files.length ? path.join(dir, files[files.length - 1]) : null;
54
+ }
55
+
56
+ function lastRateLimits(file) {
57
+ const size = fs.statSync(file).size;
58
+ const fd = fs.openSync(file, 'r');
59
+ const buffer = Buffer.alloc(Math.min(size, TAIL_BYTES));
60
+ fs.readSync(fd, buffer, 0, buffer.length, size - buffer.length);
61
+ fs.closeSync(fd);
62
+ const lines = buffer.toString('utf8').split('\n').reverse();
63
+ for (const line of lines) {
64
+ if (!line.includes('"rate_limits"')) continue;
65
+ try {
66
+ const event = JSON.parse(line);
67
+ const limits = (event.payload && event.payload.rate_limits) || event.rate_limits;
68
+ if (limits && typeof limits === 'object') return limits;
69
+ } catch {
70
+ // The first line of the tail may be cut in half; skip it.
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+
76
+ function checkCodex(threshold) {
77
+ const file = newestRollout(codexSessions());
78
+ if (!file) return result('codex', { threshold, source: codexSessions(), reason: 'no Codex session file found' });
79
+ const sessionId = process.env.CODEX_THREAD_ID || (file.match(/([0-9a-f-]{36})\.jsonl$/) || [])[1] || null;
80
+ const limits = lastRateLimits(file);
81
+ const fiveHour = limits && [limits.primary, limits.secondary].find((w) => w && w.window_minutes === FIVE_HOURS);
82
+ if (!fiveHour) return result('codex', { threshold, source: file, sessionId, reason: 'no 5-hour rate limit recorded yet' });
83
+ return result('codex', { threshold, source: file, sessionId, ...window(fiveHour.used_percent, fiveHour.resets_at) });
84
+ }
85
+
86
+ function check(tool, threshold) {
87
+ if (tool === 'claude') return checkClaude(threshold);
88
+ if (tool === 'codex') return checkCodex(threshold);
89
+ return result(tool, { threshold, reason: `no way to read the quota of "${tool}"` });
90
+ }
91
+
92
+ // Statusline hook for Claude Code: the only place it shows the usage is the JSON it pipes in.
93
+ function record(passthrough) {
94
+ const input = fs.readFileSync(0, 'utf8');
95
+ try {
96
+ const five = JSON.parse(input).rate_limits.five_hour;
97
+ fs.writeFileSync(claudeFile(), JSON.stringify({ recordedAt: Date.now(), usedPercent: five.used_percentage, resetsAt: five.resets_at }) + '\n');
98
+ if (!passthrough) process.stdout.write(`5h ${Math.round(five.used_percentage)}%`);
99
+ } catch {
100
+ if (!passthrough) process.stdout.write('5h ?');
101
+ }
102
+ if (passthrough) process.stdout.write(input);
103
+ }
104
+
105
+ // ---- crontab job (Codex) ----
106
+
107
+ const crontab = () => process.env.LEVI_CRONTAB || 'crontab';
108
+ const marker = (session) => `# levi-quota-resume ${session}`;
109
+ const quote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
110
+
111
+ function readCrontab() {
112
+ const out = spawnSync(crontab(), ['-l'], { encoding: 'utf8' });
113
+ return out.status === 0 ? out.stdout.split('\n').filter((l) => l.trim()) : [];
114
+ }
115
+
116
+ function writeCrontab(lines) {
117
+ const out = spawnSync(crontab(), ['-'], { input: lines.join('\n') + (lines.length ? '\n' : ''), encoding: 'utf8' });
118
+ if (out.status !== 0) throw new Error(`crontab failed: ${out.stderr || out.stdout}`);
119
+ }
120
+
121
+ const withoutJob = (lines, session) => lines.filter((l) => !l.endsWith(marker(session)));
122
+
123
+ function which(name) {
124
+ for (const dir of (process.env.PATH || '').split(path.delimiter)) {
125
+ const file = path.join(dir, name);
126
+ if (fs.existsSync(file)) return file;
127
+ }
128
+ return null;
129
+ }
130
+
131
+ function arm({ session, project, every, threshold, flags }) {
132
+ const codex = which('codex');
133
+ if (!codex) throw new Error('codex is not on PATH, so the resume job cannot call it');
134
+ const self = fileURLToPath(import.meta.url);
135
+ const log = path.join(os.tmpdir(), `levi-quota-resume-${session}.log`);
136
+ const command = [process.execPath, self, 'cron-fire', '--session', session, '--project', project, '--threshold', threshold, '--codex', codex, '--', ...flags]
137
+ .map(quote)
138
+ .join(' ');
139
+ // 7 minutes past, so that jobs do not all start on the hour. "%" is special inside a crontab line.
140
+ const line = `7 */${every} * * * ${command} >> ${quote(log)} 2>&1 ${marker(session)}`.replace(/%/g, '\\%');
141
+ writeCrontab([...withoutJob(readCrontab(), session), line]);
142
+ const daemon = spawnSync('pgrep', ['-x', 'cron']).status === 0 || spawnSync('pgrep', ['-x', 'crond']).status === 0;
143
+ return { armed: true, session, every, log, cronRunning: daemon, warning: daemon ? null : 'no cron daemon is running; start it (on WSL: enable systemd or run `sudo service cron start`) or the job will never fire' };
144
+ }
145
+
146
+ function disarm(session) {
147
+ writeCrontab(withoutJob(readCrontab(), session));
148
+ return { armed: false, session };
149
+ }
150
+
151
+ // Called by cron. While the quota is still used up it does nothing; otherwise it removes its
152
+ // own job first (the resumed run re-arms one if it runs low again), then resumes the session.
153
+ function fire({ session, project, threshold, flags, codex }) {
154
+ const state = check('codex', threshold);
155
+ if (state.atThreshold) return { fired: false, reason: 'quota still used up', state };
156
+ disarm(session);
157
+ const run = spawnSync(codex || 'codex', ['exec', 'resume', ...flags, session, RESUME_PROMPT], { cwd: project, stdio: 'inherit' });
158
+ if (run.status !== 0) arm({ session, project, every: EVERY_HOURS, threshold, flags });
159
+ return { fired: true, exitCode: run.status };
160
+ }
161
+
162
+ // ---- command line ----
163
+
164
+ function parseArgs(argv) {
165
+ const split = argv.indexOf('--');
166
+ const flags = split === -1 ? [] : argv.slice(split + 1);
167
+ const options = {};
168
+ const own = split === -1 ? argv : argv.slice(0, split);
169
+ for (let i = 0; i < own.length; i++) {
170
+ if (!own[i].startsWith('--')) continue;
171
+ const next = own[i + 1];
172
+ options[own[i].slice(2)] = next === undefined || next.startsWith('--') ? true : (i++, next);
173
+ }
174
+ return { options, flags };
175
+ }
176
+
177
+ function main() {
178
+ const [command, ...rest] = process.argv.slice(2);
179
+ const { options, flags } = parseArgs(rest);
180
+ const threshold = Number(options.threshold || THRESHOLD);
181
+ const job = { session: options.session, project: path.resolve(options.project || '.'), every: Number(options.every || EVERY_HOURS), threshold, flags, codex: options.codex };
182
+ if (command === 'record') return record(Boolean(options.passthrough));
183
+ if (command === 'check') return console.log(JSON.stringify(check(options.tool, threshold), null, 2));
184
+ if (!['cron-arm', 'cron-disarm', 'cron-fire'].includes(command)) throw new Error('usage: quota-check.mjs check|record|cron-arm|cron-disarm|cron-fire ...');
185
+ if (!job.session) throw new Error('--session is required');
186
+ const actions = { 'cron-arm': () => arm(job), 'cron-disarm': () => disarm(job.session), 'cron-fire': () => fire(job) };
187
+ console.log(JSON.stringify(actions[command](), null, 2));
188
+ }
189
+
190
+ try {
191
+ main();
192
+ } catch (error) {
193
+ console.error(error.message);
194
+ process.exitCode = 2;
195
+ }
@@ -0,0 +1,38 @@
1
+ ## Run rules
2
+
3
+ These rules apply to every levi usecase, in every tool. Where they disagree with a step above about asking the user, they win. The user is often away from the keyboard: a run that stops half-way to ask something stays stopped.
4
+
5
+ ### Ask first, then run alone
6
+
7
+ 1. Start with a cheap discovery pass: read the request, the matching specs, plans and designs and the project, and call the agents that only frame or analyze. Do no expensive work (writing, coding, drawing, testing) before it is done.
8
+ 2. From that pass, build the whole list of questions: what is missing, unclear or contradictory; every candidate to confirm (which spec, plan or design to reuse); every irreversible or externally visible step (deleting, publishing, pushing, deploying, spending money).
9
+ 3. Ask them all in one round (several question calls back to back when the tool limits how many fit in one). Each has two to four options, the recommended one first. Say in the same message that the run continues on its own after the answers.
10
+ 4. Then do not ask again. A question that comes up later is parked: carry on with everything that does not depend on it, and give all parked questions together at the end, with the assumption used meanwhile. Stop early only when nothing is left to do without the answer.
11
+
12
+ Ask only about a fact only the user knows (business rules, data, credentials), scope or acceptance criteria, an irreversible or externally visible action, or a pick where a wrong guess wastes a large part of the work. Anything else is a choice.
13
+
14
+ ### Choices are picked, not asked
15
+
16
+ When the work yields several acceptable options and picking one can be undone cheaply (four logo variants, a layout, a palette, a name, a wording, equal libraries), do not wait for the user. Take the recommended option, or the best by your own judgment, and keep going.
17
+
18
+ - Record each choice in its own small file `docs/levi/<slug>/choices/<who>-<topic>.md` (one file per choice, so agents working in parallel never write the same file): what was chosen between, the pick, why, the alternatives and how to switch. Without a work folder, keep the list in your notes. Every agent may write there; agents record their own choices, and the usecase records the choices it makes itself.
19
+ - Keep the rejected options reachable: files go in an `alternatives/` folder next to the deliverable; anything else is described in the entry.
20
+ - Before cleaning up the work folder, read `choices/`. Close the final report with the section "Choices I made for you": each choice, the pick, the alternatives, how to change it, and that the user can change any of them. Do this even when the run ends early (blocked, stalled, parked questions).
21
+
22
+ ### Quota guard
23
+
24
+ Applies to every run with more than one stage. You are on Claude Code, Codex or another tool; the steps differ only where marked. Script paths are relative to this skill's folder.
25
+
26
+ 1. At every stage boundary (after a stage, before dispatching the next agents, before each build round) run `node scripts/quota-check.mjs check --tool <claude|codex>` from this skill's folder and read its JSON. `atThreshold` means 95% or more of the 5-hour window is used.
27
+ 2. **Usage unknown** (`status: unknown`: Claude Code without the statusline bridge, API-key billing, Copilot): arm the resume job once, right after the opening questions are answered, and keep it until the run ends.
28
+ 3. **At the threshold:** finish the step in progress, make sure the checkpoint is written (Codex: `run.json`; the work folder holds the rest), and arm the resume job if it is not armed. Then keep working; the job matters only if the limit really interrupts the run.
29
+ 4. **Arming** the job, with this exact prompt: `I ran out of quota a moment ago and the run was interrupted. Please continue the process or workflow you were running.`
30
+ - *Claude Code:* `CronList` first, to avoid a duplicate; then `CronCreate` (load it with `ToolSearch` if it is deferred), recurring, cron `7 */2 * * *`, with that prompt.
31
+ - *Codex, when this session has a scheduled-task tool* (the Codex app lists such tasks under "Scheduled"): list the existing scheduled tasks first, to avoid a duplicate, then create one that repeats every 2 hours with that prompt, attached to this thread.
32
+ - *Codex, without such a tool:* `node scripts/quota-check.mjs cron-arm --session <sessionId from check> --project <project root> -- <the approval and sandbox flags of this session, for example --full-auto>`. It writes a crontab line every 2 hours; the line does nothing while the quota is used up, removes itself before it resumes the session, and puts itself back if the resume fails. Pass on its `warning` to the user.
33
+ - *No way to arm* (no scheduler tool, Copilot): tell the user in your next message that the run will not resume on its own, and go on.
34
+ 5. **When that prompt arrives, the job has fired and you are the resumed run.** Find what was interrupted (Codex: a `docs/levi/*/run.json` that is not complete; Claude Code: your own context and the work folder; for a Workflow run, stop the old run and continue it with `resumeFromRunId`) and continue from the recorded stage without repeating finished stages. If nothing was interrupted, delete the job and say there is nothing to resume.
35
+ - *Claude Code:* run `check`. When usage is known and below the threshold, delete the job (`CronList`, then `CronDelete` the one with this prompt); when it is at the threshold or unknown, keep it.
36
+ - *Codex with a scheduled-task tool:* the same as Claude Code: delete the task when usage is known and below the threshold.
37
+ - *Codex with the crontab job:* nothing to delete; the crontab line already removed itself.
38
+ 6. **When the run ends** (done, blocked or stalled), remove the job: Claude Code `CronDelete`; Codex delete the scheduled task (when the tool cannot delete, name the task in the final report so the user removes it from the Scheduled list; a firing that finds nothing interrupted only says so), or for the crontab job run `node scripts/quota-check.mjs cron-disarm --session <sessionId>`.
@@ -1,6 +1,6 @@
1
1
  ---
2
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".
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. A problem with several features is planned in phases: an MVP first, then one feature completed per phase, each phase a release that runs on its own. 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
4
  argument-hint: "<problem or idea to brainstorm>"
5
5
  ---
6
6
 
@@ -10,6 +10,8 @@ Turn a problem into an execution plan. `levi-pm` frames the problem and owns the
10
10
 
11
11
  The problem can be anything the team could work on: a feature, a refactor, a migration, a process change.
12
12
 
13
+ **A problem with several features is planned in phases.** Phase 1 is the MVP: the basic version of what the product needs to work end to end. Every later phase completes one feature. The plan is cut so that each phase is a release that runs on its own and never needs a later phase, which also keeps each stretch of development small. A problem with one feature, or with no sensible cut, gets a flat plan.
14
+
13
15
  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
16
 
15
17
  ## Files
@@ -18,12 +20,17 @@ This usecase plans; it does not write specs. Never create or edit anything under
18
20
  |---|---|---|
19
21
  | `docs/brainstorming/<slug>.md` | PM | **The deliverable**: the plan |
20
22
  | `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 |
23
+ | `docs/levi/<slug>/phases.md` | PM | Scratch: the features, the MVP cut and the order of the later phases. Written only when the problem holds several features. Deleted at the end |
21
24
  | `docs/levi/<slug>/architecture.md` | Teamlead | Scratch: approaches considered and the one chosen. Deleted at the end |
22
25
  | `docs/levi/<slug>/tasks.md` | Teamlead | Scratch: task breakdown with suggested roles and estimates. Deleted at the end |
23
26
  | `docs/levi/<slug>/status.md` | PM | Scratch: task assignments. Deleted at the end |
24
27
 
25
28
  `<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
29
 
30
+ ## Codex runner
31
+
32
+ On Codex, use [`references/codex-runner.md`](references/codex-runner.md). It records the planning stage in `docs/levi/<slug>/run.json`, so a stopped run resumes from its artifact checkpoint rather than from conversation memory.
33
+
27
34
  ## Steps
28
35
 
29
36
  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.
@@ -37,23 +44,26 @@ This usecase plans; it does not write specs. Never create or edit anything under
37
44
 
38
45
  From here on, "the basis" means the spec when there is one, otherwise `brief.md`.
39
46
  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
- 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.
47
+ 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. Ask what only the user can settle (facts, scope, priorities, a fork that decides the approach); a choice that is cheap to change, such as a name or the order of two equal tasks, is picked and recorded as the run rules say. 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.
48
+ 6. **Finalize the inputs.** Run these with the user's answers as input. When the problem holds several features, run the PM first (it writes `phases.md`) and then the teamlead; otherwise run them in parallel when the tool allows.
49
+ - `levi-pm`: when it wrote `brief.md`, fold the answers into it and clear the open questions that were answered. When the problem holds more than one feature, also write `phases.md`: the list of features; **Phase 1, the MVP**, the smallest set that works end to end for the core purpose, holding the basic version of every feature the core flow needs and nothing optional, with what a user can do with that release; then **one later phase per feature**, each completing that feature (bringing it from the MVP's basic version to complete, or adding it whole when the MVP has none of it), ordered by value and then risk, with the reason for the order; and for each phase a release check, a way to tell that the release works on its own. No phase may need anything from a later phase, and a later phase extends the earlier ones instead of reworking them. Say so and write no phases when there is one feature or no sensible cut.
50
+ - `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. With `phases.md`, each task also has its phase; the shared foundation goes in Phase 1; every phase has its own QA and release-check tasks, so its release is really verified; a task depends only on tasks of its own or an earlier phase; and nothing for a later phase is built early.
51
+ - **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.
52
+ - **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.
53
+ - **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.
54
+ 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 (in some phase, when there are phases), 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 phased format when `phases.md` exists). 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.
45
55
  - 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.
46
- 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:
47
- - Use fresh agent calls that get only the paths of the basis and the plan, never the conversation, the 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.
48
- - First call `levi-teamlead` to review the plan: task size, dependencies and order, estimates, missing or redundant tasks, technical risk. It edits `docs/brainstorming/<slug>.md` in place and decides: it may change tasks, estimates and even the chosen approach, and its calls override the first round.
49
- - Then call `levi-pm` as a second fresh call to review the result against the basis: coverage of every goal and done-criterion, owner of each task, the total and the agent list. The PM edits the same file, decides on scope, coverage and ownership, and writes the final version over the old one. Its calls override the first round and the Teamlead's review where they conflict. Each reply lists what changed in the review.
56
+ 8. **Review a hard plan.** Count the rows of the task tables (all phases together). With 10 tasks or fewer, skip to step 9. With more than 10, run an independent review, once:
57
+ - 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.
58
+ - 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, and for a phased plan that no task depends on a later phase and that each phase's release works on its own. 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.
59
+ - 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, and for a phased plan that the MVP is the smallest working release and that each later phase completes one feature. 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.
50
60
  - 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.
51
- 9. **Clean up.** Delete `architecture.md`, `tasks.md`, `status.md` and `brief.md` (if it exists) 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.
52
- 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.
61
+ 9. **Clean up.** Delete `architecture.md`, `tasks.md`, `status.md`, `brief.md`, `phases.md` and `review.md` (the last three if they exist) and `choices/` (read it first for the report) 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.
62
+ 10. **Check and report.** Open the plan and confirm that the total equals the sum of the task estimates (the phase estimates too, for a phased plan) and that the agent list equals the agents in the task tables; 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.
53
63
 
54
64
  ## Plan format
55
65
 
56
- `docs/brainstorming/<slug>.md`, written in the language of the request:
66
+ `docs/brainstorming/<slug>.md`, written in the language of the request. A problem with one feature, or with no sensible cut, gets the flat plan:
57
67
 
58
68
  ```markdown
59
69
  # <Problem name>
@@ -75,6 +85,42 @@ risks (the riskiest task), work that needs a human. Notes supplement the plan an
75
85
  undecided point. Omit this whole section otherwise.>
76
86
  ```
77
87
 
78
- - 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.
88
+ A problem with several features gets the phased plan. The tasks sit in one table per phase:
89
+
90
+ ```markdown
91
+ # <Problem name>
92
+
93
+ - **Total estimate:** <N> hours
94
+ - **Agents:** levi-pm, levi-teamlead, levi-developer
95
+
96
+ ## Phases
97
+
98
+ | Phase | Release | Estimate (h) |
99
+ |---|---|---|
100
+ | 1. MVP | <what a user can do with this release> | 20 |
101
+ | 2. <Feature> | <what this release adds> | 8 |
102
+
103
+ ## Phase 1: MVP
104
+
105
+ **Release check:** <how to tell that this release works on its own>
106
+
107
+ | # | Task | Agent | Estimate (h) | Depends on |
108
+ |---|---|---|---|---|
109
+ | 1 | <small, concrete task> | levi-teamlead | 2 | - |
110
+
111
+ ## Phase 2: <Feature>
112
+
113
+ **Release check:** <how to tell that this release works on its own>
114
+
115
+ | # | Task | Agent | Estimate (h) | Depends on |
116
+ |---|---|---|---|---|
117
+ | 2 | <small, concrete task> | levi-developer | 4 | 1 |
118
+
119
+ ## Notes
120
+ ```
121
+
122
+ - 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. In a phased plan each phase's estimate is the sum of its tasks.
79
123
  - 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.
80
124
  - The agent list contains each agent that owns at least one task, once.
125
+ - `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.
126
+ - Task numbers run across the phases. In a phased plan a task depends only on tasks of its own phase or an earlier one, never a later one. Phase 1 is the MVP and holds the foundation; each later phase completes one feature; every phase ends with its own QA and release-check tasks, so each release can ship and run on its own.
@@ -0,0 +1,28 @@
1
+ # Codex runner
2
+
3
+ Run this workflow from the project root with a durable checkpoint. Do not reconstruct a stopped planning run from chat history.
4
+
5
+ ```bash
6
+ node <this skill folder>/scripts/codex-run-state.mjs status docs/levi/<slug>
7
+ node <this skill folder>/scripts/codex-run-state.mjs init docs/levi/<slug> brainstorming <slug> frame explore decide finalize plan review verify
8
+ ```
9
+
10
+ ```bash
11
+ node <this skill folder>/scripts/codex-run-state.mjs begin docs/levi/<slug> <stage>
12
+ node <this skill folder>/scripts/codex-run-state.mjs complete docs/levi/<slug> <stage> <artifact>...
13
+ node <this skill folder>/scripts/codex-run-state.mjs wait docs/levi/<slug> <stage> "<questions>"
14
+ node <this skill folder>/scripts/codex-run-state.mjs block docs/levi/<slug> <stage> "<blocker>"
15
+ node <this skill folder>/scripts/codex-run-state.mjs resume docs/levi/<slug>
16
+ ```
17
+
18
+ Create the state after intake has derived the slug. On every new or resumed turn, read `status` first. Call `begin` for the current stage and `complete` only when its required artifact exists. Use `wait` for the single consolidated user-question round, `block` for a dependency outside the project, and `resume` once resolved. Completed stages are never repeated.
19
+
20
+ - `frame`: find the optional read-only spec and have `levi-pm` write `brief.md` when no spec exists.
21
+ - `explore`: `levi-teamlead` writes `architecture.md` from the basis.
22
+ - `decide`: collect the PM/teamlead questions and the overwrite choice. Mark this stage `wait` before asking the user; after the answer, `resume` and complete it. Do not ask later unless blocked.
23
+ - `finalize`: dispatch the PM and teamlead with the confirmed choices; when the problem holds several features, the PM writes `phases.md` first and the teamlead plans from it. Complete only when `tasks.md` exists (and `phases.md`, for several features) and, when no spec was available, `brief.md` has been updated.
24
+ - `plan`: `levi-pm` writes `docs/brainstorming/<slug>.md`; if it finds a coverage gap, return only the missing tasks to the teamlead and keep this stage active.
25
+ - `review`: when the plan has more than ten tasks, run the independent teamlead then PM review exactly once. Complete with the final plan; otherwise complete the skipped stage without an artifact.
26
+ - `verify`: check totals and agents in the final plan, then complete with that plan. Only after this stage is complete may cleanup remove the checkpoint and scratch files.
27
+
28
+ Use the named Levi role agents; the coordinator alone changes `run.json`. The final plan is the only deliverable after cleanup.
@@ -0,0 +1,86 @@
1
+ ---
2
+ name: levi-code-review
3
+ description: Have the teamlead review code and suggest a fix for every problem it finds, without changing anything. It checks security against the OWASP Top 10 (injection, broken authentication, sensitive data exposure, XXE, broken access control, security misconfiguration, XSS, insecure deserialization, SSRF and more) and performance and correctness (N+1 queries, race conditions, memory leaks, inefficient algorithms, missing indexes, wrong error handling, breaking API changes). The target is a pull request link, a branch, a commit range, files or folders, or the uncommitted changes. The findings are given in the conversation, graded critical / warning / suggestion. A change of more than 100 files is split into slices that several teamlead reviewers read at the same time, and one lead teamlead merges their findings into a single review, so the author gets everything in one round. Other usecases (create-feature, fix-bug) use the same review criteria for their teamlead review. Fits requests such as "review this PR", "review my changes", "check this code for security issues", "review PR này", "review code giúp tôi", "kiểm tra bảo mật đoạn code này".
4
+ argument-hint: "<pull request link, branch, commit range or path; empty for the uncommitted changes>"
5
+ skill-for: teamlead
6
+ skill-when: you review code
7
+ skill-guide: references/review-guide.md
8
+ ---
9
+
10
+ # Code review
11
+
12
+ `levi-teamlead` reviews the code; reviewing code is its job, and no other team member does it. You work out what to review, call the teamlead (or, for a large change, several), and pass the review on to the user. You never review the code yourself, and nothing is changed: not the code, not the working tree, not the pull request.
13
+
14
+ ## The rules that never bend
15
+
16
+ - **Suggest, never change.** The review returns findings and fixes. Nobody edits, commits, checks out, pushes or comments on anything.
17
+ - **Every finding has a fix.** Each problem comes with a concrete change to make, in the project's own language and idiom.
18
+ - **Evidence, not guesses.** Each finding points to a file and line and says how it fails. What depends on code or config the teamlead could not see is marked as an assumption.
19
+ - **Relay, do not edit.** You pass the findings on as the teamlead gave them. Do not add, drop, merge or soften any. (For a large change the lead teamlead merges the slices' findings; you relay its merged review.)
20
+
21
+ ## Files
22
+
23
+ | File | Purpose |
24
+ |---|---|
25
+ | `references/review-guide.md` | How the teamlead reviews: scope, severities, finding format, verdict |
26
+ | `references/security.md` | Security checklist, by OWASP Top 10 category |
27
+ | `references/performance-and-correctness.md` | Performance and correctness checklist |
28
+ | `references/large-changes.md` | How a change of more than 100 files is split among teamlead reviewers and merged into one review |
29
+
30
+ Nothing is written into the project. The review is given in the conversation.
31
+
32
+ ## Codex runner
33
+
34
+ On Codex, use [`references/codex-runner.md`](references/codex-runner.md). This workflow is deliberately stateless: its single read-only review dispatch is safe to restart after an interruption.
35
+
36
+ ## Steps
37
+
38
+ 1. **Target.** Work out what to review from the request:
39
+
40
+ | Request gives | Target |
41
+ |---|---|
42
+ | A pull request link (or a number, for the current repository) | That pull request |
43
+ | A branch name | The branch against the base branch |
44
+ | A commit, or a range `a..b` | Those commits |
45
+ | Files or folders | Those files as they are, in full, not a diff |
46
+ | Nothing | The uncommitted changes (`git status --porcelain`); if there are none, the current branch against the base branch |
47
+
48
+ The base branch is the target of `git symbolic-ref --short refs/remotes/origin/HEAD` when it exists, otherwise `main` or `master`. If the target is still empty (no changes, an empty branch, a path that does not exist), tell the user and stop. When the request asks for one area only (for example "only security"), pass that on as the focus; otherwise the focus is everything.
49
+ 2. **Pull request access.** For a pull request, check that `gh` works (`gh auth status`) and that the pull request exists (`gh pr view <link> --json number`). If either fails, tell the user what is missing and stop.
50
+ 3. **Size the change.** Count the reviewable files of the target as `references/large-changes.md` says. With more than 100, review it as that file says (its split, slice and merge steps replace the single call below, with the same prompt for every teamlead call), and go to step 4 with the merged review. With 100 or fewer, continue.
51
+ 4. **Review.** Call `levi-teamlead` once, with this prompt filled in:
52
+
53
+ ```text
54
+ Review this code as the gate before merge. Change nothing.
55
+
56
+ Target: <the target from step 1, exact>
57
+ How to read it: <the commands for this kind of target, from the table below>
58
+ Focus: <everything | the area the user asked for>
59
+ What the user said about it: <the request, word for word>
60
+
61
+ Follow <this skill's folder>/references/review-guide.md and the two checklists next to it.
62
+ Read the project code around the change (callers, schema, configuration, conventions) to judge it.
63
+ Do not create, edit or delete any file, do not check out, commit or push, and do not post anything to the pull request.
64
+ Return the review in your reply, in the format the guide gives, in the language of the user's request.
65
+ ```
66
+
67
+ | Target | How to read it |
68
+ |---|---|
69
+ | Pull request | `gh pr view <link> --json title,body,baseRefName,headRefOid,changedFiles,files,url` and `gh pr diff <link>`. Full files: if it belongs to this repository, `git fetch origin pull/<number>/head`, then `git show <headRefOid>:<path>`; otherwise `gh api "repos/<owner>/<repo>/contents/<path>?ref=<headRefOid>" -H "Accept: application/vnd.github.raw"` |
70
+ | Branch | `git diff <base>...<branch>`, and `git show <branch>:<path>` for full files |
71
+ | Commits | `git show <commit>` or `git diff <a>..<b>` |
72
+ | Files or folders | The files themselves |
73
+ | Uncommitted changes | `git diff HEAD` and the untracked files `git status --porcelain` lists |
74
+
75
+ 5. **Relay.** Give the user the teamlead's review: the verdict, then the findings from critical to suggestion, each with its location, the problem, how it fails and the suggested fix. Then the checks it could not make, and its questions. If the teamlead was BLOCKED or needed context, tell the user what it needs.
76
+
77
+ ## When another usecase reviews code
78
+
79
+ A usecase that has the teamlead review code (for example `create-feature` and `fix-bug`) uses the same criteria. In its teamlead prompt, it:
80
+
81
+ - names the change to review (for example "everything that differs from commit `<sha>`") and the context it is judged against (spec, plan, designs);
82
+ - tells the teamlead to follow `levi-code-review/references/review-guide.md` and its checklists (in the folder next to its own skill folder);
83
+ - says where the findings go (for example `review.md` and the workflow's schema) and which ones block;
84
+ - counts the reviewable files of the change, and when there are more than 100 reviews it in slices and merges the findings, as `references/large-changes.md` says. Only the lead's merge writes the review file; the slice reviewers write nothing.
85
+
86
+ The calling usecase's own rules come first: where the review is written, what blocks, and what may not be changed (for example locked tests). This usecase's rule of writing nothing applies only when it runs by itself.
@@ -0,0 +1,5 @@
1
+ # Codex runner
2
+
3
+ This is the one Codex usecase that deliberately has no `run.json`: every dispatch is read-only and creates no project artifacts. Resolve the target and pull-request access checks first, size the change, then dispatch the installed named teamlead agent: once with the exact review prompt in `SKILL.md` for 100 or fewer reviewable files, or as `large-changes.md` says (a split, the slice reviews at the same time, then a merge) for more.
4
+
5
+ If the turn is interrupted before the review is returned, rerun the same read-only target check, sizing and dispatches. Do not write a checkpoint, comment on the pull request, or modify the working tree. Once the review is returned, relay it unchanged.
@@ -0,0 +1,37 @@
1
+ # Reviewing large changes
2
+
3
+ One reviewer reading hundreds of files skims, and a skimmed review finds a few problems per round, so the author fixes, resubmits and meets the next few. A large change is therefore reviewed in slices by several teamlead calls at the same time, and one lead teamlead merges their findings into a single review. The author then gets everything in one go.
4
+
5
+ Every usecase that has the teamlead review code follows this file, whatever else it says about where the review goes and what blocks. It applies to every review round, not only the first.
6
+
7
+ Team members never call each other, so the **usecase that runs the review** (the workflow or the skill you are following) does the calling and the counting. The teamlead calls below are fresh and independent: each sees only its prompt.
8
+
9
+ ## When it applies
10
+
11
+ Count the **reviewable files** of the change: the changed files, leaving out generated files, lock files, vendored code and build output (the review guide's list).
12
+
13
+ | Reviewable files | Review |
14
+ |---|---|
15
+ | 100 or fewer | One teamlead call, as the usecase says |
16
+ | More than 100 | Slices, as below |
17
+
18
+ Count from the whole change, never from a listing that may be cut off. For a pull request use `gh pr view <link> --json changedFiles` for the number and `gh api --paginate "repos/<owner>/<repo>/pulls/<number>/files" --jq '.[].filename'` for the names (`gh pr view --json files` stops at 100 files, and `gh pr diff` fails on very large diffs: read a pull request from this repository locally, with `git fetch origin pull/<number>/head` and a diff against the merge base).
19
+
20
+ ## Steps
21
+
22
+ 1. **Split.** One `levi-teamlead` call (the lead) gets the target, the file list with the changed lines of each file, and the rule below. It returns the slices: a title, the files, and one line on what the slice shares with the others (an interface, a schema, a config).
23
+ - At most 100 files per slice, and as few slices as that allows.
24
+ - Group by what belongs together: a module or feature with its tests, callers, schema and migrations; one layer of a cross-cutting change. Never by alphabet or by chunks of 100.
25
+ - Every reviewable file is in exactly one slice. Check this yourself before going on; send an incomplete or oversized split back to the lead once, and if it is still wrong, cut the list by directory order into slices of at most 100 files.
26
+ 2. **Review the slices**, one fresh `levi-teamlead` call per slice, all at the same time (in batches when the tool limits how many run at once). Each gets: the same prompt a single review would get (target, how to read it, focus, context, the guide and checklists), its own files, the title and shared-interface line of every other slice, and these rules:
27
+ - Review every file of your slice in full and walk both checklists. Read outside the slice whenever you need context.
28
+ - **Report everything you find, in one pass, whatever the severity.** Nothing is kept back for a later round: the author will fix the whole list at once.
29
+ - Report on your slice's files. When a change in your slice breaks, or relies on, code in another slice, report it on your file and name the other location. A concern that only the other slice's reviewer can settle goes under "Cross-slice".
30
+ - Change nothing and write no file: your reply is the only output. The review guide's finding format applies; give no verdict for the whole change.
31
+ 3. **Merge**, one fresh `levi-teamlead` call (the lead) gets every slice report and the split. It writes the one review the usecase asks for, in the guide's format, with one verdict:
32
+ - Join findings that have one cause (list every location), and give equal problems equal severity across slices.
33
+ - Settle each cross-slice item by reading the code on both sides; keep it as a finding, or drop it with a reason.
34
+ - Re-read the location of every critical finding before keeping it.
35
+ - Keep every valid finding. Add nothing new except what the cross-slice items turn up.
36
+ - A slice that returned nothing usable is called again once. If it still fails, the review is incomplete: the slice goes under "Not checked" and the verdict cannot be Approve (a workflow stops as blocked instead of continuing).
37
+ 4. **Hand over** the merged review to whoever acts on it (the developer, or the user for `code-review`), as one list.