levi-gear 0.5.0 → 0.7.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 (40) hide show
  1. package/README.md +21 -14
  2. package/agents/designer.md +1 -0
  3. package/agents/developer.md +2 -1
  4. package/agents/pm.md +2 -1
  5. package/agents/qa.md +2 -1
  6. package/agents/teamlead.md +1 -0
  7. package/docs/README.md +39 -0
  8. package/docs/authoring-usecases.md +124 -0
  9. package/docs/cli.md +99 -0
  10. package/docs/codex.md +35 -0
  11. package/docs/configuration.md +84 -0
  12. package/docs/contributing.md +46 -0
  13. package/docs/customization.md +45 -0
  14. package/docs/installation.md +82 -0
  15. package/docs/introduction.md +49 -0
  16. package/docs/team.md +143 -0
  17. package/docs/troubleshooting.md +63 -0
  18. package/docs/unattended-runs.md +51 -0
  19. package/docs/updating.md +109 -0
  20. package/docs/usage.md +62 -0
  21. package/docs/usecases.md +471 -0
  22. package/package.json +4 -3
  23. package/src/cli.js +2 -2
  24. package/src/commands/init.js +20 -10
  25. package/src/commands/list.js +1 -1
  26. package/src/commands/update.js +2 -2
  27. package/src/lib/agents.js +6 -1
  28. package/src/lib/desired-state.js +65 -5
  29. package/src/lib/sync.js +1 -1
  30. package/src/lib/tools.js +4 -3
  31. package/src/runtime/codex-checkpoint.mjs +48 -0
  32. package/usecases/_run-rules.md +10 -1
  33. package/usecases/create-feature/SKILL.md +20 -15
  34. package/usecases/create-feature/scripts/lock-tests.mjs +21 -8
  35. package/usecases/create-feature/workflow.js +49 -29
  36. package/usecases/design/SKILL.md +18 -3
  37. package/usecases/fix-bug/SKILL.md +16 -13
  38. package/usecases/fix-bug/workflow.js +47 -28
  39. package/usecases/generate-test-scenarios/SKILL.md +4 -4
  40. package/usecases/generate-test-scenarios/references/test-case-guide.md +1 -1
@@ -8,6 +8,7 @@ const { setField } = require('./frontmatter');
8
8
  const { renderRouter } = require('./router');
9
9
 
10
10
  const QUOTA_CHECK = path.join(__dirname, '..', 'runtime', 'quota-check.mjs');
11
+ const CODEX_CHECKPOINT = path.join(__dirname, '..', 'runtime', 'codex-checkpoint.mjs');
11
12
 
12
13
  // Group keys say which part of the kit a file belongs to; they decide where its hash is
13
14
  // recorded in .levi.json.
@@ -65,7 +66,7 @@ function withRequired(byId, ids) {
65
66
  // The files a clean install of `ids` (and what they require) would contain: Map of
66
67
  // project-relative path to { content, group }. Nothing is written here. Usecases that are a team
67
68
  // role's skill are always installed, since the team always is and its agents rely on them.
68
- function build(kit, ids) {
69
+ function build(kit, ids, targets = ['claude']) {
69
70
  const byId = new Map(kit.usecases.map((u) => [u.id, u]));
70
71
  const out = new Map();
71
72
  const missing = [];
@@ -78,12 +79,71 @@ function build(kit, ids) {
78
79
  }
79
80
  const usecase = byId.get(id);
80
81
  present.push(usecase);
81
- addSkill(out, usecase, kit.runRules);
82
- addAgents(out, usecase.agents, usecaseGroup(id));
82
+ if (targets.includes('claude')) {
83
+ addSkill(out, usecase, kit.runRules);
84
+ addAgents(out, usecase.agents, usecaseGroup(id));
85
+ }
86
+ if (targets.includes('codex')) {
87
+ const root = `.agents/skills/${skillName(id)}`;
88
+ for (const rel of walk(usecase.dir, true)) {
89
+ if (rel === 'workflow.js') continue; // Claude's Workflow runtime is not used by Codex.
90
+ let content = fs.readFileSync(path.join(usecase.dir, rel));
91
+ if (rel === 'SKILL.md') {
92
+ let skill = content.toString('utf8');
93
+ skill = skill.replace('On Claude Code the implementation runs as a Workflow of independent subagents. ', '');
94
+ skill = skill.replace(/ - \*With a Workflow tool \(Claude Code\):\*[\s\S]*? - \*Without a Workflow tool:\* /, ' - ');
95
+ skill = skill.replace(/Continue in the same session with `resumeFromRunId` and a higher `maxRounds`\./g, 'Continue from the saved work folder and increase the round limit.');
96
+ skill = skill.replace(/Claude Code runs `workflow\.js`\./g, 'Run the documented steps with fresh Codex subagents.');
97
+ skill = skill.replace(/The steps (?:the Workflow|`workflow\.js`) runs, and the ones you run when there is no Workflow tool\./g, 'Run the following steps in order.');
98
+ skill = skill.replaceAll('model `opus` and effort `high`', '`"reasoning_effort": "high"` and `"fork_turns": "none"` on `spawn_agent`');
99
+ skill = skill.replace('default model and effort of `levi-designer` (set in its agent file) are', 'default reasoning effort in the `levi-designer` agent file is');
100
+ skill = skill.replaceAll('Model and effort', 'Reasoning effort').replaceAll(/model (?:and|or) effort/g, 'reasoning effort');
101
+ const rules = kit.runRules.split('### Quota guard')[0]
102
+ .replace('among the opening answers of the handoff report', 'in the checkpoint summary for the opening round');
103
+ const runFolder = id === 'code-review'
104
+ ? 'a unique directory in the operating system temporary directory, outside the project'
105
+ : 'a unique run folder docs/levi-runs/<slug>-<unique-id>/';
106
+ content = joinSections(skill, rules, '### Codex checkpoint and recovery',
107
+ `Before doing work, create ${runFolder} and use scripts/codex-checkpoint.mjs from this skill directory. Prepare a JSON file with {"usecase":"${id}","request":"<user request>"}, then run \`node <skill-dir>/scripts/codex-checkpoint.mjs init <run-folder>/checkpoint.json < <json-file>\`. Do not include secrets. Record the checkpoint path for the user.`,
108
+ 'Before starting each numbered stage, and after each stage or build/review round, prepare JSON with status (running, interrupted, blocked, waiting_user, or complete), stage, summary, and next (the exact next action, including artifact and lock paths), then run `node <skill-dir>/scripts/codex-checkpoint.mjs save <run-folder>/checkpoint.json < <json-file>`. Never mark a stage complete before validating its artifacts. Preserve work, test locks and checkpoint when interrupted, blocked or waiting.',
109
+ 'As soon as the user answers the opening questions, save the non-secret answers and the work folder path in the checkpoint summary. For a usecase with browser tests, also record the choice and any scope in `docs/levi/<slug>/choices/user-browser-tests.md` at that point.',
110
+ 'On resume, read the checkpoint history, the work folder and the entries in `docs/levi/<slug>/choices/` for this run when present. Use `user-browser-tests.md` to restore `browserTests` and the exact wording of any `browserScope`. Reuse the opening answers without asking those questions again. Check the current git state, verify the locked tests before making changes, and continue at the recorded action without repeating completed stages. If the state is ambiguous, report it and ask rather than guessing.',
111
+ 'Only mark complete after all gates and reports succeed. Remove temporary JSON input files and keep the checkpoint. If required subagents or tools are unavailable, record blocked and report it.');
112
+ }
113
+ if (rel === 'SKILL.md') content += '\nA running stage is not evidence that its subagent completed. On resume, first establish that the previous coordinator is no longer active. If an earlier run stopped with status running, record status interrupted; report that the cause is unknown unless there is direct evidence. Check whether every required artifact exists and was validated. If not, rerun that stage with the appropriate fresh subagent before advancing, while preserving existing user files and test locks. Never infer success from a scheduled next action. Before dispatching a subagent, checkpoint that the stage is in progress and name the subagent and its expected artifacts; only checkpoint the next stage after it finishes and its results are validated. While waiting, check the agent status with the available collaboration tools, distinguish still running from failed, and report meaningful progress. If an agent fails or cannot complete, save the error and the recovery action as blocked; do not assume success. Never start a second coordinator while the original is still active.\n';
114
+ if (rel === 'SKILL.md') content += '\nWhen cleaning up workflow-owned binary files such as XLSX snapshots, use a filesystem command appropriate for the platform; text patch tools cannot delete binary files. Delete only paths the workflow owns and only after the relevant gates have passed.\n';
115
+ put(out, `${root}/${rel}`, content, usecaseGroup(id));
116
+ }
117
+ put(out, `${root}/agents/openai.yaml`, 'policy:\n allow_implicit_invocation: false\n', usecaseGroup(id));
118
+ put(out, `${root}/scripts/codex-checkpoint.mjs`, fs.readFileSync(CODEX_CHECKPOINT), usecaseGroup(id));
119
+ for (const agent of usecase.agents) put(out, `.codex/agents/${agent.name}.toml`, codexAgent(agent), usecaseGroup(id));
120
+ }
121
+ }
122
+ if (targets.includes('claude')) {
123
+ addRouter(out, present, kit.team);
124
+ addAgents(out, kit.team, 'team', (agent) => withRoleSkills(agent, present, SKILL_DIR));
125
+ }
126
+ if (targets.includes('codex')) {
127
+ if (present.length) {
128
+ const router = renderRouter('.agents/skills', present, kit.team)
129
+ .replaceAll('/levi-<usecase>', '$levi-<usecase>')
130
+ .replace('## Steps\n', `## Resume\n\nWhen the user asks to resume a levi run, locate its checkpoint under docs/levi-runs/ or use the checkpoint path supplied by the user. If several incomplete runs match, ask which one; do not guess. Read the checkpoint and select the usecase named in it. Read that skill and follow its Codex checkpoint and recovery instructions. Do not start a new run or perform intake again. If the checkpoint is complete, say so and stop. Code-review checkpoints are outside the project; require the user to supply their path.\n\n## Steps\n`);
131
+ put(out, '.agents/skills/levi/SKILL.md', router, 'router');
132
+ put(out, '.agents/skills/levi/agents/openai.yaml', 'policy:\n allow_implicit_invocation: false\n', 'router');
133
+ }
134
+ for (const agent of kit.team) put(out, `.codex/agents/${agent.name}.toml`, codexAgent(withRoleSkills(agent, present, '.agents/skills')), 'team');
83
135
  }
84
- addRouter(out, present, kit.team);
85
- addAgents(out, kit.team, 'team', (agent) => withRoleSkills(agent, present, SKILL_DIR));
86
136
  return { files: out, missing, ids: present.map((u) => u.id) };
87
137
  }
88
138
 
139
+ function codexAgent(agent) {
140
+ const fields = [
141
+ `name = ${JSON.stringify(agent.name)}`,
142
+ `description = ${JSON.stringify(`${agent.description} Only use when a levi workflow delegates to this agent.`)}`,
143
+ ];
144
+ if (agent.effort) fields.push(`model_reasoning_effort = "${agent.effort === 'max' ? 'xhigh' : agent.effort}"`);
145
+ fields.push(`developer_instructions = ${JSON.stringify(agent.body.trim())}`);
146
+ return fields.join('\n') + '\n';
147
+ }
148
+
89
149
  module.exports = { build, usecaseGroup };
package/src/lib/sync.js CHANGED
@@ -101,7 +101,7 @@ function recordFiles(actions, ids) {
101
101
  // Brings the project in line with the kit for `ids`, touching only files the user
102
102
  // has not changed. `previous` is the stored config. With dryRun nothing is written.
103
103
  function sync(projectDir, ids, previous, { force = false, dryRun = false } = {}) {
104
- const desired = build(loadKit(), ids);
104
+ const desired = build(loadKit(), ids, previous.targets || ['claude']);
105
105
  const actions = plan(projectDir, desired, trackedFiles(previous), force);
106
106
  if (!dryRun) apply(projectDir, actions);
107
107
  return { actions, missing: desired.missing, ...recordFiles(actions, desired.ids) };
package/src/lib/tools.js CHANGED
@@ -1,4 +1,4 @@
1
- // levi installs for Claude Code only: skills go to .claude/skills, subagents to .claude/agents.
1
+ // Claude Code's installation paths and agent renderer. Codex artifacts are built separately.
2
2
  const SKILL_DIR = '.claude/skills';
3
3
  const AGENT_DIR = '.claude/agents';
4
4
 
@@ -10,8 +10,8 @@ function agentDescription(agent) {
10
10
  return `${text} Used only when ${by} delegates to it; never select it for other requests.`;
11
11
  }
12
12
 
13
- // Tool-neutral capabilities and model tiers (see agents.js), mapped to Claude Code. Omitting
14
- // `tools` keeps the defaults, including MCP servers, which an explicit list would cut off.
13
+ // Tool-neutral capabilities and model tiers (see agents.js), mapped to Claude Code. `effort` is passed as is.
14
+ // Omitting `tools` keeps the defaults, including MCP servers, which an explicit list would cut off.
15
15
  const CLAUDE_TOOLS = { read: ['Read', 'Grep', 'Glob'], edit: ['Edit', 'Write'], execute: ['Bash'], web: ['WebFetch', 'WebSearch'] };
16
16
  const CLAUDE_MODELS = { strong: 'opus', standard: 'sonnet', fast: 'haiku' };
17
17
 
@@ -19,6 +19,7 @@ function renderAgent(agent) {
19
19
  const extra = [];
20
20
  if (agent.tools) extra.push(`tools: ${agent.tools.flatMap((t) => CLAUDE_TOOLS[t]).join(', ')}`);
21
21
  if (agent.model) extra.push(`model: ${CLAUDE_MODELS[agent.model]}`);
22
+ if (agent.effort) extra.push(`effort: ${agent.effort}`);
22
23
  return ['---', `name: ${agent.name}`, `description: ${JSON.stringify(agentDescription(agent))}`, ...extra, '---', '', agent.body.trim(), ''].join('\n');
23
24
  }
24
25
 
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ // Small durable record for a Codex workflow. It records progress; it does not run agents.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ const [command, file] = process.argv.slice(2);
7
+ function fail(message) { throw new Error(message); }
8
+ function read() {
9
+ const state = JSON.parse(fs.readFileSync(file, 'utf8'));
10
+ if (state.version !== 1 || typeof state.usecase !== 'string' || !Array.isArray(state.history)) fail('invalid checkpoint');
11
+ return state;
12
+ }
13
+ function input() { return JSON.parse(fs.readFileSync(0, 'utf8')); }
14
+ function write(state, exclusive = false) {
15
+ fs.mkdirSync(path.dirname(file), { recursive: true });
16
+ if (exclusive) return fs.writeFileSync(file, JSON.stringify(state, null, 2) + '\n', { flag: 'wx' });
17
+ const temp = `${file}.${process.pid}.tmp`;
18
+ fs.writeFileSync(temp, JSON.stringify(state, null, 2) + '\n', { flag: 'wx' });
19
+ try { fs.renameSync(temp, file); } finally { if (fs.existsSync(temp)) fs.unlinkSync(temp); }
20
+ }
21
+ try {
22
+ if (!file) fail('usage: codex-checkpoint.mjs init|save|status <file>; JSON on stdin for init and save');
23
+ if (command === 'init') {
24
+ const data = input();
25
+ if (typeof data.usecase !== 'string' || !data.usecase || typeof data.request !== 'string') fail('init requires usecase and request');
26
+ const state = { version: 1, usecase: data.usecase, request: data.request, status: 'running', stage: 'intake', history: [], updatedAt: new Date().toISOString() };
27
+ write(state, true);
28
+ console.log(JSON.stringify(state));
29
+ } else if (command === 'save') {
30
+ const data = input();
31
+ if (!['running', 'interrupted', 'blocked', 'waiting_user', 'complete'].includes(data.status) || typeof data.stage !== 'string' || typeof data.next !== 'string' || typeof data.summary !== 'string') fail('save requires status, stage, summary and next');
32
+ const lock = `${file}.lock`;
33
+ fs.mkdirSync(lock); // Fail closed on concurrent writes, including abandoned locks.
34
+ try {
35
+ const state = read();
36
+ if (state.status === 'complete') fail('a completed run cannot be changed');
37
+ state.status = data.status;
38
+ state.stage = data.stage;
39
+ state.next = data.next;
40
+ state.summary = data.summary;
41
+ state.updatedAt = new Date().toISOString();
42
+ state.history.push({ status: data.status, stage: data.stage, summary: data.summary, next: data.next, at: state.updatedAt });
43
+ write(state);
44
+ console.log(JSON.stringify(state));
45
+ } finally { fs.rmdirSync(lock); }
46
+ } else if (command === 'status') console.log(JSON.stringify(read(), null, 2));
47
+ else fail('unknown command');
48
+ } catch (error) { console.error(error.message); process.exitCode = 2; }
@@ -19,6 +19,15 @@ When the work yields several acceptable options and picking one can be undone ch
19
19
  - Keep the rejected options reachable: files go in an `alternatives/` folder next to the deliverable; anything else is described in the entry.
20
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
21
 
22
+ ### Browser tests are optional, asked once
23
+
24
+ Any step that opens a browser to test (an E2E runner, Playwright, a browser project of Vitest, a browser tool driven by QA) is optional, because it is slow. The render check of `levi-design` is not a test and is not covered. A usecase with such a step asks the user once, in the first round of questions of the run, with the other opening questions. When nothing else needs asking the round holds this question alone: do not skip the round because there is nothing else to ask. Skip the question only when the request itself already says whether to run them. Never ask it again, not even when the run is resumed.
25
+
26
+ - **Question:** "Run browser tests?" Options: "Do not run browser tests (Recommended)", with the reason that it is much faster while unit and integration tests and the review still run and QA still writes the test cases to run later; and "Run the full E2E suite". Free text is allowed: when the user answers another way (for example, only some cases), follow it. An answer that amounts to running nothing is the first option.
27
+ - **Record the answer:** in `docs/levi/<slug>/choices/user-browser-tests.md`, as any other choice (the question, the pick, the alternative, how to change it), and among the opening answers of the handoff report, so that a resumed run reads it and does not ask again.
28
+ - **Pass it on:** when the usecase runs a workflow script, as `args.browserTests` (`true` or `false`; a missing value counts as `false`) and, when the user limited the run, `args.browserScope` with their words. A run done by hand applies it at the same steps.
29
+ - **When it is off:** the browser step and every step that exists only because of it (fixing what it found, running the cases again) are left out, and nothing else opens a browser either: the tests written in the run and the test suite run as a gate leave out the tests that do. QA still writes the test cases, and they stay in the deliverables without a result. The final report has the line "Browser tests: not run (the user chose this)" and lists every test case that was not run, with its ID and title. For a limited run the line says that the tests were partly run and what the user chose, and the list holds the cases left out.
30
+
22
31
  ### Quota guard
23
32
 
24
33
  Applies to every run with more than one stage. Script paths are relative to this skill's folder.
@@ -29,7 +38,7 @@ Applies to every run with more than one stage. Script paths are relative to this
29
38
  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.` Run `CronList` first, to avoid a duplicate; then `CronCreate` (load it with `ToolSearch` if it is deferred), recurring, cron `7 */2 * * *`, with that prompt. If `CronCreate` is not available, tell the user in your next message that the run will not resume on its own, and go on.
30
39
  **Handoff report.** Exactly one file, `docs/breakpoints/handoff.md` (create the folder if missing). It is overwritten whole every time it is written: the previous content belongs to an earlier interruption and is replaced, except that unfinished items from it that are still unfinished must be carried into the new one. It must be enough on its own: the next session may be this same session, or another agent, and it will read only this file, with no chat history, no skills and no scheduler. So write it from scratch for a reader who knows nothing, in the user's language, with only what is true now, no filler, no references to "above" or "as discussed", and every path relative to the project root. Sections, in this order:
31
40
  - *Status line:* the first line, `Status: interrupted | complete`, then the date, time and the usage reading (`usedPercent`, `resetsAt`).
32
- - *Goal and request:* the original request in the user's words, the usecase and its arguments, and the answers given in the opening questions.
41
+ - *Goal and request:* the original request in the user's words, the usecase and its arguments, and the answers given in the opening questions, including the browser-tests choice and its scope when the usecase asks it.
33
42
  - *Project context:* what the project is, the stack, the branch, how to build and test it, and the files and folders an agent must read first (specs, plans, designs, `CLAUDE.md`, the work folder).
34
43
  - *Progress:* a stage table with status `done`, `in progress` or `not started`, each with a one-line result; for `in progress`, exactly where it stopped and what remains in it.
35
44
  - *Done:* the deliverables made so far (path, what it is, whether it is verified), decisions taken and why, and the commands run with their result (tests, builds, checks).
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: levi-create-feature
3
- description: Build a new feature end to end, spec first and test first. Finds or writes the spec (confirmed with the user), the brainstorming plan and, for UI work, the designs; then the developer writes unit and feature tests and QA writes test cases (Markdown and Excel), both from the spec and reviewed against it; the tests are locked, only QA may change its test cases, and the developer writes the code until every test passes, the teamlead approves the code review, and then QA passes every scenario end to end in a headless browser. Tests and test cases are never changed to make them pass. On Claude Code the implementation runs as a Workflow of independent subagents. Fits requests such as "build feature X", "implement X", "add X to the app", "triển khai tính năng X", "thêm tính năng X".
3
+ description: Build a new feature end to end, spec first and test first. Finds or writes the spec (confirmed with the user), the brainstorming plan and, for UI work, the designs; then the developer writes unit and feature tests and QA writes test cases (Markdown and Excel), both from the spec and reviewed against it; the tests are locked, only QA may change its test cases, and the developer writes the code until every test passes, the teamlead approves the code review, and, when the user opts in, QA then passes every scenario end to end in a headless browser (browser tests are slow, so the user is asked once at the start, the recommended answer is to skip them, and the test cases are written to be run later). Tests and test cases are never changed to make them pass. On Claude Code the implementation runs as a Workflow of independent subagents. Fits requests such as "build feature X", "implement X", "add X to the app", "triển khai tính năng X", "thêm tính năng X".
4
4
  argument-hint: "<the feature to build, and the spec if you have one>"
5
5
  requires: spec-writing, brainstorming, design, code-review, generate-test-scenarios
6
6
  ---
@@ -12,7 +12,7 @@ Build a feature the spec-driven way: **the spec decides, the tests and scenarios
12
12
  The work has two halves:
13
13
 
14
14
  - **Prepare** (steps 1 to 5), here in the conversation, because it needs the user: the spec, the brainstorming plan and the designs. It reuses the `spec-writing`, `brainstorming` and `design` usecases.
15
- - **Implement** (step 6), without the user: tests, scenarios, code, end-to-end runs and code review. Every agent call is a fresh, independent subagent that sees only the files it is given, never the conversation or another agent's reasoning. Claude Code runs `workflow.js`.
15
+ - **Implement** (step 6), without the user: tests, scenarios, code, code review and, only when the user chose them, end-to-end runs in a browser. Every agent call is a fresh, independent subagent that sees only the files it is given, never the conversation or another agent's reasoning. Claude Code runs `workflow.js`.
16
16
 
17
17
  ## The rules that never bend
18
18
 
@@ -29,7 +29,7 @@ The work has two halves:
29
29
  | `docs/brainstorming/<plan>.md` | PM | The brainstorming plan |
30
30
  | `docs/designs/<design>/` | Designer | The designs, for UI work |
31
31
  | Unit and feature tests, in the framework's folders | Developer | **Deliverable.** Locked once reviewed |
32
- | `docs/tests/<base>.md`, `docs/tests/<base>.xlsx` | QA | **Deliverable.** The test cases with their PASS or FAIL result, in the format of `generate-test-scenarios`. Only QA changes them |
32
+ | `docs/tests/<base>.md`, `docs/tests/<base>.xlsx` | QA | **Deliverable.** The test cases with the PASS or FAIL result of each case that was run, in the format of `generate-test-scenarios`. Only QA changes them |
33
33
  | Application code, migrations | Developer, Teamlead | **Deliverable.** The feature |
34
34
  | `docs/levi/<slug>/tasks.md` | Teamlead | Scratch: execution plan and the interfaces tests and code share. Deleted at the end |
35
35
  | `docs/levi/<slug>/review.md` | Teamlead | Scratch: code review findings. Deleted at the end |
@@ -42,7 +42,7 @@ The work has two halves:
42
42
 
43
43
  1. **Intake.** The request is the feature. If it is empty, ask what to build and stop. Derive the slug. Note any spec the user attached or pointed to (a path, a link, "the spec in ...").
44
44
 
45
- **Opening round.** Before any flow starts, list the candidates for the spec (`docs/specs/`), the plan (`docs/brainstorming/`) and, when the feature has a user interface, the designs (`docs/designs/`), and ask every confirmation below in one round together with anything else unclear in the request, as the run rules say. Steps 2 to 4 then use these answers instead of asking one at a time. The flows they run ask only what they cannot know before they start (the PM's open questions about the spec); after this and those rounds the run goes on alone.
45
+ **Opening round.** Before any flow starts, list the candidates for the spec (`docs/specs/`), the plan (`docs/brainstorming/`) and, when the feature has a user interface, the designs (`docs/designs/`), and ask every confirmation below in one round together with anything else unclear in the request, as the run rules say. **Always add the browser-tests question** ("Browser tests are optional, asked once" in the run rules below): it goes in this round even when nothing else needs asking. Steps 2 to 4 then use these answers instead of asking one at a time. The flows they run ask only what they cannot know before they start (the PM's open questions about the spec); after this and those rounds the run goes on alone.
46
46
  2. **Spec.**
47
47
  - *The user gave one:* use it.
48
48
  - *Otherwise:* list `docs/specs/` and match files against the feature by name, title and goal. When one or more look like the spec for this feature, ask the user to confirm (in the opening round), in one question: each candidate (path and title) as an option, the most likely first, plus "None of these: write a new spec". Never use a candidate the user did not confirm.
@@ -50,7 +50,7 @@ The work has two halves:
50
50
  - **The spec must be Ready.** If its Status is Draft, its open questions would have to be guessed, so do not implement yet. Ask the user to settle them, and run the `spec-writing` flow in update mode with the answers. If the user prefers to leave a point out, that is an answer too: the PM moves it to Out of scope. Continue only when the Status is Ready.
51
51
  3. **Brainstorming plan.** List `docs/brainstorming/` and match plans against the feature and the spec. One clear match: use it, and say which in one line. Two or more equally plausible: ask the user which one (or "none") in the opening round. None: run the `brainstorming` flow, with the feature and the spec, and use the plan it writes.
52
52
  4. **Designs.** Decide from the spec whether the feature has a user interface (screens, pages, forms, components, visible states). If it has none, skip this step. If it has, list `docs/designs/` and match folders against the feature: one clear match is used; two or more plausible ones, ask the user in the opening round; none: run the `design` flow with the feature as subject and the spec as context, and use the folder it writes.
53
- 5. **Get ready.** Delete `docs/levi/<slug>/locked/` and `qa-snapshot/` if an earlier run left them. Work out the feature ID and the output base `<base>` of the test cases from the spec, as the "Features, IDs and file names" table of `levi-generate-test-scenarios/SKILL.md` says. Say in a few lines what will be used (spec, plan, designs) and that implementation starts now.
53
+ 5. **Get ready.** Delete `docs/levi/<slug>/locked/` and `qa-snapshot/` if an earlier run left them. Work out the feature ID and the output base `<base>` of the test cases from the spec, as the "Features, IDs and file names" table of `levi-generate-test-scenarios/SKILL.md` says. Write the browser-tests answer to `docs/levi/<slug>/choices/user-browser-tests.md`, as the run rules say. Say in a few lines what will be used (spec, plan, designs), whether browser tests will run, and that implementation starts now.
54
54
  6. **Implement.**
55
55
  - *With a Workflow tool (Claude Code):* call it with `scriptPath` set to `workflow.js` in this skill's folder, and `args`:
56
56
 
@@ -63,34 +63,39 @@ The work has two halves:
63
63
  "designs": "docs/designs/<design>/ (omit when there is no UI)",
64
64
  "featureId": "<the feature ID>",
65
65
  "testBase": "docs/tests/<base>",
66
+ "browserTests": <true or false>,
67
+ "browserScope": "<the user's words, only when they limited which cases to run>",
66
68
  "skillDir": "<this skill's folder, relative to the project root>"
67
69
  }
68
70
  ```
69
71
 
72
+ `browserTests` is the user's answer to the opening question: `false` when they chose not to run browser tests (also the value when the answer is missing). Omit `browserScope` unless the user limited the run.
73
+
70
74
  The script runs the steps under [Implementation](#implementation) below and returns a result with a `status`. Follow its progress with the user only when they ask.
71
75
  - *Without a Workflow tool:* run the steps under [Implementation](#implementation) yourself, in order, each agent call as a new subagent call that gets only the paths and instructions written there.
72
76
  7. **Act on the result.**
73
- - `done`: go to step 8.
77
+ - `done`: go to step 8. When `browserTests` was off, the result lists the test cases that were not run (`notRun`).
74
78
  - `spec_questions`: the spec is silent or unclear on a point the tests depend on. Ask the user the questions in one round, run the `spec-writing` flow in update mode with the answers, then run step 6 again from the start.
75
79
  - `blocked`: something outside the code stops the work (the app cannot start, a service or a credential is missing, an agent could not finish). Tell the user the stage and the detail, and what they need to provide. Keep `docs/levi/<slug>/`. Run step 6 again when they say to.
76
80
  - `stalled`: the build rounds ran out (10 by default) and something still fails. Tell the user what failed last. Continue in the same session with `resumeFromRunId` and a higher `maxRounds`. Tests and test cases still do not change.
77
81
  8. **Clean up.** Delete `docs/levi/<slug>/` (`tasks.md`, `review.md`, `locked/`), then `docs/levi` if it is empty. Keep everything else: spec, plan, designs, tests, test cases with their results, code.
78
- 9. **Report.** Tell the user: the spec, plan and designs used (and which were created in this run); the test files and the command that runs them; the test case files with their result (for example `12/12 PASS`); how many build rounds it took; the review outcome and the suggestions left open; the files changed (from `git status`); and that nothing was committed.
82
+ 9. **Report.** Tell the user: the spec, plan and designs used (and which were created in this run); the test files and the command that runs them; the test case files with their result (for example `12/12 PASS`); how many build rounds it took; the review outcome and the suggestions left open; the files changed (from `git status`); and that nothing was committed. When browser tests did not run (all or part), add the line "Browser tests: not run (the user chose this)", or the partly-run variant, and list every test case that was not run with its ID and title (read the titles from the test case file).
79
83
 
80
84
  ## Implementation
81
85
 
82
- The steps the Workflow runs, and the ones you run when there is no Workflow tool. Every call names its agent; give it the paths of the spec, the plan, the designs and `docs/levi/<slug>/`. When a call returns questions that only the user can answer about the spec, stop with `spec_questions`. When a call is BLOCKED, stop with `blocked`.
86
+ The steps the Workflow runs, and the ones you run when there is no Workflow tool. Every call names its agent, with the model and effort where this section says so; give it the paths of the spec, the plan, the designs and `docs/levi/<slug>/`. When a call returns questions that only the user can answer about the spec, stop with `spec_questions`. When a call is BLOCKED, stop with `blocked`.
83
87
 
84
88
  1. **Baseline.** Record `git rev-parse HEAD` and the files `git status --porcelain` lists, so the review later sees only this run's changes.
85
- 2. **Plan** — `levi-teamlead`. Reads the spec, the plan, the designs and the project. Writes `docs/levi/<slug>/tasks.md`: the interfaces tests and code share (exact names of modules, functions, endpoints, routes, components, data shapes), the test framework and where tests go, and the development tasks from the brainstorming plan with their owners. Returns: every acceptance criterion ID; test groups (each with its criteria and folder) covering every criterion; implementation batches in dependency order, where tasks of one batch do not touch the same files; any test setup the project needs; the command for the new tests and the one for the whole suite; how to start the app for E2E. A criterion left out of every test group goes back to the teamlead.
89
+ 2. **Plan** — `levi-teamlead`. Reads the spec, the plan, the designs and the project. Writes `docs/levi/<slug>/tasks.md`: the interfaces tests and code share (exact names of modules, functions, endpoints, routes, components, data shapes), the test framework and where tests go, and the development tasks from the brainstorming plan with their owners. Returns: every acceptance criterion ID; test groups (each with its criteria and folder) covering every criterion; implementation batches in dependency order, where tasks of one batch do not touch the same files; any test setup the project needs; the command for the new tests and the one for the whole suite (both leave out the tests that open a browser, unless browser tests are on); how to start the app for E2E (only when browser tests are on). A criterion left out of every test group goes back to the teamlead.
86
90
  3. **Test setup** — `levi-developer`, only when the plan says the project cannot run tests yet.
87
91
  4. **Tests and scenarios**, two tracks at the same time:
88
- - *Developer track.* One `levi-developer` call per test group, in parallel, writes unit and feature tests for its criteria, from the spec alone, against the interfaces in `tasks.md`, each test naming the criterion it covers. Then, until approved (at most 5 reviews): run the new tests (they are expected to fail, the feature does not exist yet), and a fresh `levi-teamlead` call reviews the tests against the spec: every criterion covered, every assertion from the spec and nothing beyond it, each test able to fail, one command that runs them. It does not edit them; a `levi-developer` call fixes what it found.
89
- - *QA track.* `levi-qa` writes the test cases from the spec and the designs, without reading code or tests, following `levi-generate-test-scenarios/references/test-case-guide.md`, with the feature ID, the cases file `docs/levi/<slug>/test-cases.json` and the output base `docs/tests/<base>`. Every acceptance criterion is in the refs of at least one case, and every ambiguity it finds comes back as a question. Then, until approved (at most 5 reviews): a fresh `levi-pm` call reviews the test cases against the spec (coverage, exact expected results, nothing invented, runnable from the file alone); `levi-qa` fixes what it found.
92
+ - *Developer track.* One `levi-developer` call per test group, in parallel, writes unit and feature tests for its criteria (none that opens a browser, unless browser tests are on), from the spec alone, against the interfaces in `tasks.md`, each test naming the criterion it covers. Then, until approved (at most 5 reviews): run the new tests (they are expected to fail, the feature does not exist yet), and a fresh `levi-teamlead` call reviews the tests against the spec: every criterion covered, every assertion from the spec and nothing beyond it, each test able to fail, one command that runs them. It does not edit them; a `levi-developer` call fixes what it found.
93
+ - *QA track.* `levi-qa`, called with model `opus` and effort `high`, writes the test cases from the spec and the designs, without reading code or tests, following `levi-generate-test-scenarios/references/test-case-guide.md`, with the feature ID, the cases file `docs/levi/<slug>/test-cases.json` and the output base `docs/tests/<base>`. Every acceptance criterion is in the refs of at least one case, and every ambiguity it finds comes back as a question. Then, until approved (at most 5 reviews): a fresh `levi-pm` call reviews the test cases against the spec (coverage, exact expected results, nothing invented, runnable from the file alone); `levi-qa`, again with model `opus` and effort `high`, fixes what it found.
90
94
  5. **Lock.** `node <skill folder>/scripts/lock-tests.mjs lock docs/levi/<slug>/locked <every test file>`, and the same with `docs/levi/<slug>/qa-snapshot docs/tests/<base>.md docs/tests/<base>.xlsx` for the test cases.
91
- 6. **Build**, in rounds (at most 10 unless raised), until the teamlead approves and every scenario passes:
95
+ 6. **Build**, in rounds (at most 10 unless raised), until the teamlead approves and, when browser tests are on, every scenario passes:
92
96
  1. *Code.* First round: each batch in order, the tasks of a batch in parallel, each by its owner (`levi-developer`, or `levi-teamlead` for schema, migrations and CI/CD). Later rounds: the owners fix exactly what the last round found.
93
- 2. *Gate.* Run `lock-tests.mjs verify docs/levi/<slug>/locked` (it restores any locked file that was changed), then the new tests, then the whole suite. Any restored file, failing test or regression sends the round back to the developer with the failures.
97
+ 2. *Gate.* Run `lock-tests.mjs verify docs/levi/<slug>/locked` (it restores any locked file that was changed), then the new tests, then the whole suite (without the tests that open a browser, unless browser tests are on). Any restored file, failing test or regression sends the round back to the developer with the failures.
94
98
  3. *Review* — once the tests pass, a fresh `levi-teamlead` call reviews the change since the baseline against the spec, `tasks.md` and the designs (correctness, security, performance, fit), following `levi-code-review/references/review-guide.md` and its checklists, writes `review.md` and approves only when no critical or warning finding is left. A change of more than 100 reviewable files is not read by one teamlead: it is split into slices of at most 100 files, reviewed by several fresh `levi-teamlead` calls at the same time, and a lead `levi-teamlead` call merges their reports into the one `review.md`, as `levi-code-review/references/large-changes.md` says. Findings go back to their owners, and the round starts again.
95
- 4. *E2E* — only after the review approves. First `lock-tests.mjs verify docs/levi/<slug>/qa-snapshot`, which undoes any change to the test cases made outside QA. Then `levi-qa` starts the app, runs every case in a headless browser (the project's E2E runner such as Playwright, or a browser tool; through the API or CLI when there is no UI), records PASS or FAIL and the evidence as its test case guide says, and stops the app; the snapshot is then taken again. Any case that is not PASS goes back to the developer with the evidence, and the next round runs code, gate, review and E2E again.
96
- 5. The run is done when the review approves and every case passes.
99
+ 4. *E2E* — only when browser tests are on, and only after the review approves. First `lock-tests.mjs verify docs/levi/<slug>/qa-snapshot`, which undoes any change to the test cases made outside QA. Then `levi-qa` starts the app, runs every case in a headless browser (the project's E2E runner such as Playwright, or a browser tool; through the API or CLI when there is no UI), records PASS or FAIL and the evidence as its test case guide says, and stops the app; the snapshot is then taken again. `levi-qa` keeps its default model and effort here. Any case that is not PASS goes back to the developer with the evidence, and the next round runs code, gate, review and E2E again. When the user limited the run, only the cases they chose are run; the others are reported as not run and do not count against the result.
100
+ *Browser tests off:* skip this step. Once the review approves, run `lock-tests.mjs verify docs/levi/<slug>/qa-snapshot` once more, so that the test cases stay as QA wrote them, and the run is done.
101
+ 5. The run is done when the review approves and, when browser tests are on, every case passes.
@@ -14,9 +14,11 @@ import crypto from 'node:crypto';
14
14
 
15
15
  const RESULT_LINE = /^\s*- \*\*(Status|Evidence):\*\*.*$/gm;
16
16
 
17
- function hash(file) {
18
- let text = fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n');
19
- if (file.endsWith('.md')) text = text.replace(RESULT_LINE, '');
17
+ function hash(file, legacy = false, logicalPath = file) {
18
+ const bytes = fs.readFileSync(file);
19
+ if (!legacy && !logicalPath.endsWith('.md')) return crypto.createHash('sha256').update(bytes).digest('hex');
20
+ let text = bytes.toString('utf8').replace(/\r\n/g, '\n');
21
+ if (logicalPath.endsWith('.md')) text = text.replace(RESULT_LINE, '');
20
22
  return crypto.createHash('sha256').update(text).digest('hex');
21
23
  }
22
24
 
@@ -30,22 +32,33 @@ function lock(dir, paths) {
30
32
  if (!paths.length) throw new Error('nothing to lock');
31
33
  const files = {};
32
34
  for (const file of [...new Set(paths.flatMap(walk))].map((f) => path.normalize(f))) {
33
- const copy = path.join(dir, 'files', file);
35
+ // Keep snapshots out of test discovery (for example Node's **/*.test.js).
36
+ const copy = path.join(dir, 'files', `${file}.levi-snapshot`);
34
37
  fs.mkdirSync(path.dirname(copy), { recursive: true });
35
38
  fs.copyFileSync(file, copy);
36
39
  files[file] = hash(file);
37
40
  }
38
- fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify({ files }, null, 2) + '\n');
41
+ fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify({ version: 2, files }, null, 2) + '\n');
39
42
  console.log(JSON.stringify({ locked: Object.keys(files) }, null, 2));
40
43
  }
41
44
 
42
45
  function verify(dir) {
43
- const { files } = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8'));
46
+ const { files, version } = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8'));
44
47
  const restored = [];
45
48
  for (const [file, expected] of Object.entries(files)) {
46
- if (fs.existsSync(file) && hash(file) === expected) continue;
49
+ const snapshot = path.join(dir, 'files', `${file}.levi-snapshot`);
50
+ const legacy = path.join(dir, 'files', file);
51
+ // Move old snapshots out of test discovery even when the original is intact.
52
+ if (!fs.existsSync(snapshot) && fs.existsSync(legacy) && fs.statSync(legacy).isFile()) fs.renameSync(legacy, snapshot);
53
+ if (!fs.existsSync(snapshot)) throw new Error(`snapshot missing: ${file}`);
54
+ const currentSnapshotHash = hash(snapshot, false, file);
55
+ const oldHash = version !== 2 && currentSnapshotHash !== expected;
56
+ if (currentSnapshotHash !== expected && (!oldHash || hash(snapshot, true, file) !== expected)) {
57
+ throw new Error(`snapshot corrupted: ${file}`);
58
+ }
59
+ if (fs.existsSync(file) && hash(file, oldHash) === expected) continue;
47
60
  fs.mkdirSync(path.dirname(file), { recursive: true });
48
- fs.copyFileSync(path.join(dir, 'files', file), file);
61
+ fs.copyFileSync(snapshot, file);
49
62
  restored.push(file);
50
63
  }
51
64
  console.log(JSON.stringify({ intact: restored.length === 0, restored, checked: Object.keys(files).length }, null, 2));
@@ -1,16 +1,16 @@
1
1
  export const meta = {
2
2
  name: 'levi-create-feature',
3
- description: 'Implement a feature test-first: tests and QA scenarios from the spec, reviewed and locked, then code until every test passes, the teamlead approves the review and every E2E scenario passes',
3
+ description: 'Implement a feature test-first: tests and QA scenarios from the spec, reviewed and locked, then code until every test passes and the teamlead approves the review; when browser tests are on, until every E2E scenario passes too',
4
4
  whenToUse: 'Started by the levi-create-feature skill once the spec, the brainstorming plan and the designs are ready',
5
5
  phases: [
6
6
  { title: 'Plan', detail: 'the teamlead turns the brainstorming plan into an execution plan' },
7
7
  { title: 'Tests', detail: 'developer tests and QA scenarios, written apart and reviewed against the spec' },
8
8
  { title: 'Lock', detail: 'snapshot and hash the tests, and snapshot the test cases as QA wrote them' },
9
- { title: 'Build', detail: 'implement, run the tests, review, then E2E; repeat until the review approves and every scenario passes' },
9
+ { title: 'Build', detail: 'implement, run the tests, review, then E2E when browser tests are on; repeat until the review approves and, with browser tests on, every scenario passes' },
10
10
  ],
11
11
  }
12
12
 
13
- // args: { slug, feature, spec, plan, designs?, featureId?, testBase?, skillDir, maxRounds? } — see the skill's SKILL.md.
13
+ // args: { slug, feature, spec, plan, designs?, featureId?, testBase?, browserTests?, browserScope?, skillDir, maxRounds? } — see the skill's SKILL.md.
14
14
  const A = args || {}
15
15
  const absent = ['slug', 'feature', 'spec', 'plan', 'skillDir'].filter((k) => !A[k])
16
16
  if (absent.length) return { status: 'error', message: `missing args: ${absent.join(', ')}` }
@@ -32,6 +32,14 @@ const LOCK = `node ${A.skillDir}/scripts/lock-tests.mjs`
32
32
  const REVIEW_GUIDE = `${A.skillDir}/../levi-code-review/references/review-guide.md`
33
33
  const MAX_TEST_REVIEWS = 5
34
34
  const MAX_BUILD_ROUNDS = A.maxRounds || 10
35
+ // Browser tests (the E2E run) are slow and optional: the user chooses at the start, and a missing value means no.
36
+ const BROWSER = A.browserTests === true
37
+ const BROWSER_SCOPE = BROWSER && A.browserScope ? String(A.browserScope) : ''
38
+ // QA writes and changes test cases with the strongest setting; running them keeps the agent's default.
39
+ const QA_WRITE = { model: 'opus', effort: 'high' }
40
+
41
+ // With browser tests off, nothing in the run may open a browser: not the new tests, and not the suite the gate runs.
42
+ const NO_BROWSER = BROWSER ? '' : '\n\nBrowser tests are off for this run: write or rely on no test that opens a browser (an E2E runner, Playwright, a browser project of Vitest), and make every test command you return (testCommand and suiteCommand) leave out the tests that do.'
35
43
 
36
44
  const CONTEXT = [
37
45
  `Feature: ${A.feature}`,
@@ -103,6 +111,7 @@ const E2E = obj({
103
111
  status: STATUS,
104
112
  summary: { type: 'string' },
105
113
  results: { type: 'array', items: obj({ id: { type: 'string' }, result: { type: 'string', enum: ['PASS', 'FAIL'] }, evidence: { type: 'string' } }) },
114
+ skipped: { ...STRINGS, description: 'IDs of the cases left out on purpose because of the scope the user set. Empty when no scope was set' },
106
115
  })
107
116
  const IMPL = obj({ status: STATUS, summary: { type: 'string' }, files: STRINGS, blockers: STRINGS })
108
117
  const CODE_REVIEW = obj({
@@ -162,8 +171,8 @@ You are starting the implementation of this feature. Read the spec, the brainsto
162
171
  - criteria: every acceptance criterion ID in the spec.
163
172
  - testGroups: split the unit and feature tests into groups that can be written in parallel, each with the criteria it covers and the folder where the project's framework expects those tests. Every criterion belongs to at least one group.
164
173
  - batches: the implementation tasks in dependency order. Tasks in one batch run in parallel in the same working tree, so they must not touch the same files.
165
- - testSetup when the project cannot run unit and feature tests yet (pick the framework that fits the stack), testCommand, suiteCommand, and how to start the app for end-to-end tests (app.start, app.url, app.notes, including seed data or env it needs).
166
- Ask in questions only what the spec cannot answer.`,
174
+ - testSetup when the project cannot run unit and feature tests yet (pick the framework that fits the stack), testCommand, suiteCommand, and how to start the app for end-to-end tests (app.start, app.url, app.notes, including seed data or env it needs).${BROWSER ? '' : ' Browser tests will not run, so leave app.start, app.url and app.notes empty.'}
175
+ Ask in questions only what the spec cannot answer.${NO_BROWSER}`,
167
176
  { label: 'teamlead:plan', agentType: 'levi-teamlead', schema: PLAN },
168
177
  )
169
178
  for (let i = 0; plan && i < 2; i++) {
@@ -172,7 +181,7 @@ for (let i = 0; plan && i < 2; i++) {
172
181
  if (!uncovered.length) break
173
182
  log(`criteria with no test group: ${uncovered.join(', ')}; asking the teamlead to fix the plan`)
174
183
  plan = await agent(
175
- `${CONTEXT}\n\nYour execution plan in ${TASKS} leaves these acceptance criteria out of every test group: ${uncovered.join(', ')}. Put each into a test group, update ${TASKS}, and return the whole corrected plan.`,
184
+ `${CONTEXT}\n\nYour execution plan in ${TASKS} leaves these acceptance criteria out of every test group: ${uncovered.join(', ')}. Put each into a test group, update ${TASKS}, and return the whole corrected plan.${NO_BROWSER}`,
176
185
  { label: 'teamlead:plan-fix', agentType: 'levi-teamlead', schema: PLAN },
177
186
  )
178
187
  }
@@ -203,7 +212,7 @@ Write the unit tests and feature tests of test group ${g.id} (${g.area}). They c
203
212
  - Every criterion of the group has at least one test, and each test names the criterion it covers (for example "AC-3: ...").
204
213
  - The feature is not built yet, so these tests are expected to fail now. Do not write application code, stubs or fakes of the feature.
205
214
  - Work from the spec alone: do not read ${SCENARIOS} or the tests of other groups. If files from an earlier run exist, bring them in line with the spec.
206
- - After this step the tests are locked: the code will have to pass them and nobody may change them. Get them right now.
215
+ - After this step the tests are locked: the code will have to pass them and nobody may change them. Get them right now.${NO_BROWSER}
207
216
 
208
217
  Return every test file you created or changed (helpers and fixtures included).`,
209
218
  { label: `developer:tests-${g.id}`, phase: 'Tests', agentType: 'levi-developer', schema: WRITTEN },
@@ -231,7 +240,7 @@ Check that:
231
240
  - each test can fail on a real bug; a test that already passes without the feature needs a real reason;
232
241
  - they use the project's framework and the interfaces in ${TASKS}, and one command runs exactly these tests (return it as testCommand).
233
242
 
234
- The tests belong to the developer: do not edit them. Approve only when nothing is left to change.`,
243
+ The tests belong to the developer: do not edit them. Approve only when nothing is left to change.${NO_BROWSER}`,
235
244
  { label: `teamlead:review-tests-${i}`, phase: 'Tests', agentType: 'levi-teamlead', schema: SPEC_REVIEW },
236
245
  )
237
246
  if (!review) return { stop: 'blocked', detail: 'the test review did not complete' }
@@ -240,7 +249,7 @@ The tests belong to the developer: do not edit them. Approve only when nothing i
240
249
  if (questions.length) return { stop: 'spec_questions', questions }
241
250
  if (review.approved) return { files, testCommand }
242
251
  const fixed = await agent(
243
- `${CONTEXT}\n\nThe review of your unit and feature tests against the spec found these problems. Fix each one in the tests, and only these:\n${JSON.stringify(review.issues, null, 2)}\nThe spec decides. Do not write application code. Return every test file of the feature (${files.join(', ')}, plus any you add).`,
252
+ `${CONTEXT}\n\nThe review of your unit and feature tests against the spec found these problems. Fix each one in the tests, and only these:\n${JSON.stringify(review.issues, null, 2)}\nThe spec decides. Do not write application code. Return every test file of the feature (${files.join(', ')}, plus any you add).${NO_BROWSER}`,
244
253
  { label: `developer:fix-tests-${i}`, phase: 'Tests', agentType: 'levi-developer', schema: WRITTEN },
245
254
  )
246
255
  if (fixed) fixed.files.forEach((f) => files.includes(f) || files.push(f))
@@ -261,12 +270,12 @@ Output base: ${TEST_BASE}. If its files exist from an earlier run, they are your
261
270
 
262
271
  On top of the guide:
263
272
  - Every acceptance criterion in ${plan.criteria.join(', ')} is in the refs of at least one case.
264
- - Each case can be run end to end ${plan.hasUi ? 'in a browser' : 'through the API or the CLI'} by someone who has only the rendered file and the running app (${plan.app.url}).
273
+ - Each case can be run end to end ${plan.hasUi ? 'in a browser' : 'through the API or the CLI'} by someone who has only the rendered file and the running app${BROWSER ? ` (${plan.app.url})` : ''}.
265
274
  - Do not record results: they are recorded when the cases are run, after the code is built.
266
275
  - The spec is Ready, so it should settle everything a case needs. Put every ambiguity you find into questions as well.
267
276
 
268
277
  Return the number of cases as scenarioCount.`,
269
- { label: 'qa:scenarios', phase: 'Tests', agentType: 'levi-qa', schema: WRITTEN },
278
+ { label: 'qa:scenarios', phase: 'Tests', agentType: 'levi-qa', schema: WRITTEN, ...QA_WRITE },
270
279
  )
271
280
  if (!written || written.status === 'BLOCKED') return { stop: 'blocked', detail: written ? written.summary : 'QA did not write the scenarios' }
272
281
  let questions = questionsOf(written)
@@ -291,7 +300,7 @@ The file belongs to QA: do not edit it. Approve only when nothing is left to cha
291
300
  written =
292
301
  (await agent(
293
302
  `${CONTEXT}\n\nThe review of ${SCENARIOS} against the spec found these problems. Fix each one, and only these, as your test case guide (${TEST_GUIDE}, "Changing test cases") says, with the cases file ${CASES} and the output base ${TEST_BASE}:\n${JSON.stringify(review.issues, null, 2)}\nThe spec decides. Return the number of cases as scenarioCount.`,
294
- { label: `qa:fix-scenarios-${i}`, phase: 'Tests', agentType: 'levi-qa', schema: WRITTEN },
303
+ { label: `qa:fix-scenarios-${i}`, phase: 'Tests', agentType: 'levi-qa', schema: WRITTEN, ...QA_WRITE },
295
304
  )) || written
296
305
  }
297
306
  return { stop: 'blocked', detail: `the scenarios were not approved after ${MAX_TEST_REVIEWS} reviews` }
@@ -314,6 +323,7 @@ if (!locked || locked.exitCode !== 0) return { status: 'blocked', stage: 'lock',
314
323
  const snapped = await snapshotScenarios()
315
324
  if (!snapped || snapped.exitCode !== 0) return { status: 'blocked', stage: 'lock', detail: snapped ? snapped.summary : 'the test cases could not be snapshotted' }
316
325
  log(`locked ${tests.files.length} test file(s); ${scenarios.scenarioCount} test case(s) kept as QA wrote them`)
326
+ const CASE_IDS = Array.from({ length: scenarios.scenarioCount }, (_, i) => `TC-${FEATURE_ID}-${String(i + 1).padStart(3, '0')}`)
317
327
 
318
328
  const REVIEW_PHASE = 'Build'
319
329
  // ---- review of the change: one teamlead, or slices merged by a lead when the change is large ----
@@ -410,7 +420,7 @@ ${output}`,
410
420
  )
411
421
  }
412
422
 
413
- // ---- 4. Build: implement, tests, review, then E2E, until the review approves and every scenario passes ----
423
+ // ---- 4. Build: implement, tests, review, then E2E when browser tests are on, until the review approves and every scenario passes ----
414
424
 
415
425
  const RULES = LOCKED_RULES(tests.files)
416
426
 
@@ -458,7 +468,11 @@ async function e2e(note) {
458
468
  return agent(
459
469
  `${CONTEXT}
460
470
 
461
- The code was approved in review. Run every test case in ${SCENARIOS} (there are ${scenarios.scenarioCount}) against the running app and record the results, following your test case guide, ${TEST_GUIDE} ("Recording results"), with the cases file ${CASES} and the output base ${TEST_BASE}. Run them ${
471
+ The code was approved in review. Run ${
472
+ BROWSER_SCOPE
473
+ ? `only the test cases in ${SCENARIOS} that the user chose with these words: "${BROWSER_SCOPE}". List the IDs of the others in skipped and do not run them`
474
+ : `every test case in ${SCENARIOS} (there are ${scenarios.scenarioCount})`
475
+ } against the running app and record the results, following your test case guide, ${TEST_GUIDE} ("Recording results"), with the cases file ${CASES} and the output base ${TEST_BASE}. Run them ${
462
476
  plan.hasUi
463
477
  ? "in a headless browser: the project's E2E runner (such as Playwright) or a browser tool you have"
464
478
  : 'through its API or CLI'
@@ -468,6 +482,20 @@ Change no application code. Return the result of every case, by its ID.${note ?
468
482
  )
469
483
  }
470
484
 
485
+ // The result of a finished run. `notRun` lists the test cases that were not run in a browser.
486
+ const finish = (rounds, review, notRun) => ({
487
+ status: 'done',
488
+ rounds,
489
+ tests: tests.files,
490
+ testCommand: tests.testCommand,
491
+ scenarios: { files: SCENARIO_FILES, count: scenarios.scenarioCount },
492
+ browserTests: BROWSER,
493
+ browserScope: BROWSER_SCOPE || undefined,
494
+ notRun,
495
+ review: review.summary,
496
+ suggestions: review.findings.filter((f) => f.severity === 'suggestion'),
497
+ })
498
+
471
499
  phase('Build')
472
500
  let pending = null
473
501
  let last = null
@@ -500,27 +528,19 @@ Check the change against the spec, ${TASKS} and the designs: correctness, securi
500
528
  continue
501
529
  }
502
530
 
503
- // The review approved: QA runs the scenarios end to end.
504
- // Changes to the test cases by anyone but QA are undone before QA runs them; QA's own results are kept after.
531
+ // The review approved. Changes to the test cases by anyone but QA are undone, with browser tests on or off.
505
532
  const restored = await restoreScenarios()
506
533
  if (restored && restored.exitCode !== 0) log('the test cases had been changed outside QA and were restored')
534
+ if (!BROWSER) return finish(round, review, CASE_IDS)
535
+
536
+ // Browser tests on: QA runs the scenarios end to end; QA's own results are kept after.
507
537
  const run = await e2e()
508
538
  if (!run) return { status: 'blocked', stage: 'e2e', detail: 'the E2E run did not complete' }
509
539
  await snapshotScenarios()
510
- const caseIds = Array.from({ length: scenarios.scenarioCount }, (_, i) => `TC-${FEATURE_ID}-${String(i + 1).padStart(3, '0')}`)
540
+ const skipped = new Set(BROWSER_SCOPE ? (run.skipped || []).filter((id) => CASE_IDS.includes(id)) : [])
511
541
  const passed = new Set(run.results.filter((r) => r.result === 'PASS').map((r) => r.id))
512
- const failing = caseIds.filter((id) => !passed.has(id))
513
- if (!failing.length) {
514
- return {
515
- status: 'done',
516
- rounds: round,
517
- tests: tests.files,
518
- testCommand: tests.testCommand,
519
- scenarios: { files: SCENARIO_FILES, count: scenarios.scenarioCount },
520
- review: review.summary,
521
- suggestions: review.findings.filter((f) => f.severity === 'suggestion'),
522
- }
523
- }
542
+ const failing = CASE_IDS.filter((id) => !skipped.has(id) && !passed.has(id))
543
+ if (!failing.length) return finish(round, review, [...skipped])
524
544
  const evidence = failing.map((id) => {
525
545
  const r = run.results.find((x) => x.id === id)
526
546
  return `${id}: ${r ? r.evidence : 'not run'}`